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 | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Symbols/NoPiaIllegalGenericInstantiationSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A NoPiaIllegalGenericInstantiationSymbol is a special kind of ErrorSymbol that represents a
/// generic type instantiation that cannot cross assembly boundaries according to NoPia rules.
/// </summary>
internal class NoPiaIllegalGenericInstantiationSymbol : ErrorTypeSymbol
{
private readonly ModuleSymbol _exposingModule;
private readonly NamedTypeSymbol _underlyingSymbol;
public NoPiaIllegalGenericInstantiationSymbol(ModuleSymbol exposingModule, NamedTypeSymbol underlyingSymbol)
{
_exposingModule = exposingModule;
_underlyingSymbol = underlyingSymbol;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new NoPiaIllegalGenericInstantiationSymbol(_exposingModule, _underlyingSymbol);
}
internal override bool MangleName
{
get
{
Debug.Assert(Arity == 0);
return false;
}
}
public NamedTypeSymbol UnderlyingSymbol
{
get
{
return _underlyingSymbol;
}
}
internal override DiagnosticInfo ErrorInfo
{
get
{
if (_underlyingSymbol.IsErrorType())
{
DiagnosticInfo? underlyingInfo = ((ErrorTypeSymbol)_underlyingSymbol).ErrorInfo;
if ((object?)underlyingInfo != null)
{
return underlyingInfo;
}
}
return new CSDiagnosticInfo(ErrorCode.ERR_GenericsUsedAcrossAssemblies, _underlyingSymbol, _exposingModule.ContainingAssembly);
}
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison)
{
return ReferenceEquals(this, t2);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A NoPiaIllegalGenericInstantiationSymbol is a special kind of ErrorSymbol that represents a
/// generic type instantiation that cannot cross assembly boundaries according to NoPia rules.
/// </summary>
internal class NoPiaIllegalGenericInstantiationSymbol : ErrorTypeSymbol
{
private readonly ModuleSymbol _exposingModule;
private readonly NamedTypeSymbol _underlyingSymbol;
public NoPiaIllegalGenericInstantiationSymbol(ModuleSymbol exposingModule, NamedTypeSymbol underlyingSymbol)
{
_exposingModule = exposingModule;
_underlyingSymbol = underlyingSymbol;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new NoPiaIllegalGenericInstantiationSymbol(_exposingModule, _underlyingSymbol);
}
internal override bool MangleName
{
get
{
Debug.Assert(Arity == 0);
return false;
}
}
public NamedTypeSymbol UnderlyingSymbol
{
get
{
return _underlyingSymbol;
}
}
internal override DiagnosticInfo ErrorInfo
{
get
{
if (_underlyingSymbol.IsErrorType())
{
DiagnosticInfo? underlyingInfo = ((ErrorTypeSymbol)_underlyingSymbol).ErrorInfo;
if ((object?)underlyingInfo != null)
{
return underlyingInfo;
}
}
return new CSDiagnosticInfo(ErrorCode.ERR_GenericsUsedAcrossAssemblies, _underlyingSymbol, _exposingModule.ContainingAssembly);
}
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison)
{
return ReferenceEquals(this, t2);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertyClonedParameterSymbolForAccessors.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SourcePropertyClonedParameterSymbolForAccessors : SourceClonedParameterSymbol
{
internal SourcePropertyClonedParameterSymbolForAccessors(SourceParameterSymbol originalParam, Symbol newOwner)
: base(originalParam, newOwner, originalParam.Ordinal, suppressOptional: false)
{
}
internal override bool IsCallerFilePath => _originalParam.IsCallerFilePath;
internal override bool IsCallerLineNumber => _originalParam.IsCallerLineNumber;
internal override bool IsCallerMemberName => _originalParam.IsCallerMemberName;
internal override int CallerArgumentExpressionParameterIndex => _originalParam.CallerArgumentExpressionParameterIndex;
internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams)
{
return new SourcePropertyClonedParameterSymbolForAccessors(
_originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams),
this.ContainingSymbol);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SourcePropertyClonedParameterSymbolForAccessors : SourceClonedParameterSymbol
{
internal SourcePropertyClonedParameterSymbolForAccessors(SourceParameterSymbol originalParam, Symbol newOwner)
: base(originalParam, newOwner, originalParam.Ordinal, suppressOptional: false)
{
}
internal override bool IsCallerFilePath => _originalParam.IsCallerFilePath;
internal override bool IsCallerLineNumber => _originalParam.IsCallerLineNumber;
internal override bool IsCallerMemberName => _originalParam.IsCallerMemberName;
internal override int CallerArgumentExpressionParameterIndex => _originalParam.CallerArgumentExpressionParameterIndex;
internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams)
{
return new SourcePropertyClonedParameterSymbolForAccessors(
_originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams),
this.ContainingSymbol);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/GotoTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class GotoTests
Inherits FlowTestBase
#Region "ControlFlowPass and DataflowAnalysis"
<Fact()>
Public Sub GotoInLambda()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoInLambda">
<file name="a.vb">
Imports System
Imports System.Linq
Class C1
Sub MAIN()
Dim lists = goo()
lists.Where(Function(ByVal item)
[|GoTo lab1|]
For Each item In lists
item = New myattribute1()
lab1:
Next
Return item.ToString() = ""
End Function).ToList()
End Sub
Shared Function goo() As List(Of myattribute1)
Return Nothing
End Function
End Class
Class myattribute1
Inherits Attribute
Implements IDisposable
Sub dispose() Implements IDisposable.Dispose
End Sub
End Class
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Equal("lists, item", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside))
Assert.Equal("Me, lists, item", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Equal(1, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.False(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact()>
Public Sub GotoInNestedSyncLock()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoInNestedSyncLock">
<file name="a.vb">
Imports System
Imports System.Linq
Delegate Sub MyDelegate(ByRef x As Integer)
Class C1
Shared Sub Main()
SyncLock "a"
[|SyncLock "B"
GoTo lab1
End SyncLock
lab1:|]
Dim x As MyDelegate = Sub(ByRef y As Integer)
lab1:
End Sub
End SyncLock
End Sub
End Class
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Equal(0, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact()>
Public Sub GotoCaseElse()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoCaseElse">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim str As String
Dim flag1 = 1
[|GoTo 2
Select flag1
Case 1 :
1: str = "abc"
Case 2 :
str = "abc"
2: Case Else :
str = "abc"
End Select|]
Console.Write(str)
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut))
Assert.Equal("flag1", GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Equal("str", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Equal("str", GetSymbolNamesJoined(dataFlowResults.WrittenInside))
Assert.Equal("flag1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Equal(0, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact()>
Public Sub InfiniteLoop()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoCaseElse">
<file name="a.vb">
Imports System
Module M
Sub Main()
[|A:
GoTo B
B:
GoTo A|]
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Assert.Equal(0, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.False(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
#End Region
#Region "Semantic API test"
<Fact()>
Public Sub SimpleLabel()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SimpleLabel">
<file name="a.vb">
Module M
Sub Main()
lab1: GoTo lab1
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<WorkItem(543378, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543378")>
<Fact()>
Public Sub DuplicatedLabel()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicatedLabel">
<file name="a.vb">
Module M
Sub Main()
lab1: GoTo lab1
lab1: GoTo lab1
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntaxArray = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToArray()
Dim gotoSyntaxArray = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToArray()
Dim declaredSymbol0 = model.GetDeclaredSymbol(labelStatementSyntaxArray(0))
Dim semanticSummary0 = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntaxArray(0).Label)
Assert.Null(semanticSummary0.Type)
Assert.Null(semanticSummary0.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary0.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary0.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary0.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol0, semanticSummary0.Symbol)
Dim declaredSymbol1 = model.GetDeclaredSymbol(labelStatementSyntaxArray(1))
Dim semanticSummary1 = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntaxArray(1).Label)
Assert.Null(semanticSummary1.Type)
Assert.Null(semanticSummary1.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary1.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary1.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol0, semanticSummary1.Symbol)
Assert.NotEqual(declaredSymbol0, declaredSymbol1)
Assert.Equal(semanticSummary0.Symbol, semanticSummary1.Symbol)
Assert.Equal(semanticSummary0.Symbol.Name, semanticSummary1.Symbol.Name)
End Sub
<Fact()>
Public Sub NumericLabel()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NumericLabel">
<file name="a.vb">
Module M
Sub Main()
0: GoTo 0
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("0", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub SameLabelNameInDifferentScope()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SameLabelNameInDifferentScope">
<file name="a.vb">
Module M
Sub Main()
0: Dim s = Sub()
0: GoTo 0
End Sub
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntaxOuter = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim labelStatementSyntaxInner = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().Last
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbolOuter = model.GetDeclaredSymbol(labelStatementSyntaxOuter)
Dim declaredSymbolInner = model.GetDeclaredSymbol(labelStatementSyntaxInner)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("0", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.NotEqual(Of ISymbol)(declaredSymbolOuter, semanticSummary.Symbol)
Assert.Equal(Of ISymbol)(declaredSymbolInner, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub LabelOnCaseElse()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LabelOnCaseElse">
<file name="a.vb">
Module M
Sub Main()
GoTo 1
Dim x As Integer = 1
Select Case x
Case 1 :
Return
1: Case Else:
x = 2
End Select
Console.Write(x)
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub LabelOnIfElse()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LabelOnIfElse">
<file name="a.vb">
Module M
Sub Main()
GoTo 1
Dim str As String = "Init"
If str = "a"
Return
1: Else If str = "b"
End If
Console.Write(str)
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub GotoLabelDefinedInTryFromCatch()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoLabelDefinedInTryFromCatch">
<file name="a.vb">
Module M
Sub Main()
Try
lab1:
Catch ex As Exception
GoTo lab1
End Try
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub GoToInNestedLambda()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GoToInNestedLambda">
<file name="a.vb">
Module M
Sub Main()
Dim x = Sub()
lab1:
Dim y = Sub()
GoTo lab1
End Sub
End Sub
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Null(semanticSummary.Symbol)
End Sub
#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 Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class GotoTests
Inherits FlowTestBase
#Region "ControlFlowPass and DataflowAnalysis"
<Fact()>
Public Sub GotoInLambda()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoInLambda">
<file name="a.vb">
Imports System
Imports System.Linq
Class C1
Sub MAIN()
Dim lists = goo()
lists.Where(Function(ByVal item)
[|GoTo lab1|]
For Each item In lists
item = New myattribute1()
lab1:
Next
Return item.ToString() = ""
End Function).ToList()
End Sub
Shared Function goo() As List(Of myattribute1)
Return Nothing
End Function
End Class
Class myattribute1
Inherits Attribute
Implements IDisposable
Sub dispose() Implements IDisposable.Dispose
End Sub
End Class
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Equal("lists, item", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside))
Assert.Equal("Me, lists, item", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Equal(1, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.False(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact()>
Public Sub GotoInNestedSyncLock()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoInNestedSyncLock">
<file name="a.vb">
Imports System
Imports System.Linq
Delegate Sub MyDelegate(ByRef x As Integer)
Class C1
Shared Sub Main()
SyncLock "a"
[|SyncLock "B"
GoTo lab1
End SyncLock
lab1:|]
Dim x As MyDelegate = Sub(ByRef y As Integer)
lab1:
End Sub
End SyncLock
End Sub
End Class
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Equal("y", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.WrittenInside))
Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Equal(0, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact()>
Public Sub GotoCaseElse()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoCaseElse">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim str As String
Dim flag1 = 1
[|GoTo 2
Select flag1
Case 1 :
1: str = "abc"
Case 2 :
str = "abc"
2: Case Else :
str = "abc"
End Select|]
Console.Write(str)
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.VariablesDeclared))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.AlwaysAssigned))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsIn))
Assert.Equal(Nothing, GetSymbolNamesJoined(dataFlowResults.DataFlowsOut))
Assert.Equal("flag1", GetSymbolNamesJoined(dataFlowResults.ReadInside))
Assert.Equal("str", GetSymbolNamesJoined(dataFlowResults.ReadOutside))
Assert.Equal("str", GetSymbolNamesJoined(dataFlowResults.WrittenInside))
Assert.Equal("flag1", GetSymbolNamesJoined(dataFlowResults.WrittenOutside))
Assert.Equal(0, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact()>
Public Sub InfiniteLoop()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation name="GotoCaseElse">
<file name="a.vb">
Imports System
Module M
Sub Main()
[|A:
GoTo B
B:
GoTo A|]
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Assert.Equal(0, controlFlowResults.ExitPoints.Count)
Assert.Equal(0, controlFlowResults.EntryPoints.Count)
Assert.False(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
#End Region
#Region "Semantic API test"
<Fact()>
Public Sub SimpleLabel()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SimpleLabel">
<file name="a.vb">
Module M
Sub Main()
lab1: GoTo lab1
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<WorkItem(543378, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543378")>
<Fact()>
Public Sub DuplicatedLabel()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicatedLabel">
<file name="a.vb">
Module M
Sub Main()
lab1: GoTo lab1
lab1: GoTo lab1
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntaxArray = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToArray()
Dim gotoSyntaxArray = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToArray()
Dim declaredSymbol0 = model.GetDeclaredSymbol(labelStatementSyntaxArray(0))
Dim semanticSummary0 = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntaxArray(0).Label)
Assert.Null(semanticSummary0.Type)
Assert.Null(semanticSummary0.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary0.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary0.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary0.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol0, semanticSummary0.Symbol)
Dim declaredSymbol1 = model.GetDeclaredSymbol(labelStatementSyntaxArray(1))
Dim semanticSummary1 = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntaxArray(1).Label)
Assert.Null(semanticSummary1.Type)
Assert.Null(semanticSummary1.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary1.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary1.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary1.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol0, semanticSummary1.Symbol)
Assert.NotEqual(declaredSymbol0, declaredSymbol1)
Assert.Equal(semanticSummary0.Symbol, semanticSummary1.Symbol)
Assert.Equal(semanticSummary0.Symbol.Name, semanticSummary1.Symbol.Name)
End Sub
<Fact()>
Public Sub NumericLabel()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NumericLabel">
<file name="a.vb">
Module M
Sub Main()
0: GoTo 0
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("0", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub SameLabelNameInDifferentScope()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SameLabelNameInDifferentScope">
<file name="a.vb">
Module M
Sub Main()
0: Dim s = Sub()
0: GoTo 0
End Sub
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntaxOuter = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim labelStatementSyntaxInner = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().Last
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbolOuter = model.GetDeclaredSymbol(labelStatementSyntaxOuter)
Dim declaredSymbolInner = model.GetDeclaredSymbol(labelStatementSyntaxInner)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("0", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.NotEqual(Of ISymbol)(declaredSymbolOuter, semanticSummary.Symbol)
Assert.Equal(Of ISymbol)(declaredSymbolInner, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub LabelOnCaseElse()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LabelOnCaseElse">
<file name="a.vb">
Module M
Sub Main()
GoTo 1
Dim x As Integer = 1
Select Case x
Case 1 :
Return
1: Case Else:
x = 2
End Select
Console.Write(x)
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub LabelOnIfElse()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LabelOnIfElse">
<file name="a.vb">
Module M
Sub Main()
GoTo 1
Dim str As String = "Init"
If str = "a"
Return
1: Else If str = "b"
End If
Console.Write(str)
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub GotoLabelDefinedInTryFromCatch()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoLabelDefinedInTryFromCatch">
<file name="a.vb">
Module M
Sub Main()
Try
lab1:
Catch ex As Exception
GoTo lab1
End Try
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim labelStatementSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of LabelStatementSyntax)().ToList().First
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim declaredSymbol = model.GetDeclaredSymbol(labelStatementSyntax)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("lab1", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Label, semanticSummary.Symbol.Kind)
Assert.Equal(Of ISymbol)(declaredSymbol, semanticSummary.Symbol)
End Sub
<Fact()>
Public Sub GoToInNestedLambda()
Dim Compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GoToInNestedLambda">
<file name="a.vb">
Module M
Sub Main()
Dim x = Sub()
lab1:
Dim y = Sub()
GoTo lab1
End Sub
End Sub
End Sub
End Module
</file>
</compilation>)
Dim tree = Compilation.SyntaxTrees.[Single]()
Dim model = Compilation.GetSemanticModel(tree)
Dim gotoSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType(Of GoToStatementSyntax)().ToList().First
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Compilation, gotoSyntax.Label)
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Null(semanticSummary.Symbol)
End Sub
#End Region
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.ru.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="ru" original="../VBCodeStyleResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Удалите это значение при добавлении другого значения.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ru" original="../VBCodeStyleResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Удалите это значение при добавлении другого значения.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Analyzers/CSharp/CodeFixes/UseCompoundAssignment/CSharpUseCompoundAssignmentCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.UseCompoundAssignment;
namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCompoundAssignment), Shared]
internal class CSharpUseCompoundAssignmentCodeFixProvider
: AbstractUseCompoundAssignmentCodeFixProvider<SyntaxKind, AssignmentExpressionSyntax, ExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseCompoundAssignmentCodeFixProvider()
: base(Utilities.Kinds)
{
}
protected override SyntaxToken Token(SyntaxKind kind)
=> SyntaxFactory.Token(kind);
protected override AssignmentExpressionSyntax Assignment(
SyntaxKind assignmentOpKind, ExpressionSyntax left, SyntaxToken syntaxToken, ExpressionSyntax right)
{
return SyntaxFactory.AssignmentExpression(assignmentOpKind, left, syntaxToken, right);
}
protected override ExpressionSyntax Increment(ExpressionSyntax left, bool postfix)
=> postfix
? Postfix(SyntaxKind.PostIncrementExpression, left)
: Prefix(SyntaxKind.PreIncrementExpression, left);
protected override ExpressionSyntax Decrement(ExpressionSyntax left, bool postfix)
=> postfix
? Postfix(SyntaxKind.PostDecrementExpression, left)
: Prefix(SyntaxKind.PreDecrementExpression, left);
private static ExpressionSyntax Postfix(SyntaxKind kind, ExpressionSyntax operand)
=> SyntaxFactory.PostfixUnaryExpression(kind, operand);
private static ExpressionSyntax Prefix(SyntaxKind kind, ExpressionSyntax operand)
=> SyntaxFactory.PrefixUnaryExpression(kind, operand);
protected override bool PreferPostfix(ISyntaxFactsService syntaxFacts, AssignmentExpressionSyntax currentAssignment)
{
// in `for (...; x = x + 1)` we prefer to translate that idiomatically as `for (...; x++)`
if (currentAssignment.Parent is ForStatementSyntax forStatement &&
forStatement.Incrementors.Contains(currentAssignment))
{
return true;
}
return base.PreferPostfix(syntaxFacts, currentAssignment);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.UseCompoundAssignment;
namespace Microsoft.CodeAnalysis.CSharp.UseCompoundAssignment
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseCompoundAssignment), Shared]
internal class CSharpUseCompoundAssignmentCodeFixProvider
: AbstractUseCompoundAssignmentCodeFixProvider<SyntaxKind, AssignmentExpressionSyntax, ExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseCompoundAssignmentCodeFixProvider()
: base(Utilities.Kinds)
{
}
protected override SyntaxToken Token(SyntaxKind kind)
=> SyntaxFactory.Token(kind);
protected override AssignmentExpressionSyntax Assignment(
SyntaxKind assignmentOpKind, ExpressionSyntax left, SyntaxToken syntaxToken, ExpressionSyntax right)
{
return SyntaxFactory.AssignmentExpression(assignmentOpKind, left, syntaxToken, right);
}
protected override ExpressionSyntax Increment(ExpressionSyntax left, bool postfix)
=> postfix
? Postfix(SyntaxKind.PostIncrementExpression, left)
: Prefix(SyntaxKind.PreIncrementExpression, left);
protected override ExpressionSyntax Decrement(ExpressionSyntax left, bool postfix)
=> postfix
? Postfix(SyntaxKind.PostDecrementExpression, left)
: Prefix(SyntaxKind.PreDecrementExpression, left);
private static ExpressionSyntax Postfix(SyntaxKind kind, ExpressionSyntax operand)
=> SyntaxFactory.PostfixUnaryExpression(kind, operand);
private static ExpressionSyntax Prefix(SyntaxKind kind, ExpressionSyntax operand)
=> SyntaxFactory.PrefixUnaryExpression(kind, operand);
protected override bool PreferPostfix(ISyntaxFactsService syntaxFacts, AssignmentExpressionSyntax currentAssignment)
{
// in `for (...; x = x + 1)` we prefer to translate that idiomatically as `for (...; x++)`
if (currentAssignment.Parent is ForStatementSyntax forStatement &&
forStatement.Incrementors.Contains(currentAssignment))
{
return true;
}
return base.PreferPostfix(syntaxFacts, currentAssignment);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharp/FindUsages/CSharpFindUsagesLSPService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.CSharp.FindUsages
{
[ExportLanguageService(typeof(IFindUsagesLSPService), LanguageNames.CSharp), Shared]
internal class CSharpFindUsagesLSPService : AbstractFindUsagesService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpFindUsagesLSPService()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.CSharp.FindUsages
{
[ExportLanguageService(typeof(IFindUsagesLSPService), LanguageNames.CSharp), Shared]
internal class CSharpFindUsagesLSPService : AbstractFindUsagesService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpFindUsagesLSPService()
{
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState>
{
// TODO: Need to estimate amount of elements for this map and pass that value to the constructor.
protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>();
private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything);
private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>();
private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt;
public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt
=> _embeddedTypesManagerOpt;
// Gives the name of this module (may not reflect the name of the underlying symbol).
// See Assembly.MetadataName.
private readonly string _metadataName;
private ImmutableArray<Cci.ExportedType> _lazyExportedTypes;
/// <summary>
/// The compiler-generated implementation type for each fixed-size buffer.
/// </summary>
private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes;
private int _needsGeneratedAttributes;
private bool _needsGeneratedAttributes_IsFrozen;
/// <summary>
/// Returns a value indicating which embedded attributes should be generated during emit phase.
/// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it.
/// Freezing is needed to make sure that nothing tries to modify the value after the value is read.
/// </summary>
internal EmbeddableAttributes GetNeedsGeneratedAttributes()
{
_needsGeneratedAttributes_IsFrozen = true;
return GetNeedsGeneratedAttributesInternal();
}
private EmbeddableAttributes GetNeedsGeneratedAttributesInternal()
{
return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes();
}
private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes);
}
internal PEModuleBuilder(
SourceModuleSymbol sourceModule,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
sourceModule,
serializationProperties,
manifestResources,
outputKind,
emitOptions,
new ModuleCompilationState())
{
var specifiedName = sourceModule.MetadataName;
_metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ?
specifiedName :
emitOptions.OutputNameOverride ?? specifiedName;
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this);
if (sourceModule.AnyReferencedAssembliesAreLinked)
{
_embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this);
}
}
public override string Name
{
get { return _metadataName; }
}
internal sealed override string ModuleName
{
get { return _metadataName; }
}
internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor)
{
return Compilation.TrySynthesizeAttribute(attributeConstructor);
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly)
{
return SourceModule.ContainingSourceAssembly
.GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule());
}
public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes()
{
return SourceModule.ContainingSourceAssembly.GetSecurityAttributes();
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes()
{
return SourceModule.GetCustomAttributesToEmit(this);
}
internal sealed override AssemblySymbol CorLibrary
{
get { return SourceModule.ContainingSourceAssembly.CorLibrary; }
}
public sealed override bool GenerateVisualBasicStylePdb => false;
// C# doesn't emit linked assembly names into PDBs.
public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>();
// C# currently doesn't emit compilation level imports (TODO: scripting).
public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty;
// C# doesn't allow to define default namespace for compilation.
public sealed override string DefaultNamespace => null;
protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics)
{
ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols())
{
yield return Translate(aRef, diagnostics);
}
}
}
private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics)
{
AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity;
AssemblyIdentity refIdentity = asmRef.Identity;
if (asmIdentity.IsStrongName && !refIdentity.IsStrongName &&
asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime)
{
// Dev12 reported error, we have changed it to a warning to allow referencing libraries
// built for platforms that don't support strong names.
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton);
}
if (OutputKind != OutputKind.NetModule &&
!string.IsNullOrEmpty(refIdentity.CultureName) &&
!string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase))
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton);
}
var refMachine = assembly.Machine;
// If other assembly is agnostic this is always safe
// Also, if no mscorlib was specified for back compat we add a reference to mscorlib
// that resolves to the current framework directory. If the compiler is 64-bit
// this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is
// specified. A reference to the default mscorlib should always succeed without
// warning so we ignore it here.
if ((object)assembly != (object)assembly.CorLibrary &&
!(refMachine == Machine.I386 && !assembly.Bit32Required))
{
var machine = SourceModule.Machine;
if (!(machine == Machine.I386 && !SourceModule.Bit32Required) &&
machine != refMachine)
{
// Different machine types, and neither is agnostic
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton);
}
}
if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen)
{
_embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics);
}
}
internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container)
{
return null;
}
public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap()
{
var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>();
var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>();
namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace);
Location location = null;
while (namespacesAndTypesToProcess.Count > 0)
{
NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop();
switch (symbol.Kind)
{
case SymbolKind.Namespace:
location = GetSmallestSourceLocationOrNull(symbol);
// filtering out synthesized symbols not having real source
// locations such as anonymous types, etc...
if (location != null)
{
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Namespace:
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
case SymbolKind.NamedType:
location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
// add this named type location
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
case SymbolKind.Method:
// NOTE: Dev11 does not add synthesized static constructors to this map,
// but adds synthesized instance constructors, Roslyn adds both
var method = (MethodSymbol)member;
if (!method.ShouldEmit())
{
break;
}
AddSymbolLocation(result, member);
break;
case SymbolKind.Property:
AddSymbolLocation(result, member);
break;
case SymbolKind.Field:
if (member is TupleErrorFieldSymbol)
{
break;
}
// NOTE: Dev11 does not add synthesized backing fields for properties,
// but adds backing fields for events, Roslyn adds both
AddSymbolLocation(result, member);
break;
case SymbolKind.Event:
AddSymbolLocation(result, member);
// event backing fields do not show up in GetMembers
{
FieldSymbol field = ((EventSymbol)member).AssociatedField;
if ((object)field != null)
{
AddSymbolLocation(result, field);
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
return result;
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol)
{
var location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
}
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition)
{
FileLinePositionSpan span = location.GetLineSpan();
Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath);
if (doc != null)
{
result.Add(doc,
new Cci.DefinitionWithLocation(
definition,
span.StartLinePosition.Line,
span.StartLinePosition.Character,
span.EndLinePosition.Line,
span.EndLinePosition.Character));
}
}
private Location GetSmallestSourceLocationOrNull(Symbol symbol)
{
CSharpCompilation compilation = symbol.DeclaringCompilation;
Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?");
Location result = null;
foreach (var loc in symbol.Locations)
{
if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0))
{
result = loc;
}
}
return result;
}
/// <summary>
/// Ignore accessibility when resolving well-known type
/// members, in particular for generic type arguments
/// (e.g.: binding to internal types in the EE).
/// </summary>
internal virtual bool IgnoreAccessibility => false;
/// <summary>
/// Override the dynamic operation context type for all dynamic calls in the module.
/// </summary>
internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType)
{
return contextType;
}
internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics)
{
return null;
}
internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes()
{
return ImmutableArray<AnonymousTypeKey>.Empty;
}
internal virtual int GetNextAnonymousTypeIndex()
{
return 0;
}
internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index)
{
Debug.Assert(Compilation == template.DeclaringCompilation);
name = null;
index = -1;
return false;
}
public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context)
{
if (context.MetadataOnly)
{
return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>();
}
return Compilation.AnonymousTypeManager.GetAllCreatedTemplates()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context)
{
var namespacesToProcess = new Stack<NamespaceSymbol>();
namespacesToProcess.Push(SourceModule.GlobalNamespace);
while (namespacesToProcess.Count > 0)
{
var ns = namespacesToProcess.Pop();
foreach (var member in ns.GetMembers())
{
if (member.Kind == SymbolKind.Namespace)
{
namespacesToProcess.Push((NamespaceSymbol)member);
}
else
{
yield return ((NamedTypeSymbol)member).GetCciAdapter();
}
}
}
}
private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder)
{
int index;
if (symbol.Kind == SymbolKind.NamedType)
{
if (symbol.DeclaredAccessibility != Accessibility.Public)
{
return;
}
Debug.Assert(symbol.IsDefinition);
index = builder.Count;
builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false));
}
else
{
index = -1;
}
foreach (var member in symbol.GetMembers())
{
var namespaceOrType = member as NamespaceOrTypeSymbol;
if ((object)namespaceOrType != null)
{
GetExportedTypes(namespaceOrType, index, builder);
}
}
}
public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics)
{
Debug.Assert(HaveDeterminedTopLevelTypes);
if (_lazyExportedTypes.IsDefault)
{
_lazyExportedTypes = CalculateExportedTypes();
if (_lazyExportedTypes.Length > 0)
{
ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics);
}
}
return _lazyExportedTypes;
}
/// <summary>
/// Builds an array of public type symbols defined in netmodules included in the compilation
/// and type forwarders defined in this compilation or any included netmodule (in this order).
/// </summary>
private ImmutableArray<Cci.ExportedType> CalculateExportedTypes()
{
SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly;
var builder = ArrayBuilder<Cci.ExportedType>.GetInstance();
if (!OutputKind.IsNetModule())
{
var modules = sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0]
{
GetExportedTypes(modules[i].GlobalNamespace, -1, builder);
}
}
Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule());
GetForwardedTypes(sourceAssembly, builder);
return builder.ToImmutableAndFree();
}
#nullable enable
/// <summary>
/// Returns a set of top-level forwarded types
/// </summary>
internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder)
{
var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>();
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder);
if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule())
{
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder);
}
return seenTopLevelForwardedTypes;
}
#nullable disable
private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics)
{
var sourceAssembly = SourceModule.ContainingSourceAssembly;
var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance);
foreach (var exportedType in exportedTypes)
{
var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol();
Debug.Assert(type.IsDefinition);
if (!type.IsTopLevelType())
{
continue;
}
// exported types are not emitted in EnC deltas (hence generation 0):
string fullEmittedName = MetadataHelpers.BuildQualifiedName(
((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName,
Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0));
// First check against types declared in the primary module
if (ContainsTopLevelType(fullEmittedName))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule);
}
else
{
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type);
}
continue;
}
NamedTypeSymbol contender;
// Now check against other exported types
if (exportedNamesMap.TryGetValue(fullEmittedName, out contender))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
// all exported types precede forwarded types, therefore contender cannot be a forwarded type.
Debug.Assert(contender.ContainingAssembly == sourceAssembly);
diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule);
}
else if ((object)contender.ContainingAssembly == sourceAssembly)
{
// Forwarded type conflicts with exported type
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule);
}
else
{
// Forwarded type conflicts with another forwarded type
diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly);
}
continue;
}
exportedNamesMap.Add(fullEmittedName, type);
}
}
#nullable enable
private static void GetForwardedTypes(
HashSet<NamedTypeSymbol> seenTopLevelTypes,
CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData,
ArrayBuilder<Cci.ExportedType>? builder)
{
if (wellKnownAttributeData?.ForwardedTypes?.Count > 0)
{
// (type, index of the parent exported type in builder, or -1 if the type is a top-level type)
var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance();
// Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names.
IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes;
if (builder is object)
{
orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat));
}
foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes)
{
NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition;
Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?");
// Since we need to allow multiple constructions of the same generic type at the source
// level, we need to de-dup the original definitions before emitting.
if (!seenTopLevelTypes.Add(originalDefinition)) continue;
if (builder is object)
{
// Return all nested types.
// Note the order: depth first, children in reverse order (to match dev10, not a requirement).
Debug.Assert(stack.Count == 0);
stack.Push((originalDefinition, -1));
while (stack.Count > 0)
{
var (type, parentIndex) = stack.Pop();
// In general, we don't want private types to appear in the ExportedTypes table.
// BREAK: dev11 emits these types. The problem was discovered in dev10, but failed
// to meet the bar Bug: Dev10/258038 and was left as-is.
if (type.DeclaredAccessibility == Accessibility.Private)
{
// NOTE: this will also exclude nested types of type
continue;
}
// NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.
int index = builder.Count;
builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true));
// Iterate backwards so they get popped in forward order.
ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered.
for (int i = nested.Length - 1; i >= 0; i--)
{
stack.Push((nested[i], index));
}
}
}
}
stack.Free();
}
}
#nullable disable
internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar()
{
foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols())
{
if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a))
{
yield return a;
}
}
}
private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType);
DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo;
if (info != null)
{
Symbol.ReportUseSiteDiagnostic(info,
diagnostics,
syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton);
}
return typeSymbol;
}
internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics),
diagnostics: diagnostics,
syntaxNodeOpt: syntaxNodeOpt,
needDeclaration: true);
}
public sealed override Cci.IMethodReference GetInitArrayHelper()
{
return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter();
}
public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType)
{
var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol;
if ((object)namedType != null)
{
if (platformType == Cci.PlatformType.SystemType)
{
return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type);
}
return namedType.SpecialType == (SpecialType)platformType;
}
return false;
}
protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context)
{
AssemblySymbol corLibrary = CorLibrary;
if (!corLibrary.IsMissing &&
!corLibrary.IsLinked &&
!ReferenceEquals(corLibrary, SourceModule.ContainingAssembly))
{
return Translate(corLibrary, context.Diagnostics);
}
return null;
}
internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule.ContainingAssembly, assembly))
{
return (Cci.IAssemblyReference)this;
}
Cci.IModuleReference reference;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference))
{
return (Cci.IAssemblyReference)reference;
}
AssemblyReference asmRef = new AssemblyReference(assembly);
AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef);
if (cachedAsmRef == asmRef)
{
ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics);
}
// TryAdd because whatever is associated with assembly should be associated with Modules[0]
AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef);
return cachedAsmRef;
}
internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule, module))
{
return this;
}
if ((object)module == null)
{
return null;
}
Cci.IModuleReference moduleRef;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef))
{
return moduleRef;
}
moduleRef = TranslateModule(module, diagnostics);
moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef);
return moduleRef;
}
protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics)
{
AssemblySymbol container = module.ContainingAssembly;
if ((object)container != null && ReferenceEquals(container.Modules[0], module))
{
Cci.IModuleReference moduleRef = new AssemblyReference(container);
Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef);
if (cachedModuleRef == moduleRef)
{
ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics);
}
else
{
moduleRef = cachedModuleRef;
}
return moduleRef;
}
else
{
return new ModuleReference(this, module);
}
}
internal Cci.INamedTypeReference Translate(
NamedTypeSymbol namedTypeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool fromImplements = false,
bool needDeclaration = false)
{
Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct());
Debug.Assert(diagnostics != null);
// Anonymous type being translated
if (namedTypeSymbol.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol);
}
else if (namedTypeSymbol.IsTupleType)
{
CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics);
}
// Substitute error types with a special singleton object.
// Unreported bad types can come through NoPia embedding, for example.
if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType)
{
ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition;
DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType)
{
errorType = (ErrorTypeSymbol)namedTypeSymbol;
diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (_reportedErrorTypesMap.Add(errorType))
{
diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location));
}
return CodeAnalysis.Emit.ErrorType.Singleton;
}
if (!namedTypeSymbol.IsDefinition)
{
// generic instantiation for sure
Debug.Assert(!needDeclaration);
if (namedTypeSymbol.IsUnboundGenericType)
{
namedTypeSymbol = namedTypeSymbol.OriginalDefinition;
}
else
{
return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol);
}
}
else if (!needDeclaration)
{
object reference;
Cci.INamedTypeReference typeRef;
NamedTypeSymbol container = namedTypeSymbol.ContainingType;
if (namedTypeSymbol.Arity > 0)
{
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
if ((object)container != null)
{
if (IsGenericType(container))
{
// Container is a generic instance too.
typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol);
}
else
{
typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol);
}
}
else
{
typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol);
}
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (IsGenericType(container))
{
Debug.Assert((object)container != null);
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
typeRef = new SpecializedNestedTypeReference(namedTypeSymbol);
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType)
{
namedTypeSymbol = underlyingType;
}
}
// NoPia: See if this is a type, which definition we should copy into our assembly.
Debug.Assert(namedTypeSymbol.IsDefinition);
return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter();
}
private object GetCciAdapter(Symbol symbol)
{
return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter());
}
private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
// check that underlying type of a ValueTuple is indeed a value type (or error)
// this should never happen, in theory,
// but if it does happen we should make it a failure.
// NOTE: declaredBase could be null for interfaces
var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType)
{
return;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (!_reportedErrorTypesMap.Add(namedTypeSymbol))
{
return;
}
var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location;
if ((object)declaredBase != null)
{
var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo;
if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(diagnosticInfo, location);
return;
}
}
diagnostics.Add(
new CSDiagnostic(
new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName),
location));
}
public static bool IsGenericType(NamedTypeSymbol toCheck)
{
while ((object)toCheck != null)
{
if (toCheck.Arity > 0)
{
return true;
}
toCheck = toCheck.ContainingType;
}
return false;
}
internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param)
{
if (!param.IsDefinition)
throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name));
return param.GetCciAdapter();
}
internal sealed override Cci.ITypeReference Translate(
TypeSymbol typeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
switch (typeSymbol.Kind)
{
case SymbolKind.DynamicType:
return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.ArrayType:
return Translate((ArrayTypeSymbol)typeSymbol);
case SymbolKind.ErrorType:
case SymbolKind.NamedType:
return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.PointerType:
return Translate((PointerTypeSymbol)typeSymbol);
case SymbolKind.TypeParameter:
return Translate((TypeParameterSymbol)typeSymbol);
case SymbolKind.FunctionPointerType:
return Translate((FunctionPointerTypeSymbol)typeSymbol);
}
throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind);
}
internal Cci.IFieldReference Translate(
FieldSymbol fieldSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration = false)
{
Debug.Assert(fieldSymbol.IsDefinitionOrDistinct());
Debug.Assert(!fieldSymbol.IsVirtualTupleField &&
(object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol &&
fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now");
if (!fieldSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
return (Cci.IFieldReference)GetCciAdapter(fieldSymbol);
}
else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType))
{
object reference;
Cci.IFieldReference fieldRef;
if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference))
{
return (Cci.IFieldReference)reference;
}
fieldRef = new SpecializedFieldReference(fieldSymbol);
fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef);
return fieldRef;
}
return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter();
}
public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol)
{
//
// We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies.
//
// Top-level:
// private -> public
// protected -> public (compiles with a warning)
// public
// internal -> public
//
// In a nested class:
//
// private
// protected
// public
// internal -> public
//
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
return Cci.TypeMemberVisibility.Public;
case Accessibility.Private:
if (symbol.ContainingType?.TypeKind == TypeKind.Submission)
{
// top-level private member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Private;
}
case Accessibility.Internal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Assembly;
}
case Accessibility.Protected:
if (symbol.ContainingType.TypeKind == TypeKind.Submission)
{
// top-level protected member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Family;
}
case Accessibility.ProtectedAndInternal:
Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission);
return Cci.TypeMemberVisibility.FamilyAndAssembly;
case Accessibility.ProtectedOrInternal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested protected internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.FamilyOrAssembly;
}
default:
throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility);
}
}
internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration)
{
return Translate(symbol, null, diagnostics, null, needDeclaration);
}
internal Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
BoundArgListOperator optArgList = null,
bool needDeclaration = false)
{
Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true));
Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration));
Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration);
if (optArgList != null && optArgList.Arguments.Length > 0)
{
Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length];
int ordinal = methodSymbol.ParameterCount;
for (int i = 0; i < @params.Length; i++)
{
@params[i] = new ArgListParameterTypeInformation(ordinal,
!optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None,
Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics));
ordinal++;
}
return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull());
}
else
{
return unexpandedMethodRef;
}
}
private Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration)
{
object reference;
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
// Method of anonymous type being translated
if (container.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol);
}
Debug.Assert(methodSymbol.IsDefinitionOrDistinct());
if (!methodSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol));
Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol));
return (Cci.IMethodReference)GetCciAdapter(methodSymbol);
}
else if (!needDeclaration)
{
bool methodIsGeneric = methodSymbol.IsGenericMethod;
bool typeIsGeneric = IsGenericType(container);
if (methodIsGeneric || typeIsGeneric)
{
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
return (Cci.IMethodReference)reference;
}
if (methodIsGeneric)
{
if (typeIsGeneric)
{
// Specialized and generic instance at the same time.
methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol);
}
else
{
methodRef = new GenericMethodInstanceReference(methodSymbol);
}
}
else
{
Debug.Assert(typeIsGeneric);
methodRef = new SpecializedMethodReference(methodSymbol);
}
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
return methodRef;
}
else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod })
{
methodSymbol = underlyingMethod;
}
}
if (_embeddedTypesManagerOpt != null)
{
return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
return methodSymbol.GetCciAdapter();
}
internal Cci.IMethodReference TranslateOverriddenMethodReference(
MethodSymbol methodSymbol,
CSharpSyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
if (IsGenericType(container))
{
if (methodSymbol.IsDefinition)
{
object reference;
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
methodRef = (Cci.IMethodReference)reference;
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
}
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
}
}
else
{
Debug.Assert(methodSymbol.IsDefinition);
if (_embeddedTypesManagerOpt != null)
{
methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
else
{
methodRef = methodSymbol.GetCciAdapter();
}
}
return methodRef;
}
internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params)
{
Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct()));
bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First());
Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating");
if (!mustBeTranslated)
{
#if DEBUG
return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter());
#else
return StaticCast<Cci.IParameterTypeInformation>.From(@params);
#endif
}
return TranslateAll(@params);
}
private static bool MustBeWrapped(ParameterSymbol param)
{
// we represent parameters of generic methods as definitions
// CCI wants them represented as IParameterTypeInformation
// so we need to create a wrapper of parameters iff
// 1) parameters are definitions and
// 2) container is generic
// NOTE: all parameters must always agree on whether they need wrapping
if (param.IsDefinition)
{
var container = param.ContainingSymbol;
if (ContainerIsGeneric(container))
{
return true;
}
}
return false;
}
private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params)
{
var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance();
foreach (var param in @params)
{
builder.Add(CreateParameterTypeInformationWrapper(param));
}
return builder.ToImmutableAndFree();
}
private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param)
{
object reference;
Cci.IParameterTypeInformation paramRef;
if (_genericInstanceMap.TryGetValue(param, out reference))
{
return (Cci.IParameterTypeInformation)reference;
}
paramRef = new ParameterTypeInformation(param);
paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef);
return paramRef;
}
private static bool ContainerIsGeneric(Symbol container)
{
return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod ||
IsGenericType(container.ContainingType);
}
internal Cci.ITypeReference Translate(
DynamicTypeSymbol symbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
// Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table.
// We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter
// masquerades the TypeRef as System.Object when used to encode signatures.
return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics);
}
internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol)
{
return (Cci.IArrayTypeReference)GetCciAdapter(symbol);
}
internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol)
{
return (Cci.IPointerTypeReference)GetCciAdapter(symbol);
}
internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol)
{
return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol);
}
/// <summary>
/// Set the underlying implementation type for a given fixed-size buffer field.
/// </summary>
public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field)
{
if (_fixedImplementationTypes == null)
{
Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null);
}
lock (_fixedImplementationTypes)
{
NamedTypeSymbol result;
if (_fixedImplementationTypes.TryGetValue(field, out result))
{
return result;
}
result = new FixedFieldImplementationType(field);
_fixedImplementationTypes.Add(field, result);
AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter());
return result;
}
}
internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field)
{
// Note that this method is called only after ALL fixed buffer types have been placed in the map.
// At that point the map is all filled in and will not change further. Therefore it is safe to
// pull values from the map without locking.
NamedTypeSymbol result;
var found = _fixedImplementationTypes.TryGetValue(field, out result);
Debug.Assert(found);
return result;
}
protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics)
{
return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter();
}
internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute();
internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsReadOnlyAttribute();
}
internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsUnmanagedAttribute();
}
internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsByRefLikeAttribute();
}
/// <summary>
/// Given a type <paramref name="type"/>, which is either a nullable reference type OR
/// is a constructed type with a nullable reference type present in its type argument tree,
/// returns a synthesized NullableAttribute with encoded nullable transforms array.
/// </summary>
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var flagsBuilder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(flagsBuilder);
SynthesizedAttributeData attribute;
if (!flagsBuilder.Any())
{
attribute = null;
}
else
{
Debug.Assert(flagsBuilder.All(f => f <= 2));
byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder);
if (commonValue != null)
{
attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault());
}
else
{
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType));
var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType);
attribute = SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags,
ImmutableArray.Create(new TypedConstant(byteArrayType, value)));
}
}
flagsBuilder.Free();
return attribute;
}
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue)
{
if (nullableValue == nullableContextValue ||
(nullableContextValue == null && nullableValue == 0))
{
return null;
}
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
return SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte,
ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value)
{
var module = Compilation.SourceModule;
if ((object)module != symbol && (object)module != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return SynthesizeNullableContextAttribute(
ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute()
{
return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type)
{
Debug.Assert((object)type != null);
Debug.Assert(type.ContainsNativeInteger());
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var builder = ArrayBuilder<bool>.GetInstance();
CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type);
Debug.Assert(builder.Any());
Debug.Assert(builder.Contains(true));
SynthesizedAttributeData attribute;
if (builder.Count == 1 && builder[0])
{
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty);
}
else
{
NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean);
Debug.Assert((object)booleanType != null);
var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType);
var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType));
var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags));
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments);
}
builder.Free();
return attribute;
}
internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal bool ShouldEmitNullablePublicOnlyAttribute()
{
// No need to look at this.GetNeedsGeneratedAttributes() since those bits are
// only set for members generated by the rewriter which are not public.
return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly;
}
internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor);
}
private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0)
{
return;
}
// Don't report any errors. They should be reported during binding.
if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null))
{
SetNeedsGeneratedAttributes(attribute);
}
}
internal void EnsureIsReadOnlyAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute);
}
internal void EnsureIsUnmanagedAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute);
}
internal void EnsureNullableAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute);
}
internal void EnsureNativeIntegerAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute);
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context)
{
return GetAdditionalTopLevelTypes()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context)
{
return GetEmbeddedTypes(context.Diagnostics)
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics)
{
return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics));
}
internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
return base.GetEmbeddedTypes(diagnostics.DiagnosticBag);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState>
{
// TODO: Need to estimate amount of elements for this map and pass that value to the constructor.
protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>();
private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything);
private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>();
private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt;
public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt
=> _embeddedTypesManagerOpt;
// Gives the name of this module (may not reflect the name of the underlying symbol).
// See Assembly.MetadataName.
private readonly string _metadataName;
private ImmutableArray<Cci.ExportedType> _lazyExportedTypes;
/// <summary>
/// The compiler-generated implementation type for each fixed-size buffer.
/// </summary>
private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes;
private int _needsGeneratedAttributes;
private bool _needsGeneratedAttributes_IsFrozen;
/// <summary>
/// Returns a value indicating which embedded attributes should be generated during emit phase.
/// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it.
/// Freezing is needed to make sure that nothing tries to modify the value after the value is read.
/// </summary>
internal EmbeddableAttributes GetNeedsGeneratedAttributes()
{
_needsGeneratedAttributes_IsFrozen = true;
return GetNeedsGeneratedAttributesInternal();
}
private EmbeddableAttributes GetNeedsGeneratedAttributesInternal()
{
return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes();
}
private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes);
}
internal PEModuleBuilder(
SourceModuleSymbol sourceModule,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
sourceModule,
serializationProperties,
manifestResources,
outputKind,
emitOptions,
new ModuleCompilationState())
{
var specifiedName = sourceModule.MetadataName;
_metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ?
specifiedName :
emitOptions.OutputNameOverride ?? specifiedName;
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this);
if (sourceModule.AnyReferencedAssembliesAreLinked)
{
_embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this);
}
}
public override string Name
{
get { return _metadataName; }
}
internal sealed override string ModuleName
{
get { return _metadataName; }
}
internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor)
{
return Compilation.TrySynthesizeAttribute(attributeConstructor);
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly)
{
return SourceModule.ContainingSourceAssembly
.GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule());
}
public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes()
{
return SourceModule.ContainingSourceAssembly.GetSecurityAttributes();
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes()
{
return SourceModule.GetCustomAttributesToEmit(this);
}
internal sealed override AssemblySymbol CorLibrary
{
get { return SourceModule.ContainingSourceAssembly.CorLibrary; }
}
public sealed override bool GenerateVisualBasicStylePdb => false;
// C# doesn't emit linked assembly names into PDBs.
public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>();
// C# currently doesn't emit compilation level imports (TODO: scripting).
public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty;
// C# doesn't allow to define default namespace for compilation.
public sealed override string DefaultNamespace => null;
protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics)
{
ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols())
{
yield return Translate(aRef, diagnostics);
}
}
}
private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics)
{
AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity;
AssemblyIdentity refIdentity = asmRef.Identity;
if (asmIdentity.IsStrongName && !refIdentity.IsStrongName &&
asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime)
{
// Dev12 reported error, we have changed it to a warning to allow referencing libraries
// built for platforms that don't support strong names.
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton);
}
if (OutputKind != OutputKind.NetModule &&
!string.IsNullOrEmpty(refIdentity.CultureName) &&
!string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase))
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton);
}
var refMachine = assembly.Machine;
// If other assembly is agnostic this is always safe
// Also, if no mscorlib was specified for back compat we add a reference to mscorlib
// that resolves to the current framework directory. If the compiler is 64-bit
// this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is
// specified. A reference to the default mscorlib should always succeed without
// warning so we ignore it here.
if ((object)assembly != (object)assembly.CorLibrary &&
!(refMachine == Machine.I386 && !assembly.Bit32Required))
{
var machine = SourceModule.Machine;
if (!(machine == Machine.I386 && !SourceModule.Bit32Required) &&
machine != refMachine)
{
// Different machine types, and neither is agnostic
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton);
}
}
if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen)
{
_embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics);
}
}
internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container)
{
return null;
}
public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap()
{
var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>();
var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>();
namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace);
Location location = null;
while (namespacesAndTypesToProcess.Count > 0)
{
NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop();
switch (symbol.Kind)
{
case SymbolKind.Namespace:
location = GetSmallestSourceLocationOrNull(symbol);
// filtering out synthesized symbols not having real source
// locations such as anonymous types, etc...
if (location != null)
{
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Namespace:
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
case SymbolKind.NamedType:
location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
// add this named type location
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
case SymbolKind.Method:
// NOTE: Dev11 does not add synthesized static constructors to this map,
// but adds synthesized instance constructors, Roslyn adds both
var method = (MethodSymbol)member;
if (!method.ShouldEmit())
{
break;
}
AddSymbolLocation(result, member);
break;
case SymbolKind.Property:
AddSymbolLocation(result, member);
break;
case SymbolKind.Field:
if (member is TupleErrorFieldSymbol)
{
break;
}
// NOTE: Dev11 does not add synthesized backing fields for properties,
// but adds backing fields for events, Roslyn adds both
AddSymbolLocation(result, member);
break;
case SymbolKind.Event:
AddSymbolLocation(result, member);
// event backing fields do not show up in GetMembers
{
FieldSymbol field = ((EventSymbol)member).AssociatedField;
if ((object)field != null)
{
AddSymbolLocation(result, field);
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
return result;
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol)
{
var location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
}
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition)
{
FileLinePositionSpan span = location.GetLineSpan();
Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath);
if (doc != null)
{
result.Add(doc,
new Cci.DefinitionWithLocation(
definition,
span.StartLinePosition.Line,
span.StartLinePosition.Character,
span.EndLinePosition.Line,
span.EndLinePosition.Character));
}
}
private Location GetSmallestSourceLocationOrNull(Symbol symbol)
{
CSharpCompilation compilation = symbol.DeclaringCompilation;
Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?");
Location result = null;
foreach (var loc in symbol.Locations)
{
if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0))
{
result = loc;
}
}
return result;
}
/// <summary>
/// Ignore accessibility when resolving well-known type
/// members, in particular for generic type arguments
/// (e.g.: binding to internal types in the EE).
/// </summary>
internal virtual bool IgnoreAccessibility => false;
/// <summary>
/// Override the dynamic operation context type for all dynamic calls in the module.
/// </summary>
internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType)
{
return contextType;
}
internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics)
{
return null;
}
internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes()
{
return ImmutableArray<AnonymousTypeKey>.Empty;
}
internal virtual int GetNextAnonymousTypeIndex()
{
return 0;
}
internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index)
{
Debug.Assert(Compilation == template.DeclaringCompilation);
name = null;
index = -1;
return false;
}
public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context)
{
if (context.MetadataOnly)
{
return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>();
}
return Compilation.AnonymousTypeManager.GetAllCreatedTemplates()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context)
{
var namespacesToProcess = new Stack<NamespaceSymbol>();
namespacesToProcess.Push(SourceModule.GlobalNamespace);
while (namespacesToProcess.Count > 0)
{
var ns = namespacesToProcess.Pop();
foreach (var member in ns.GetMembers())
{
if (member.Kind == SymbolKind.Namespace)
{
namespacesToProcess.Push((NamespaceSymbol)member);
}
else
{
yield return ((NamedTypeSymbol)member).GetCciAdapter();
}
}
}
}
private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder)
{
int index;
if (symbol.Kind == SymbolKind.NamedType)
{
if (symbol.DeclaredAccessibility != Accessibility.Public)
{
return;
}
Debug.Assert(symbol.IsDefinition);
index = builder.Count;
builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false));
}
else
{
index = -1;
}
foreach (var member in symbol.GetMembers())
{
var namespaceOrType = member as NamespaceOrTypeSymbol;
if ((object)namespaceOrType != null)
{
GetExportedTypes(namespaceOrType, index, builder);
}
}
}
public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics)
{
Debug.Assert(HaveDeterminedTopLevelTypes);
if (_lazyExportedTypes.IsDefault)
{
_lazyExportedTypes = CalculateExportedTypes();
if (_lazyExportedTypes.Length > 0)
{
ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics);
}
}
return _lazyExportedTypes;
}
/// <summary>
/// Builds an array of public type symbols defined in netmodules included in the compilation
/// and type forwarders defined in this compilation or any included netmodule (in this order).
/// </summary>
private ImmutableArray<Cci.ExportedType> CalculateExportedTypes()
{
SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly;
var builder = ArrayBuilder<Cci.ExportedType>.GetInstance();
if (!OutputKind.IsNetModule())
{
var modules = sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0]
{
GetExportedTypes(modules[i].GlobalNamespace, -1, builder);
}
}
Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule());
GetForwardedTypes(sourceAssembly, builder);
return builder.ToImmutableAndFree();
}
#nullable enable
/// <summary>
/// Returns a set of top-level forwarded types
/// </summary>
internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder)
{
var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>();
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder);
if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule())
{
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder);
}
return seenTopLevelForwardedTypes;
}
#nullable disable
private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics)
{
var sourceAssembly = SourceModule.ContainingSourceAssembly;
var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance);
foreach (var exportedType in exportedTypes)
{
var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol();
Debug.Assert(type.IsDefinition);
if (!type.IsTopLevelType())
{
continue;
}
// exported types are not emitted in EnC deltas (hence generation 0):
string fullEmittedName = MetadataHelpers.BuildQualifiedName(
((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName,
Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0));
// First check against types declared in the primary module
if (ContainsTopLevelType(fullEmittedName))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule);
}
else
{
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type);
}
continue;
}
NamedTypeSymbol contender;
// Now check against other exported types
if (exportedNamesMap.TryGetValue(fullEmittedName, out contender))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
// all exported types precede forwarded types, therefore contender cannot be a forwarded type.
Debug.Assert(contender.ContainingAssembly == sourceAssembly);
diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule);
}
else if ((object)contender.ContainingAssembly == sourceAssembly)
{
// Forwarded type conflicts with exported type
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule);
}
else
{
// Forwarded type conflicts with another forwarded type
diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly);
}
continue;
}
exportedNamesMap.Add(fullEmittedName, type);
}
}
#nullable enable
private static void GetForwardedTypes(
HashSet<NamedTypeSymbol> seenTopLevelTypes,
CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData,
ArrayBuilder<Cci.ExportedType>? builder)
{
if (wellKnownAttributeData?.ForwardedTypes?.Count > 0)
{
// (type, index of the parent exported type in builder, or -1 if the type is a top-level type)
var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance();
// Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names.
IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes;
if (builder is object)
{
orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat));
}
foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes)
{
NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition;
Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?");
// Since we need to allow multiple constructions of the same generic type at the source
// level, we need to de-dup the original definitions before emitting.
if (!seenTopLevelTypes.Add(originalDefinition)) continue;
if (builder is object)
{
// Return all nested types.
// Note the order: depth first, children in reverse order (to match dev10, not a requirement).
Debug.Assert(stack.Count == 0);
stack.Push((originalDefinition, -1));
while (stack.Count > 0)
{
var (type, parentIndex) = stack.Pop();
// In general, we don't want private types to appear in the ExportedTypes table.
// BREAK: dev11 emits these types. The problem was discovered in dev10, but failed
// to meet the bar Bug: Dev10/258038 and was left as-is.
if (type.DeclaredAccessibility == Accessibility.Private)
{
// NOTE: this will also exclude nested types of type
continue;
}
// NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.
int index = builder.Count;
builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true));
// Iterate backwards so they get popped in forward order.
ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered.
for (int i = nested.Length - 1; i >= 0; i--)
{
stack.Push((nested[i], index));
}
}
}
}
stack.Free();
}
}
#nullable disable
internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar()
{
foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols())
{
if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a))
{
yield return a;
}
}
}
private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType);
DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo;
if (info != null)
{
Symbol.ReportUseSiteDiagnostic(info,
diagnostics,
syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton);
}
return typeSymbol;
}
internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics),
diagnostics: diagnostics,
syntaxNodeOpt: syntaxNodeOpt,
needDeclaration: true);
}
public sealed override Cci.IMethodReference GetInitArrayHelper()
{
return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter();
}
public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType)
{
var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol;
if ((object)namedType != null)
{
if (platformType == Cci.PlatformType.SystemType)
{
return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type);
}
return namedType.SpecialType == (SpecialType)platformType;
}
return false;
}
protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context)
{
AssemblySymbol corLibrary = CorLibrary;
if (!corLibrary.IsMissing &&
!corLibrary.IsLinked &&
!ReferenceEquals(corLibrary, SourceModule.ContainingAssembly))
{
return Translate(corLibrary, context.Diagnostics);
}
return null;
}
internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule.ContainingAssembly, assembly))
{
return (Cci.IAssemblyReference)this;
}
Cci.IModuleReference reference;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference))
{
return (Cci.IAssemblyReference)reference;
}
AssemblyReference asmRef = new AssemblyReference(assembly);
AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef);
if (cachedAsmRef == asmRef)
{
ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics);
}
// TryAdd because whatever is associated with assembly should be associated with Modules[0]
AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef);
return cachedAsmRef;
}
internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule, module))
{
return this;
}
if ((object)module == null)
{
return null;
}
Cci.IModuleReference moduleRef;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef))
{
return moduleRef;
}
moduleRef = TranslateModule(module, diagnostics);
moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef);
return moduleRef;
}
protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics)
{
AssemblySymbol container = module.ContainingAssembly;
if ((object)container != null && ReferenceEquals(container.Modules[0], module))
{
Cci.IModuleReference moduleRef = new AssemblyReference(container);
Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef);
if (cachedModuleRef == moduleRef)
{
ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics);
}
else
{
moduleRef = cachedModuleRef;
}
return moduleRef;
}
else
{
return new ModuleReference(this, module);
}
}
internal Cci.INamedTypeReference Translate(
NamedTypeSymbol namedTypeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool fromImplements = false,
bool needDeclaration = false)
{
Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct());
Debug.Assert(diagnostics != null);
// Anonymous type being translated
if (namedTypeSymbol.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol);
}
else if (namedTypeSymbol.IsTupleType)
{
CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics);
}
// Substitute error types with a special singleton object.
// Unreported bad types can come through NoPia embedding, for example.
if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType)
{
ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition;
DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType)
{
errorType = (ErrorTypeSymbol)namedTypeSymbol;
diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (_reportedErrorTypesMap.Add(errorType))
{
diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location));
}
return CodeAnalysis.Emit.ErrorType.Singleton;
}
if (!namedTypeSymbol.IsDefinition)
{
// generic instantiation for sure
Debug.Assert(!needDeclaration);
if (namedTypeSymbol.IsUnboundGenericType)
{
namedTypeSymbol = namedTypeSymbol.OriginalDefinition;
}
else
{
return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol);
}
}
else if (!needDeclaration)
{
object reference;
Cci.INamedTypeReference typeRef;
NamedTypeSymbol container = namedTypeSymbol.ContainingType;
if (namedTypeSymbol.Arity > 0)
{
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
if ((object)container != null)
{
if (IsGenericType(container))
{
// Container is a generic instance too.
typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol);
}
else
{
typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol);
}
}
else
{
typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol);
}
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (IsGenericType(container))
{
Debug.Assert((object)container != null);
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
typeRef = new SpecializedNestedTypeReference(namedTypeSymbol);
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType)
{
namedTypeSymbol = underlyingType;
}
}
// NoPia: See if this is a type, which definition we should copy into our assembly.
Debug.Assert(namedTypeSymbol.IsDefinition);
return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter();
}
private object GetCciAdapter(Symbol symbol)
{
return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter());
}
private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
// check that underlying type of a ValueTuple is indeed a value type (or error)
// this should never happen, in theory,
// but if it does happen we should make it a failure.
// NOTE: declaredBase could be null for interfaces
var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType)
{
return;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (!_reportedErrorTypesMap.Add(namedTypeSymbol))
{
return;
}
var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location;
if ((object)declaredBase != null)
{
var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo;
if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(diagnosticInfo, location);
return;
}
}
diagnostics.Add(
new CSDiagnostic(
new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName),
location));
}
public static bool IsGenericType(NamedTypeSymbol toCheck)
{
while ((object)toCheck != null)
{
if (toCheck.Arity > 0)
{
return true;
}
toCheck = toCheck.ContainingType;
}
return false;
}
internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param)
{
if (!param.IsDefinition)
throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name));
return param.GetCciAdapter();
}
internal sealed override Cci.ITypeReference Translate(
TypeSymbol typeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
switch (typeSymbol.Kind)
{
case SymbolKind.DynamicType:
return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.ArrayType:
return Translate((ArrayTypeSymbol)typeSymbol);
case SymbolKind.ErrorType:
case SymbolKind.NamedType:
return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.PointerType:
return Translate((PointerTypeSymbol)typeSymbol);
case SymbolKind.TypeParameter:
return Translate((TypeParameterSymbol)typeSymbol);
case SymbolKind.FunctionPointerType:
return Translate((FunctionPointerTypeSymbol)typeSymbol);
}
throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind);
}
internal Cci.IFieldReference Translate(
FieldSymbol fieldSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration = false)
{
Debug.Assert(fieldSymbol.IsDefinitionOrDistinct());
Debug.Assert(!fieldSymbol.IsVirtualTupleField &&
(object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol &&
fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now");
if (!fieldSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
return (Cci.IFieldReference)GetCciAdapter(fieldSymbol);
}
else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType))
{
object reference;
Cci.IFieldReference fieldRef;
if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference))
{
return (Cci.IFieldReference)reference;
}
fieldRef = new SpecializedFieldReference(fieldSymbol);
fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef);
return fieldRef;
}
return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter();
}
public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol)
{
//
// We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies.
//
// Top-level:
// private -> public
// protected -> public (compiles with a warning)
// public
// internal -> public
//
// In a nested class:
//
// private
// protected
// public
// internal -> public
//
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
return Cci.TypeMemberVisibility.Public;
case Accessibility.Private:
if (symbol.ContainingType?.TypeKind == TypeKind.Submission)
{
// top-level private member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Private;
}
case Accessibility.Internal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Assembly;
}
case Accessibility.Protected:
if (symbol.ContainingType.TypeKind == TypeKind.Submission)
{
// top-level protected member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Family;
}
case Accessibility.ProtectedAndInternal:
Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission);
return Cci.TypeMemberVisibility.FamilyAndAssembly;
case Accessibility.ProtectedOrInternal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested protected internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.FamilyOrAssembly;
}
default:
throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility);
}
}
internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration)
{
return Translate(symbol, null, diagnostics, null, needDeclaration);
}
internal Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
BoundArgListOperator optArgList = null,
bool needDeclaration = false)
{
Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true));
Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration));
Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration);
if (optArgList != null && optArgList.Arguments.Length > 0)
{
Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length];
int ordinal = methodSymbol.ParameterCount;
for (int i = 0; i < @params.Length; i++)
{
@params[i] = new ArgListParameterTypeInformation(ordinal,
!optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None,
Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics));
ordinal++;
}
return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull());
}
else
{
return unexpandedMethodRef;
}
}
private Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration)
{
object reference;
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
// Method of anonymous type being translated
if (container.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol);
}
Debug.Assert(methodSymbol.IsDefinitionOrDistinct());
if (!methodSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol));
Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol));
return (Cci.IMethodReference)GetCciAdapter(methodSymbol);
}
else if (!needDeclaration)
{
bool methodIsGeneric = methodSymbol.IsGenericMethod;
bool typeIsGeneric = IsGenericType(container);
if (methodIsGeneric || typeIsGeneric)
{
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
return (Cci.IMethodReference)reference;
}
if (methodIsGeneric)
{
if (typeIsGeneric)
{
// Specialized and generic instance at the same time.
methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol);
}
else
{
methodRef = new GenericMethodInstanceReference(methodSymbol);
}
}
else
{
Debug.Assert(typeIsGeneric);
methodRef = new SpecializedMethodReference(methodSymbol);
}
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
return methodRef;
}
else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod })
{
methodSymbol = underlyingMethod;
}
}
if (_embeddedTypesManagerOpt != null)
{
return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
return methodSymbol.GetCciAdapter();
}
internal Cci.IMethodReference TranslateOverriddenMethodReference(
MethodSymbol methodSymbol,
CSharpSyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
if (IsGenericType(container))
{
if (methodSymbol.IsDefinition)
{
object reference;
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
methodRef = (Cci.IMethodReference)reference;
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
}
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
}
}
else
{
Debug.Assert(methodSymbol.IsDefinition);
if (_embeddedTypesManagerOpt != null)
{
methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
else
{
methodRef = methodSymbol.GetCciAdapter();
}
}
return methodRef;
}
internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params)
{
Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct()));
bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First());
Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating");
if (!mustBeTranslated)
{
#if DEBUG
return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter());
#else
return StaticCast<Cci.IParameterTypeInformation>.From(@params);
#endif
}
return TranslateAll(@params);
}
private static bool MustBeWrapped(ParameterSymbol param)
{
// we represent parameters of generic methods as definitions
// CCI wants them represented as IParameterTypeInformation
// so we need to create a wrapper of parameters iff
// 1) parameters are definitions and
// 2) container is generic
// NOTE: all parameters must always agree on whether they need wrapping
if (param.IsDefinition)
{
var container = param.ContainingSymbol;
if (ContainerIsGeneric(container))
{
return true;
}
}
return false;
}
private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params)
{
var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance();
foreach (var param in @params)
{
builder.Add(CreateParameterTypeInformationWrapper(param));
}
return builder.ToImmutableAndFree();
}
private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param)
{
object reference;
Cci.IParameterTypeInformation paramRef;
if (_genericInstanceMap.TryGetValue(param, out reference))
{
return (Cci.IParameterTypeInformation)reference;
}
paramRef = new ParameterTypeInformation(param);
paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef);
return paramRef;
}
private static bool ContainerIsGeneric(Symbol container)
{
return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod ||
IsGenericType(container.ContainingType);
}
internal Cci.ITypeReference Translate(
DynamicTypeSymbol symbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
// Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table.
// We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter
// masquerades the TypeRef as System.Object when used to encode signatures.
return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics);
}
internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol)
{
return (Cci.IArrayTypeReference)GetCciAdapter(symbol);
}
internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol)
{
return (Cci.IPointerTypeReference)GetCciAdapter(symbol);
}
internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol)
{
return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol);
}
/// <summary>
/// Set the underlying implementation type for a given fixed-size buffer field.
/// </summary>
public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field)
{
if (_fixedImplementationTypes == null)
{
Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null);
}
lock (_fixedImplementationTypes)
{
NamedTypeSymbol result;
if (_fixedImplementationTypes.TryGetValue(field, out result))
{
return result;
}
result = new FixedFieldImplementationType(field);
_fixedImplementationTypes.Add(field, result);
AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter());
return result;
}
}
internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field)
{
// Note that this method is called only after ALL fixed buffer types have been placed in the map.
// At that point the map is all filled in and will not change further. Therefore it is safe to
// pull values from the map without locking.
NamedTypeSymbol result;
var found = _fixedImplementationTypes.TryGetValue(field, out result);
Debug.Assert(found);
return result;
}
protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics)
{
return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter();
}
internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute();
internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsReadOnlyAttribute();
}
internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsUnmanagedAttribute();
}
internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsByRefLikeAttribute();
}
/// <summary>
/// Given a type <paramref name="type"/>, which is either a nullable reference type OR
/// is a constructed type with a nullable reference type present in its type argument tree,
/// returns a synthesized NullableAttribute with encoded nullable transforms array.
/// </summary>
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var flagsBuilder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(flagsBuilder);
SynthesizedAttributeData attribute;
if (!flagsBuilder.Any())
{
attribute = null;
}
else
{
Debug.Assert(flagsBuilder.All(f => f <= 2));
byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder);
if (commonValue != null)
{
attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault());
}
else
{
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType));
var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType);
attribute = SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags,
ImmutableArray.Create(new TypedConstant(byteArrayType, value)));
}
}
flagsBuilder.Free();
return attribute;
}
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue)
{
if (nullableValue == nullableContextValue ||
(nullableContextValue == null && nullableValue == 0))
{
return null;
}
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
return SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte,
ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value)
{
var module = Compilation.SourceModule;
if ((object)module != symbol && (object)module != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return SynthesizeNullableContextAttribute(
ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute()
{
return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type)
{
Debug.Assert((object)type != null);
Debug.Assert(type.ContainsNativeInteger());
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var builder = ArrayBuilder<bool>.GetInstance();
CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type);
Debug.Assert(builder.Any());
Debug.Assert(builder.Contains(true));
SynthesizedAttributeData attribute;
if (builder.Count == 1 && builder[0])
{
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty);
}
else
{
NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean);
Debug.Assert((object)booleanType != null);
var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType);
var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType));
var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags));
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments);
}
builder.Free();
return attribute;
}
internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal bool ShouldEmitNullablePublicOnlyAttribute()
{
// No need to look at this.GetNeedsGeneratedAttributes() since those bits are
// only set for members generated by the rewriter which are not public.
return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly;
}
internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor);
}
private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0)
{
return;
}
// Don't report any errors. They should be reported during binding.
if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null))
{
SetNeedsGeneratedAttributes(attribute);
}
}
internal void EnsureIsReadOnlyAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute);
}
internal void EnsureIsUnmanagedAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute);
}
internal void EnsureNullableAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute);
}
internal void EnsureNativeIntegerAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute);
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context)
{
return GetAdditionalTopLevelTypes()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context)
{
return GetEmbeddedTypes(context.Diagnostics)
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics)
{
return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics));
}
internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
return base.GetEmbeddedTypes(diagnostics.DiagnosticBag);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Core/CommandHandlers/IExecuteInInteractiveCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.CommandHandlers
{
/// <summary>
/// Interface for the ExecuteInInteractiveCommand handler.
/// Ensures that the command handler can be exported via MEF
/// without actually being instantiated as all other command handlers.
/// </summary>
internal interface IExecuteInInteractiveCommandHandler
: ICommandHandler<ExecuteInInteractiveCommandArgs>
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.CommandHandlers
{
/// <summary>
/// Interface for the ExecuteInInteractiveCommand handler.
/// Ensures that the command handler can be exported via MEF
/// without actually being instantiated as all other command handlers.
/// </summary>
internal interface IExecuteInInteractiveCommandHandler
: ICommandHandler<ExecuteInInteractiveCommandArgs>
{
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.PropertySymbols.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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Goo|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:Goo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Go$$o|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:$$P|} { get; }
}
class C : I
{
public int {|Definition:P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:P|} { get; }
}
class C : I
{
public int {|Definition:$$P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:$$Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:$$Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int Definition:Area { get; }
}
class C1 : I1
{
public int Definition:Area { get { return 1; } }
}
class C2 : C1
{
public int {|Definition:$$Area|}
{
get
{
return base.Area;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|$$Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:$$Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:$$Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:$$Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_FEature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:$$Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:$$Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:$$X|} As Integer ' Rename X to Y
Get
[|X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:X|} As Integer ' Rename X to Y
Get
[|$$X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { $$[|{|Definition:P|}|] = 4 };
var b = new { P = "asdf" };
var c = new { [|P|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { [|P|] = 4 };
var b = new { P = "asdf" };
var c = new { $$[|{|Definition:P|}|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { $$[|{|Definition:P|}|] = "asdf" };
var c = new { P = 4 };
var d = new { [|P|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { [|P|] = "asdf" };
var c = new { P = 4 };
var d = new { $$[|{|Definition:P|}|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key {|Definition:a1|}}
Dim hello = query.First()
Console.WriteLine(hello.$$[|a1|].at.s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.[|{|Definition:at|}|] = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.$$[|at|].s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.[|{|Definition:s|}|] = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.at.$$[|s|])
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:$$X|}()
Sub Goo()
Console.WriteLine([|_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:X|}()
Sub Goo()
Console.WriteLine([|$$_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:$$X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:$$get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|$$get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property Goo(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property {|Definition:$$Goo|}(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property {|Definition:$$Goo|}(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property Goo(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpProperty_Cref(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
/// <see cref="[|Prop|]"/>
int {|Definition:$$Prop|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestProperty_ValueUsageInfo(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
set
{
}
}
static void Main(string[] args)
{
Console.WriteLine(Program.{|ValueUsageInfo.Read:[|Goo|]|});
Program.{|ValueUsageInfo.Write:[|Goo|]|} = 0;
Program.{|ValueUsageInfo.ReadWrite:[|Goo|]|} += 1;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPropertyReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~P:N.C.[|P|]")]
namespace N
{
class C
{
public int {|Definition:$$P|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyUseInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
namespace ConsoleApplication22
{
class C
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
}
}
</Document>
<DocumentFromSourceGenerator>
using System;
namespace ConsoleApplication22
{
class Program
{
static void Main(string[] args)
{
int temp = C.[|Goo|];
}
}
}
</DocumentFromSourceGenerator>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyInInterface(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P$$2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.P2 { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int P2 { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Goo|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_Property2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:Goo|}
{
get
{
return 1;
}
}
static void Main(string[] args)
{
int temp = Program.[|Go$$o|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:$$P|} { get; }
}
class C : I
{
public int {|Definition:P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539022")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyCascadeThroughInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I
{
int {|Definition:P|} { get; }
}
class C : I
{
public int {|Definition:$$P|} { get; }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:$$Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:$$Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int Definition:Area { get; }
}
class C1 : I1
{
public int Definition:Area { get { return 1; } }
}
class C2 : C1
{
public int {|Definition:$$Area|}
{
get
{
return base.Area;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539047")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyThroughBase4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I1
{
int {|Definition:Area|} { get; }
}
class C1 : I1
{
public int {|Definition:Area|} { get { return 1; } }
}
class C2 : C1
{
public int Area
{
get
{
return base.[|$$Area|];
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:$$Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539523")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_ExplicitProperty2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
public interface DD
{
int {|Definition:Prop|} { get; set; }
}
public class A : DD
{
int DD.{|Definition:$$Prop|}
{
get { return 1; }
set { }
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface1_Feature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:$$Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:$$Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_Api(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface3_FEature(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:$$Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T Name { get; set; }
}
interface I2
{
int {|Definition:Name|} { get; set; }
}
interface I3<T> : I2
{
new T Name { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T Name { get; set; }
int I2.{|Definition:$$Name|} { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(539885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539885")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyFromGenericInterface5(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<![CDATA[
using System;
interface I1<T>
{
T {|Definition:Name|} { get; set; }
}
interface I2
{
int Name { get; set; }
}
interface I3<T> : I2
{
new T {|Definition:Name|} { get; set; }
}
public class M<T> : I1<T>, I3<T>
{
public T {|Definition:$$Name|} { get; set; }
int I2.Name { get; set; }
}
]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:$$X|} As Integer ' Rename X to Y
Get
[|X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(540440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540440")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_PropertyFunctionValue2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<![CDATA[
Module Program
ReadOnly Property {|Definition:X|} As Integer ' Rename X to Y
Get
[|$$X|] = 1
End Get
End Property
End Module]]>
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { $$[|{|Definition:P|}|] = 4 };
var b = new { P = "asdf" };
var c = new { [|P|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { [|P|] = 4 };
var b = new { P = "asdf" };
var c = new { $$[|{|Definition:P|}|] = 4 };
var d = new { P = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { $$[|{|Definition:P|}|] = "asdf" };
var c = new { P = 4 };
var d = new { [|P|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(543125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543125")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AnonymousTypeProperties4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = new { P = 4 };
var b = new { [|P|] = "asdf" };
var c = new { P = 4 };
var d = new { $$[|{|Definition:P|}|] = "asdf" };
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key {|Definition:a1|}}
Dim hello = query.First()
Console.WriteLine(hello.$$[|a1|].at.s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.[|{|Definition:at|}|] = New With {.s = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.$$[|at|].s)
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542881")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_AnonymousTypeProperties3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a1 = New With {Key.at = New With {.[|{|Definition:s|}|] = "hello"}}
Dim query = From at In (From s In "1" Select s)
Select New With {Key a1}
Dim hello = query.First()
Console.WriteLine(hello.a1.at.$$[|s|])
End Sub
End Module
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:$$X|}()
Sub Goo()
Console.WriteLine([|_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(545576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545576")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenPropertyAndField2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Property {|Definition:X|}()
Sub Goo()
Console.WriteLine([|$$_X|])
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:$$X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:$$get_X|}(int y)
{
return base.[|get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_CascadeBetweenParameterizedVBPropertyAndCSharpMethod3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true">
<Document>
Public Class A
Public Overridable ReadOnly Property {|Definition:X|}(y As Integer) As Integer
{|Definition:Get|}
Return 0
End Get
End Property
End Class
</Document>
</Project>
<Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true">
<ProjectReference>VBAssembly</ProjectReference>
<Document>
class B : A
{
public override int {|Definition:get_X|}(int y)
{
return base.[|$$get_X|](y);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property Goo(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property {|Definition:$$Goo|}(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x[||](1L)
Dim y2 = x(1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(665876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665876")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestBasic_DefaultProperties2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Strict On
Public Interface IA
Default Property {|Definition:$$Goo|}(ByVal x As Integer) As Integer
End Interface
Public Interface IC
Inherits IA
Default Overloads Property Goo(ByVal x As Long) As String ' Rename Goo to Bar
End Interface
Class M
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
<Document>
Class M2
Sub F(x As IC)
Dim y = x(1L)
Dim y2 = x[||](1)
End Sub
End Class
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharpProperty_Cref(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface IC
{
/// <see cref="[|Prop|]"/>
int {|Definition:$$Prop|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WorkItem(538886, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538886")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestProperty_ValueUsageInfo(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
namespace ConsoleApplication22
{
class Program
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
set
{
}
}
static void Main(string[] args)
{
Console.WriteLine(Program.{|ValueUsageInfo.Read:[|Goo|]|});
Program.{|ValueUsageInfo.Write:[|Goo|]|} = 0;
Program.{|ValueUsageInfo.ReadWrite:[|Goo|]|} += 1;
}
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestPropertyReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~P:N.C.[|P|]")]
namespace N
{
class C
{
public int {|Definition:$$P|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_PropertyUseInSourceGeneratedDocument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
namespace ConsoleApplication22
{
class C
{
static public int {|Definition:G$$oo|}
{
get
{
return 1;
}
}
}
}
</Document>
<DocumentFromSourceGenerator>
using System;
namespace ConsoleApplication22
{
class Program
{
static void Main(string[] args)
{
int temp = C.[|Goo|];
}
}
}
</DocumentFromSourceGenerator>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyInInterface(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P$$2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.P2 { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaFeature2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int P2 { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestStreamingFeature(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI1(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P$$2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_AbstractStaticPropertyViaAPI2(host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface I2
{
abstract static int {|Definition:P2|} { get; set; }
}
class C2_1 : I2
{
public static int {|Definition:P$$2|} { get; set; }
}
class C2_2 : I2
{
static int I2.{|Definition:P2|} { get; set; }
}
</Document>
</Project>
</Workspace>
Await TestAPI(input, host)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableEntriesSnapshot.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Base implementation of ITableEntriesSnapshot
/// </summary>
internal abstract class AbstractTableEntriesSnapshot<TItem> : ITableEntriesSnapshot
where TItem : TableItem
{
// TODO : remove these once we move to new drop which contains API change from editor team
protected const string ProjectNames = StandardTableKeyNames.ProjectName + "s";
protected const string ProjectGuids = StandardTableKeyNames.ProjectGuid + "s";
private readonly int _version;
private readonly ImmutableArray<TItem> _items;
private ImmutableArray<ITrackingPoint> _trackingPoints;
protected AbstractTableEntriesSnapshot(int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints)
{
_version = version;
_items = items;
_trackingPoints = trackingPoints;
}
public abstract bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken);
public abstract bool TryGetValue(int index, string columnName, out object content);
public int VersionNumber
{
get
{
return _version;
}
}
public int Count
{
get
{
return _items.Length;
}
}
public int IndexOf(int index, ITableEntriesSnapshot newerSnapshot)
{
var item = GetItem(index);
if (item == null)
{
return -1;
}
if (!(newerSnapshot is AbstractTableEntriesSnapshot<TItem> ourSnapshot) || ourSnapshot.Count == 0)
{
// not ours, we don't know how to track index
return -1;
}
// quick path - this will deal with a case where we update data without any actual change
if (Count == ourSnapshot.Count)
{
var newItem = ourSnapshot.GetItem(index);
if (newItem != null && newItem.Equals(item))
{
return index;
}
}
// slow path.
for (var i = 0; i < ourSnapshot.Count; i++)
{
var newItem = ourSnapshot.GetItem(i);
if (item.EqualsIgnoringLocation(newItem))
{
return i;
}
}
// no similar item exist. table control itself will try to maintain selection
return -1;
}
public void StopTracking()
{
// remove tracking points
_trackingPoints = default;
}
public void Dispose()
=> StopTracking();
internal TItem GetItem(int index)
{
if (index < 0 || _items.Length <= index)
{
return null;
}
return _items[index];
}
protected LinePosition GetTrackingLineColumn(Document document, int index)
{
if (_trackingPoints.IsDefaultOrEmpty)
{
return LinePosition.Zero;
}
var trackingPoint = _trackingPoints[index];
if (!document.TryGetText(out var text))
{
return LinePosition.Zero;
}
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
return GetLinePosition(snapshot, trackingPoint);
}
var textBuffer = text.Container.TryGetTextBuffer();
if (textBuffer == null)
{
return LinePosition.Zero;
}
var currentSnapshot = textBuffer.CurrentSnapshot;
return GetLinePosition(currentSnapshot, trackingPoint);
}
private static LinePosition GetLinePosition(ITextSnapshot snapshot, ITrackingPoint trackingPoint)
{
var point = trackingPoint.GetPoint(snapshot);
var line = point.GetContainingLine();
return new LinePosition(line.LineNumber, point.Position - line.Start);
}
protected static bool TryNavigateTo(Workspace workspace, DocumentId documentId, LinePosition position, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
if (navigationService == null)
{
return false;
}
var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, previewTab)
.WithChangedOption(NavigationOptions.ActivateTab, activate);
return navigationService.TryNavigateToLineAndOffset(workspace, documentId, position.Line, position.Character, options, cancellationToken);
}
protected bool TryNavigateToItem(int index, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var item = GetItem(index);
var documentId = item?.DocumentId;
if (documentId == null)
{
return false;
}
var workspace = item.Workspace;
var solution = workspace.CurrentSolution;
var document = solution.GetDocument(documentId);
if (document == null)
{
return false;
}
LinePosition position;
LinePosition trackingLinePosition;
if (workspace.IsDocumentOpen(documentId) &&
(trackingLinePosition = GetTrackingLineColumn(document, index)) != LinePosition.Zero)
{
position = trackingLinePosition;
}
else
{
position = item.GetOriginalPosition();
}
return TryNavigateTo(workspace, documentId, position, previewTab, activate, cancellationToken);
}
// we don't use these
#pragma warning disable IDE0060 // Remove unused parameter - Implements interface method for sub-type
public object Identity(int index)
#pragma warning restore IDE0060 // Remove unused parameter
=> null;
public void StartCaching()
{
}
public void StopCaching()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.TableManager;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Base implementation of ITableEntriesSnapshot
/// </summary>
internal abstract class AbstractTableEntriesSnapshot<TItem> : ITableEntriesSnapshot
where TItem : TableItem
{
// TODO : remove these once we move to new drop which contains API change from editor team
protected const string ProjectNames = StandardTableKeyNames.ProjectName + "s";
protected const string ProjectGuids = StandardTableKeyNames.ProjectGuid + "s";
private readonly int _version;
private readonly ImmutableArray<TItem> _items;
private ImmutableArray<ITrackingPoint> _trackingPoints;
protected AbstractTableEntriesSnapshot(int version, ImmutableArray<TItem> items, ImmutableArray<ITrackingPoint> trackingPoints)
{
_version = version;
_items = items;
_trackingPoints = trackingPoints;
}
public abstract bool TryNavigateTo(int index, bool previewTab, bool activate, CancellationToken cancellationToken);
public abstract bool TryGetValue(int index, string columnName, out object content);
public int VersionNumber
{
get
{
return _version;
}
}
public int Count
{
get
{
return _items.Length;
}
}
public int IndexOf(int index, ITableEntriesSnapshot newerSnapshot)
{
var item = GetItem(index);
if (item == null)
{
return -1;
}
if (!(newerSnapshot is AbstractTableEntriesSnapshot<TItem> ourSnapshot) || ourSnapshot.Count == 0)
{
// not ours, we don't know how to track index
return -1;
}
// quick path - this will deal with a case where we update data without any actual change
if (Count == ourSnapshot.Count)
{
var newItem = ourSnapshot.GetItem(index);
if (newItem != null && newItem.Equals(item))
{
return index;
}
}
// slow path.
for (var i = 0; i < ourSnapshot.Count; i++)
{
var newItem = ourSnapshot.GetItem(i);
if (item.EqualsIgnoringLocation(newItem))
{
return i;
}
}
// no similar item exist. table control itself will try to maintain selection
return -1;
}
public void StopTracking()
{
// remove tracking points
_trackingPoints = default;
}
public void Dispose()
=> StopTracking();
internal TItem GetItem(int index)
{
if (index < 0 || _items.Length <= index)
{
return null;
}
return _items[index];
}
protected LinePosition GetTrackingLineColumn(Document document, int index)
{
if (_trackingPoints.IsDefaultOrEmpty)
{
return LinePosition.Zero;
}
var trackingPoint = _trackingPoints[index];
if (!document.TryGetText(out var text))
{
return LinePosition.Zero;
}
var snapshot = text.FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
return GetLinePosition(snapshot, trackingPoint);
}
var textBuffer = text.Container.TryGetTextBuffer();
if (textBuffer == null)
{
return LinePosition.Zero;
}
var currentSnapshot = textBuffer.CurrentSnapshot;
return GetLinePosition(currentSnapshot, trackingPoint);
}
private static LinePosition GetLinePosition(ITextSnapshot snapshot, ITrackingPoint trackingPoint)
{
var point = trackingPoint.GetPoint(snapshot);
var line = point.GetContainingLine();
return new LinePosition(line.LineNumber, point.Position - line.Start);
}
protected static bool TryNavigateTo(Workspace workspace, DocumentId documentId, LinePosition position, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
if (navigationService == null)
{
return false;
}
var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, previewTab)
.WithChangedOption(NavigationOptions.ActivateTab, activate);
return navigationService.TryNavigateToLineAndOffset(workspace, documentId, position.Line, position.Character, options, cancellationToken);
}
protected bool TryNavigateToItem(int index, bool previewTab, bool activate, CancellationToken cancellationToken)
{
var item = GetItem(index);
var documentId = item?.DocumentId;
if (documentId == null)
{
return false;
}
var workspace = item.Workspace;
var solution = workspace.CurrentSolution;
var document = solution.GetDocument(documentId);
if (document == null)
{
return false;
}
LinePosition position;
LinePosition trackingLinePosition;
if (workspace.IsDocumentOpen(documentId) &&
(trackingLinePosition = GetTrackingLineColumn(document, index)) != LinePosition.Zero)
{
position = trackingLinePosition;
}
else
{
position = item.GetOriginalPosition();
}
return TryNavigateTo(workspace, documentId, position, previewTab, activate, cancellationToken);
}
// we don't use these
#pragma warning disable IDE0060 // Remove unused parameter - Implements interface method for sub-type
public object Identity(int index)
#pragma warning restore IDE0060 // Remove unused parameter
=> null;
public void StartCaching()
{
}
public void StopCaching()
{
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatcher.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface IRemoteServiceCallbackDispatcher
{
RemoteServiceCallbackDispatcher.Handle CreateHandle(object? instance);
}
internal class RemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
internal readonly struct Handle : IDisposable
{
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances;
public readonly RemoteServiceCallbackId Id;
public Handle(ConcurrentDictionary<RemoteServiceCallbackId, object> callbackInstances, RemoteServiceCallbackId callbackId)
{
_callbackInstances = callbackInstances;
Id = callbackId;
}
public void Dispose()
{
Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false);
}
}
private int _callbackId = 1;
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances = new(concurrencyLevel: 2, capacity: 10);
public Handle CreateHandle(object? instance)
{
if (instance is null)
{
return default;
}
var callbackId = new RemoteServiceCallbackId(Interlocked.Increment(ref _callbackId));
var handle = new Handle(_callbackInstances, callbackId);
_callbackInstances.Add(callbackId, instance);
return handle;
}
public object GetCallback(RemoteServiceCallbackId callbackId)
{
Contract.ThrowIfFalse(_callbackInstances.TryGetValue(callbackId, out var instance));
return 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.Collections.Concurrent;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal interface IRemoteServiceCallbackDispatcher
{
RemoteServiceCallbackDispatcher.Handle CreateHandle(object? instance);
}
internal class RemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher
{
internal readonly struct Handle : IDisposable
{
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances;
public readonly RemoteServiceCallbackId Id;
public Handle(ConcurrentDictionary<RemoteServiceCallbackId, object> callbackInstances, RemoteServiceCallbackId callbackId)
{
_callbackInstances = callbackInstances;
Id = callbackId;
}
public void Dispose()
{
Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false);
}
}
private int _callbackId = 1;
private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances = new(concurrencyLevel: 2, capacity: 10);
public Handle CreateHandle(object? instance)
{
if (instance is null)
{
return default;
}
var callbackId = new RemoteServiceCallbackId(Interlocked.Increment(ref _callbackId));
var handle = new Handle(_callbackInstances, callbackId);
_callbackInstances.Add(callbackId, instance);
return handle;
}
public object GetCallback(RemoteServiceCallbackId callbackId)
{
Contract.ThrowIfFalse(_callbackInstances.TryGetValue(callbackId, out var instance));
return instance;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Portable/Compilation/AwaitExpressionInfo.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.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Structure containing all semantic information about an Await expression.
''' </summary>
Public Structure AwaitExpressionInfo
''' <summary>
''' Initializes a new instance of the <see cref="AwaitExpressionInfo" /> structure.
''' </summary>
Friend Sub New(getAwaiter As IMethodSymbol, isCompleted As IPropertySymbol, getResult As IMethodSymbol)
_getAwaiter = getAwaiter
_isCompleted = isCompleted
_getResult = getResult
End Sub
Private ReadOnly _getAwaiter As IMethodSymbol
Private ReadOnly _isCompleted As IPropertySymbol
Private ReadOnly _getResult As IMethodSymbol
''' <summary>
''' Gets the "GetAwaiter" method.
''' </summary>
Public ReadOnly Property GetAwaiterMethod As IMethodSymbol
Get
Return _getAwaiter
End Get
End Property
''' <summary>
''' Gets the "GetResult" method.
''' </summary>
Public ReadOnly Property GetResultMethod As IMethodSymbol
Get
Return _getResult
End Get
End Property
''' <summary>
''' Gets the "IsCompleted" property.
''' </summary>
Public ReadOnly Property IsCompletedProperty As IPropertySymbol
Get
Return _isCompleted
End Get
End Property
End Structure
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.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Structure containing all semantic information about an Await expression.
''' </summary>
Public Structure AwaitExpressionInfo
''' <summary>
''' Initializes a new instance of the <see cref="AwaitExpressionInfo" /> structure.
''' </summary>
Friend Sub New(getAwaiter As IMethodSymbol, isCompleted As IPropertySymbol, getResult As IMethodSymbol)
_getAwaiter = getAwaiter
_isCompleted = isCompleted
_getResult = getResult
End Sub
Private ReadOnly _getAwaiter As IMethodSymbol
Private ReadOnly _isCompleted As IPropertySymbol
Private ReadOnly _getResult As IMethodSymbol
''' <summary>
''' Gets the "GetAwaiter" method.
''' </summary>
Public ReadOnly Property GetAwaiterMethod As IMethodSymbol
Get
Return _getAwaiter
End Get
End Property
''' <summary>
''' Gets the "GetResult" method.
''' </summary>
Public ReadOnly Property GetResultMethod As IMethodSymbol
Get
Return _getResult
End Get
End Property
''' <summary>
''' Gets the "IsCompleted" property.
''' </summary>
Public ReadOnly Property IsCompletedProperty As IPropertySymbol
Get
Return _isCompleted
End Get
End Property
End Structure
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Test/Semantic/AssemblyAttributes.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 Xunit
| ' Licensed to the .NET Foundation under one or more 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 Xunit
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/ClassifiedSpansAndHighlightSpan.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Classification
{
internal readonly struct ClassifiedSpansAndHighlightSpan
{
public const string Key = nameof(ClassifiedSpansAndHighlightSpan);
public readonly ImmutableArray<ClassifiedSpan> ClassifiedSpans;
public readonly TextSpan HighlightSpan;
public ClassifiedSpansAndHighlightSpan(
ImmutableArray<ClassifiedSpan> classifiedSpans,
TextSpan highlightSpan)
{
ClassifiedSpans = classifiedSpans;
HighlightSpan = highlightSpan;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Classification
{
internal readonly struct ClassifiedSpansAndHighlightSpan
{
public const string Key = nameof(ClassifiedSpansAndHighlightSpan);
public readonly ImmutableArray<ClassifiedSpan> ClassifiedSpans;
public readonly TextSpan HighlightSpan;
public ClassifiedSpansAndHighlightSpan(
ImmutableArray<ClassifiedSpan> classifiedSpans,
TextSpan highlightSpan)
{
ClassifiedSpans = classifiedSpans;
HighlightSpan = highlightSpan;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Core/EditorConfigSettings/Data/AnalyzerSetting.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data
{
internal class AnalyzerSetting
{
private readonly DiagnosticDescriptor _descriptor;
private readonly AnalyzerSettingsUpdater _settingsUpdater;
public AnalyzerSetting(DiagnosticDescriptor descriptor,
ReportDiagnostic effectiveSeverity,
AnalyzerSettingsUpdater settingsUpdater,
Language language,
SettingLocation location)
{
_descriptor = descriptor;
_settingsUpdater = settingsUpdater;
DiagnosticSeverity severity = default;
if (effectiveSeverity == ReportDiagnostic.Default)
{
severity = descriptor.DefaultSeverity;
}
else if (effectiveSeverity.ToDiagnosticSeverity() is DiagnosticSeverity severity1)
{
severity = severity1;
}
var enabled = effectiveSeverity != ReportDiagnostic.Suppress;
IsEnabled = enabled;
Severity = severity;
Language = language;
Location = location;
}
public string Id => _descriptor.Id;
public string Title => _descriptor.Title.ToString(CultureInfo.CurrentUICulture);
public string Description => _descriptor.Description.ToString(CultureInfo.CurrentUICulture);
public string Category => _descriptor.Category;
public DiagnosticSeverity Severity { get; private set; }
public bool IsEnabled { get; private set; }
public Language Language { get; }
public SettingLocation Location { get; }
internal void ChangeSeverity(DiagnosticSeverity severity)
{
if (severity == Severity)
return;
Severity = severity;
_settingsUpdater.QueueUpdate(this, severity);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data
{
internal class AnalyzerSetting
{
private readonly DiagnosticDescriptor _descriptor;
private readonly AnalyzerSettingsUpdater _settingsUpdater;
public AnalyzerSetting(DiagnosticDescriptor descriptor,
ReportDiagnostic effectiveSeverity,
AnalyzerSettingsUpdater settingsUpdater,
Language language,
SettingLocation location)
{
_descriptor = descriptor;
_settingsUpdater = settingsUpdater;
DiagnosticSeverity severity = default;
if (effectiveSeverity == ReportDiagnostic.Default)
{
severity = descriptor.DefaultSeverity;
}
else if (effectiveSeverity.ToDiagnosticSeverity() is DiagnosticSeverity severity1)
{
severity = severity1;
}
var enabled = effectiveSeverity != ReportDiagnostic.Suppress;
IsEnabled = enabled;
Severity = severity;
Language = language;
Location = location;
}
public string Id => _descriptor.Id;
public string Title => _descriptor.Title.ToString(CultureInfo.CurrentUICulture);
public string Description => _descriptor.Description.ToString(CultureInfo.CurrentUICulture);
public string Category => _descriptor.Category;
public DiagnosticSeverity Severity { get; private set; }
public bool IsEnabled { get; private set; }
public Language Language { get; }
public SettingLocation Location { get; }
internal void ChangeSeverity(DiagnosticSeverity severity)
{
if (severity == Severity)
return;
Severity = severity;
_settingsUpdater.QueueUpdate(this, severity);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Test/Emit/PDB/PDBNamespaceScopes.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.IO
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBNamespaceScopes
Inherits BasicTestBase
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ProjectLevelXmlImportsWithoutRootNamespace()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
imports <xmlns:file1="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile1">
Imports System
Imports System.Collections.Generic
Imports file1=System.Collections
Imports typefile1 = System.String
Imports ignoredAliasFile1 = System.Collections.Generic.Dictionary(Of String, String) ' ignored
Imports System.Collections.Generic.List(Of String) ' ignored
Imports NS1.NS2.C1.C2
Imports C3ALIAS=NS1.NS2.C1.C2.C3
Namespace Boo
Partial Class C1
Public Field1 as Object = new Object()
Public Shared Sub Main()
Console.WriteLine("Hello World!")
End Sub
Public Shared Sub DoStuff()
Console.WriteLine("Hello World again!")
End Sub
End Class
End Namespace
</file>
<file name="b.vb">
Option Strict On
imports <xmlns:file2="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile2">
Imports System.Diagnostics
Imports file2=System.Collections
Imports typefile2 = System.Int32
Imports System.Collections.ArrayList ' import type without alias
Namespace Boo
Partial Class C1
Public Field2 as Object = new Object()
End Class
End Namespace
' C2 has empty current namespace
Class C2
Public Shared Sub DoStuff2()
System.Console.WriteLine("Hello World again and again!")
End Sub
End Class
Namespace NS1.NS2
Public Class C1
Public Class C2
Public Class C3
End Class
End Class
End Class
End Namespace
</file>
</compilation>
Dim globalImports = GlobalImport.Parse(
"<xmlns:prjlevel1=""http://NewNamespace"">",
"<xmlns=""http://NewNamespace/prjlevel"">",
"prjlevel=System.Collections.Generic",
"System.Threading",
"typeproj1=System.Int64",
"prjlevelIgnored=System.Collections.Generic.List(Of String)",
"System.Collections.Generic.List(Of String)",
"System.Collections.ArrayList")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.DebugExe.WithGlobalImports(globalImports).WithRootNamespace(""))
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="40-26-2D-BC-C1-9A-0B-B7-68-F0-ED-8E-CA-70-22-73-78-33-EA-C0"/>
<file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="94-7A-FB-0B-3B-B0-EF-63-B9-ED-E8-A9-D0-58-BA-D0-21-07-C2-CE"/>
</files>
<entryPoint declaringType="Boo.C1" methodName="Main"/>
<methods>
<method containingType="Boo.C1" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" startLine="22" startColumn="12" endLine="22" endColumn="43" document="1"/>
<entry offset="0x17" startLine="16" startColumn="12" endLine="16" endColumn="43" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x28">
<xmlnamespace prefix="file1" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile1" importlevel="file"/>
<alias name="file1" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile1" target="System.String" kind="namespace" importlevel="file"/>
<alias name="C3ALIAS" target="NS1.NS2.C1.C2.C3" kind="namespace" importlevel="file"/>
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<type name="NS1.NS2.C1.C2" importlevel="file"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name="Boo"/>
</scope>
</method>
<method containingType="Boo.C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="24" startColumn="5" endLine="24" endColumn="29" document="1"/>
<entry offset="0x1" startLine="25" startColumn="9" endLine="25" endColumn="42" document="1"/>
<entry offset="0xc" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="Boo.C1" name="DoStuff">
<sequencePoints>
<entry offset="0x0" startLine="28" startColumn="5" endLine="28" endColumn="32" document="1"/>
<entry offset="0x1" startLine="29" startColumn="9" endLine="29" endColumn="48" document="1"/>
<entry offset="0xc" startLine="30" startColumn="5" endLine="30" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="C2" name="DoStuff2">
<sequencePoints>
<entry offset="0x0" startLine="23" startColumn="5" endLine="23" endColumn="33" document="2"/>
<entry offset="0x1" startLine="24" startColumn="9" endLine="24" endColumn="65" document="2"/>
<entry offset="0xc" startLine="25" startColumn="5" endLine="25" endColumn="12" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<xmlnamespace prefix="file2" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile2" importlevel="file"/>
<alias name="file2" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile2" target="System.Int32" kind="namespace" importlevel="file"/>
<namespace name="System.Diagnostics" importlevel="file"/>
<type name="System.Collections.ArrayList" importlevel="file"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ProjectLevelXmlImportsWithRootNamespace()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
imports <xmlns:file1="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile1">
Imports System
Imports System.Collections.Generic
Imports file1=System.Collections
Imports typefile1 = System.String
Imports ignoredAliasFile1 = System.Collections.Generic.Dictionary(Of String, String) ' ignored
Imports System.Collections.Generic.List(Of String) ' ignored
Imports DefaultNamespace.NS1.NS2.C1.C2
Imports C3ALIAS=DefaultNamespace.NS1.NS2.C1.C2.C3
Namespace Boo
Partial Class C1
Public Field1 as Object = new Object()
Public Shared Sub Main()
Console.WriteLine("Hello World!")
End Sub
Public Shared Sub DoStuff()
Console.WriteLine("Hello World again!")
End Sub
End Class
End Namespace
</file>
<file name="b.vb">
Option Strict On
imports <xmlns:file2="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile2">
Imports System.Diagnostics
Imports file2=System.Collections
Imports typefile2 = System.Int32
Imports System.Collections.ArrayList ' import type without alias
Namespace Boo
Partial Class C1
Public Field2 as Object = new Object()
End Class
End Namespace
' C2 has empty current namespace
Class C2
Public Shared Sub DoStuff2()
System.Console.WriteLine("Hello World again and again!")
End Sub
End Class
Namespace NS1.NS2
Public Class C1
Public Class C2
Public Class C3
End Class
End Class
End Class
End Namespace
</file>
</compilation>
Dim globalImports = GlobalImport.Parse(
"<xmlns:prjlevel1=""http://NewNamespace"">",
"<xmlns=""http://NewNamespace/prjlevel"">",
"prjlevel=System.Collections.Generic",
"System.Threading",
"typeproj1=System.Int64",
"prjlevelIgnored=System.Collections.Generic.List(Of String)",
"System.Collections.Generic.List(Of String)",
"System.Collections.ArrayList")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.DebugExe.WithGlobalImports(globalImports).WithRootNamespace("DefaultNamespace"))
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="93-20-A5-3E-2C-50-B2-0E-7C-D6-29-3F-E9-9E-33-72-A6-21-FD-3F"/>
<file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="94-7A-FB-0B-3B-B0-EF-63-B9-ED-E8-A9-D0-58-BA-D0-21-07-C2-CE"/>
</files>
<entryPoint declaringType="DefaultNamespace.Boo.C1" methodName="Main"/>
<methods>
<method containingType="DefaultNamespace.Boo.C1" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" startLine="22" startColumn="12" endLine="22" endColumn="43" document="1"/>
<entry offset="0x17" startLine="16" startColumn="12" endLine="16" endColumn="43" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x28">
<xmlnamespace prefix="file1" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile1" importlevel="file"/>
<alias name="file1" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile1" target="System.String" kind="namespace" importlevel="file"/>
<alias name="C3ALIAS" target="DefaultNamespace.NS1.NS2.C1.C2.C3" kind="namespace" importlevel="file"/>
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<type name="DefaultNamespace.NS1.NS2.C1.C2" importlevel="file"/>
<defaultnamespace name="DefaultNamespace"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name="DefaultNamespace.Boo"/>
</scope>
</method>
<method containingType="DefaultNamespace.Boo.C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="24" startColumn="5" endLine="24" endColumn="29" document="1"/>
<entry offset="0x1" startLine="25" startColumn="9" endLine="25" endColumn="42" document="1"/>
<entry offset="0xc" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="DefaultNamespace.Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="DefaultNamespace.Boo.C1" name="DoStuff">
<sequencePoints>
<entry offset="0x0" startLine="28" startColumn="5" endLine="28" endColumn="32" document="1"/>
<entry offset="0x1" startLine="29" startColumn="9" endLine="29" endColumn="48" document="1"/>
<entry offset="0xc" startLine="30" startColumn="5" endLine="30" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="DefaultNamespace.Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="DefaultNamespace.C2" name="DoStuff2">
<sequencePoints>
<entry offset="0x0" startLine="23" startColumn="5" endLine="23" endColumn="33" document="2"/>
<entry offset="0x1" startLine="24" startColumn="9" endLine="24" endColumn="65" document="2"/>
<entry offset="0xc" startLine="25" startColumn="5" endLine="25" endColumn="12" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<xmlnamespace prefix="file2" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile2" importlevel="file"/>
<alias name="file2" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile2" target="System.Int32" kind="namespace" importlevel="file"/>
<namespace name="System.Diagnostics" importlevel="file"/>
<type name="System.Collections.ArrayList" importlevel="file"/>
<defaultnamespace name="DefaultNamespace"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name="DefaultNamespace"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub EmittingPdbVsNot()
Dim source =
<compilation name="EmittingPdbVsNot">
<file>
Imports System
Imports X = System.IO.FileStream
Class C
Dim x As Integer = 1
Shared y As Integer = 1
Sub New()
Console.WriteLine()
End Sub
End Class
</file>
</compilation>
Dim c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll)
Dim peStream1 = New MemoryStream()
Dim peStream2 = New MemoryStream()
Dim pdbStream = New MemoryStream()
Dim emitResult1 = c.Emit(peStream:=peStream1, pdbStream:=pdbStream)
Dim emitResult2 = c.Emit(peStream:=peStream2)
MetadataValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NoPiaNeedsDesktop)>
Public Sub ImportedNoPiaTypes()
Dim sourceLib =
<compilation name="ImportedNoPiaTypesAssemblyName">
<file><![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
<Assembly:Guid("11111111-1111-1111-1111-111111111111")>
<Assembly:ImportedFromTypeLib("Goo")>
<Assembly:TypeLibVersion(1, 0)>
Namespace N
Public Enum E
Value1 = 1
End Enum
Public Structure S1
Public A1 As Integer
Public A2 As Integer
End Structure
Public Structure S2
Public Const Value2 As Integer = 2
End Structure
Public Structure SBad
Public A3 As Integer
Public Const Value3 As Integer = 3
End Structure
<ComImport, Guid("22222222-2222-2222-2222-222222222222")>
Public Interface I
Sub F()
End Interface
Public Interface IBad
Sub F()
End Interface
End Namespace
]]>
</file>
</compilation>
Dim source =
<compilation>
<file>
Imports System
Imports N.E
Imports N.SBad
Imports Z1 = N.S1
Imports Z2 = N.S2
Imports ZBad = N.SBad
Imports NI = N.I
Imports NIBad = N.IBad
Class C
Dim i As NI
Sub M
Console.WriteLine(Value1)
Console.WriteLine(Z2.Value2)
Console.WriteLine(New Z1())
End Sub
End Class
</file>
</compilation>
Dim globalImports = GlobalImport.Parse(
"GlobalNIBad = N.IBad",
"GlobalZ1 = N.S1",
"GlobalZ2 = N.S2",
"GlobalZBad = N.SBad",
"GlobalNI = N.I")
Dim libRef = CreateCompilationWithMscorlib40(sourceLib).EmitToImageReference(embedInteropTypes:=True)
Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {libRef}, options:=TestOptions.DebugDll.WithGlobalImports(globalImports))
Dim v = CompileAndVerify(compilation)
v.Diagnostics.Verify(
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports N.SBad"),
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports ZBad = N.SBad"),
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports NIBad = N.IBad"))
' Imports of embedded types are currently omitted:
v.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="13" startColumn="5" endLine="13" endColumn="10" document="1"/>
<entry offset="0x1" startLine="14" startColumn="9" endLine="14" endColumn="34" document="1"/>
<entry offset="0x8" startLine="15" startColumn="9" endLine="15" endColumn="37" document="1"/>
<entry offset="0xf" startLine="16" startColumn="9" endLine="16" endColumn="36" document="1"/>
<entry offset="0x23" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x24">
<namespace name="System" importlevel="file"/>
<defunct name="&ImportedNoPiaTypesAssemblyName"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ImportedTypeWithUnknownBase()
Dim sourceLib1 =
<compilation>
<file>
Namespace N
Public Class A
End Class
End Namespace
</file>
</compilation>
Dim sourceLib2 =
<compilation name="LibRef2">
<file>
Namespace N
Public Class B
Inherits A
End Class
End Namespace
</file>
</compilation>
Dim source =
<compilation>
<file>
Imports System
Imports X = N.B
Class C
Sub M()
Console.WriteLine()
End Sub
End Class
</file>
</compilation>
Dim libRef1 = CreateCompilationWithMscorlib40(sourceLib1).EmitToImageReference()
Dim libRef2 = CreateCompilationWithMscorlib40AndReferences(sourceLib2, {libRef1}).EmitToImageReference()
Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {libRef2})
Dim v = CompileAndVerify(compilation)
v.Diagnostics.Verify(
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports X = N.B"))
v.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="6" startColumn="9" endLine="6" endColumn="28" document="1"/>
<entry offset="0x5" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x6">
<alias name="X" target="N.B" kind="namespace" importlevel="file"/>
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.IO
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBNamespaceScopes
Inherits BasicTestBase
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ProjectLevelXmlImportsWithoutRootNamespace()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
imports <xmlns:file1="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile1">
Imports System
Imports System.Collections.Generic
Imports file1=System.Collections
Imports typefile1 = System.String
Imports ignoredAliasFile1 = System.Collections.Generic.Dictionary(Of String, String) ' ignored
Imports System.Collections.Generic.List(Of String) ' ignored
Imports NS1.NS2.C1.C2
Imports C3ALIAS=NS1.NS2.C1.C2.C3
Namespace Boo
Partial Class C1
Public Field1 as Object = new Object()
Public Shared Sub Main()
Console.WriteLine("Hello World!")
End Sub
Public Shared Sub DoStuff()
Console.WriteLine("Hello World again!")
End Sub
End Class
End Namespace
</file>
<file name="b.vb">
Option Strict On
imports <xmlns:file2="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile2">
Imports System.Diagnostics
Imports file2=System.Collections
Imports typefile2 = System.Int32
Imports System.Collections.ArrayList ' import type without alias
Namespace Boo
Partial Class C1
Public Field2 as Object = new Object()
End Class
End Namespace
' C2 has empty current namespace
Class C2
Public Shared Sub DoStuff2()
System.Console.WriteLine("Hello World again and again!")
End Sub
End Class
Namespace NS1.NS2
Public Class C1
Public Class C2
Public Class C3
End Class
End Class
End Class
End Namespace
</file>
</compilation>
Dim globalImports = GlobalImport.Parse(
"<xmlns:prjlevel1=""http://NewNamespace"">",
"<xmlns=""http://NewNamespace/prjlevel"">",
"prjlevel=System.Collections.Generic",
"System.Threading",
"typeproj1=System.Int64",
"prjlevelIgnored=System.Collections.Generic.List(Of String)",
"System.Collections.Generic.List(Of String)",
"System.Collections.ArrayList")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.DebugExe.WithGlobalImports(globalImports).WithRootNamespace(""))
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="40-26-2D-BC-C1-9A-0B-B7-68-F0-ED-8E-CA-70-22-73-78-33-EA-C0"/>
<file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="94-7A-FB-0B-3B-B0-EF-63-B9-ED-E8-A9-D0-58-BA-D0-21-07-C2-CE"/>
</files>
<entryPoint declaringType="Boo.C1" methodName="Main"/>
<methods>
<method containingType="Boo.C1" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" startLine="22" startColumn="12" endLine="22" endColumn="43" document="1"/>
<entry offset="0x17" startLine="16" startColumn="12" endLine="16" endColumn="43" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x28">
<xmlnamespace prefix="file1" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile1" importlevel="file"/>
<alias name="file1" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile1" target="System.String" kind="namespace" importlevel="file"/>
<alias name="C3ALIAS" target="NS1.NS2.C1.C2.C3" kind="namespace" importlevel="file"/>
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<type name="NS1.NS2.C1.C2" importlevel="file"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name="Boo"/>
</scope>
</method>
<method containingType="Boo.C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="24" startColumn="5" endLine="24" endColumn="29" document="1"/>
<entry offset="0x1" startLine="25" startColumn="9" endLine="25" endColumn="42" document="1"/>
<entry offset="0xc" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="Boo.C1" name="DoStuff">
<sequencePoints>
<entry offset="0x0" startLine="28" startColumn="5" endLine="28" endColumn="32" document="1"/>
<entry offset="0x1" startLine="29" startColumn="9" endLine="29" endColumn="48" document="1"/>
<entry offset="0xc" startLine="30" startColumn="5" endLine="30" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="C2" name="DoStuff2">
<sequencePoints>
<entry offset="0x0" startLine="23" startColumn="5" endLine="23" endColumn="33" document="2"/>
<entry offset="0x1" startLine="24" startColumn="9" endLine="24" endColumn="65" document="2"/>
<entry offset="0xc" startLine="25" startColumn="5" endLine="25" endColumn="12" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<xmlnamespace prefix="file2" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile2" importlevel="file"/>
<alias name="file2" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile2" target="System.Int32" kind="namespace" importlevel="file"/>
<namespace name="System.Diagnostics" importlevel="file"/>
<type name="System.Collections.ArrayList" importlevel="file"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ProjectLevelXmlImportsWithRootNamespace()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
imports <xmlns:file1="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile1">
Imports System
Imports System.Collections.Generic
Imports file1=System.Collections
Imports typefile1 = System.String
Imports ignoredAliasFile1 = System.Collections.Generic.Dictionary(Of String, String) ' ignored
Imports System.Collections.Generic.List(Of String) ' ignored
Imports DefaultNamespace.NS1.NS2.C1.C2
Imports C3ALIAS=DefaultNamespace.NS1.NS2.C1.C2.C3
Namespace Boo
Partial Class C1
Public Field1 as Object = new Object()
Public Shared Sub Main()
Console.WriteLine("Hello World!")
End Sub
Public Shared Sub DoStuff()
Console.WriteLine("Hello World again!")
End Sub
End Class
End Namespace
</file>
<file name="b.vb">
Option Strict On
imports <xmlns:file2="http://stuff/fromFile">
imports <xmlns="http://stuff/fromFile2">
Imports System.Diagnostics
Imports file2=System.Collections
Imports typefile2 = System.Int32
Imports System.Collections.ArrayList ' import type without alias
Namespace Boo
Partial Class C1
Public Field2 as Object = new Object()
End Class
End Namespace
' C2 has empty current namespace
Class C2
Public Shared Sub DoStuff2()
System.Console.WriteLine("Hello World again and again!")
End Sub
End Class
Namespace NS1.NS2
Public Class C1
Public Class C2
Public Class C3
End Class
End Class
End Class
End Namespace
</file>
</compilation>
Dim globalImports = GlobalImport.Parse(
"<xmlns:prjlevel1=""http://NewNamespace"">",
"<xmlns=""http://NewNamespace/prjlevel"">",
"prjlevel=System.Collections.Generic",
"System.Threading",
"typeproj1=System.Int64",
"prjlevelIgnored=System.Collections.Generic.List(Of String)",
"System.Collections.Generic.List(Of String)",
"System.Collections.ArrayList")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.DebugExe.WithGlobalImports(globalImports).WithRootNamespace("DefaultNamespace"))
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="93-20-A5-3E-2C-50-B2-0E-7C-D6-29-3F-E9-9E-33-72-A6-21-FD-3F"/>
<file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="94-7A-FB-0B-3B-B0-EF-63-B9-ED-E8-A9-D0-58-BA-D0-21-07-C2-CE"/>
</files>
<entryPoint declaringType="DefaultNamespace.Boo.C1" methodName="Main"/>
<methods>
<method containingType="DefaultNamespace.Boo.C1" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" startLine="22" startColumn="12" endLine="22" endColumn="43" document="1"/>
<entry offset="0x17" startLine="16" startColumn="12" endLine="16" endColumn="43" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x28">
<xmlnamespace prefix="file1" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile1" importlevel="file"/>
<alias name="file1" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile1" target="System.String" kind="namespace" importlevel="file"/>
<alias name="C3ALIAS" target="DefaultNamespace.NS1.NS2.C1.C2.C3" kind="namespace" importlevel="file"/>
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<type name="DefaultNamespace.NS1.NS2.C1.C2" importlevel="file"/>
<defaultnamespace name="DefaultNamespace"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name="DefaultNamespace.Boo"/>
</scope>
</method>
<method containingType="DefaultNamespace.Boo.C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="24" startColumn="5" endLine="24" endColumn="29" document="1"/>
<entry offset="0x1" startLine="25" startColumn="9" endLine="25" endColumn="42" document="1"/>
<entry offset="0xc" startLine="26" startColumn="5" endLine="26" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="DefaultNamespace.Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="DefaultNamespace.Boo.C1" name="DoStuff">
<sequencePoints>
<entry offset="0x0" startLine="28" startColumn="5" endLine="28" endColumn="32" document="1"/>
<entry offset="0x1" startLine="29" startColumn="9" endLine="29" endColumn="48" document="1"/>
<entry offset="0xc" startLine="30" startColumn="5" endLine="30" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<importsforward declaringType="DefaultNamespace.Boo.C1" methodName=".ctor"/>
</scope>
</method>
<method containingType="DefaultNamespace.C2" name="DoStuff2">
<sequencePoints>
<entry offset="0x0" startLine="23" startColumn="5" endLine="23" endColumn="33" document="2"/>
<entry offset="0x1" startLine="24" startColumn="9" endLine="24" endColumn="65" document="2"/>
<entry offset="0xc" startLine="25" startColumn="5" endLine="25" endColumn="12" document="2"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xd">
<xmlnamespace prefix="file2" name="http://stuff/fromFile" importlevel="file"/>
<xmlnamespace prefix="" name="http://stuff/fromFile2" importlevel="file"/>
<alias name="file2" target="System.Collections" kind="namespace" importlevel="file"/>
<alias name="typefile2" target="System.Int32" kind="namespace" importlevel="file"/>
<namespace name="System.Diagnostics" importlevel="file"/>
<type name="System.Collections.ArrayList" importlevel="file"/>
<defaultnamespace name="DefaultNamespace"/>
<xmlnamespace prefix="prjlevel1" name="http://NewNamespace" importlevel="project"/>
<xmlnamespace prefix="" name="http://NewNamespace/prjlevel" importlevel="project"/>
<alias name="prjlevel" target="System.Collections.Generic" kind="namespace" importlevel="project"/>
<alias name="typeproj1" target="System.Int64" kind="namespace" importlevel="project"/>
<namespace name="System.Threading" importlevel="project"/>
<type name="System.Collections.ArrayList" importlevel="project"/>
<currentnamespace name="DefaultNamespace"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub EmittingPdbVsNot()
Dim source =
<compilation name="EmittingPdbVsNot">
<file>
Imports System
Imports X = System.IO.FileStream
Class C
Dim x As Integer = 1
Shared y As Integer = 1
Sub New()
Console.WriteLine()
End Sub
End Class
</file>
</compilation>
Dim c = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll)
Dim peStream1 = New MemoryStream()
Dim peStream2 = New MemoryStream()
Dim pdbStream = New MemoryStream()
Dim emitResult1 = c.Emit(peStream:=peStream1, pdbStream:=pdbStream)
Dim emitResult2 = c.Emit(peStream:=peStream2)
MetadataValidation.VerifyMetadataEqualModuloMvid(peStream1, peStream2)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NoPiaNeedsDesktop)>
Public Sub ImportedNoPiaTypes()
Dim sourceLib =
<compilation name="ImportedNoPiaTypesAssemblyName">
<file><![CDATA[
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
<Assembly:Guid("11111111-1111-1111-1111-111111111111")>
<Assembly:ImportedFromTypeLib("Goo")>
<Assembly:TypeLibVersion(1, 0)>
Namespace N
Public Enum E
Value1 = 1
End Enum
Public Structure S1
Public A1 As Integer
Public A2 As Integer
End Structure
Public Structure S2
Public Const Value2 As Integer = 2
End Structure
Public Structure SBad
Public A3 As Integer
Public Const Value3 As Integer = 3
End Structure
<ComImport, Guid("22222222-2222-2222-2222-222222222222")>
Public Interface I
Sub F()
End Interface
Public Interface IBad
Sub F()
End Interface
End Namespace
]]>
</file>
</compilation>
Dim source =
<compilation>
<file>
Imports System
Imports N.E
Imports N.SBad
Imports Z1 = N.S1
Imports Z2 = N.S2
Imports ZBad = N.SBad
Imports NI = N.I
Imports NIBad = N.IBad
Class C
Dim i As NI
Sub M
Console.WriteLine(Value1)
Console.WriteLine(Z2.Value2)
Console.WriteLine(New Z1())
End Sub
End Class
</file>
</compilation>
Dim globalImports = GlobalImport.Parse(
"GlobalNIBad = N.IBad",
"GlobalZ1 = N.S1",
"GlobalZ2 = N.S2",
"GlobalZBad = N.SBad",
"GlobalNI = N.I")
Dim libRef = CreateCompilationWithMscorlib40(sourceLib).EmitToImageReference(embedInteropTypes:=True)
Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {libRef}, options:=TestOptions.DebugDll.WithGlobalImports(globalImports))
Dim v = CompileAndVerify(compilation)
v.Diagnostics.Verify(
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports N.SBad"),
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports ZBad = N.SBad"),
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports NIBad = N.IBad"))
' Imports of embedded types are currently omitted:
v.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="13" startColumn="5" endLine="13" endColumn="10" document="1"/>
<entry offset="0x1" startLine="14" startColumn="9" endLine="14" endColumn="34" document="1"/>
<entry offset="0x8" startLine="15" startColumn="9" endLine="15" endColumn="37" document="1"/>
<entry offset="0xf" startLine="16" startColumn="9" endLine="16" endColumn="36" document="1"/>
<entry offset="0x23" startLine="17" startColumn="5" endLine="17" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x24">
<namespace name="System" importlevel="file"/>
<defunct name="&ImportedNoPiaTypesAssemblyName"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ImportedTypeWithUnknownBase()
Dim sourceLib1 =
<compilation>
<file>
Namespace N
Public Class A
End Class
End Namespace
</file>
</compilation>
Dim sourceLib2 =
<compilation name="LibRef2">
<file>
Namespace N
Public Class B
Inherits A
End Class
End Namespace
</file>
</compilation>
Dim source =
<compilation>
<file>
Imports System
Imports X = N.B
Class C
Sub M()
Console.WriteLine()
End Sub
End Class
</file>
</compilation>
Dim libRef1 = CreateCompilationWithMscorlib40(sourceLib1).EmitToImageReference()
Dim libRef2 = CreateCompilationWithMscorlib40AndReferences(sourceLib2, {libRef1}).EmitToImageReference()
Dim compilation = CreateCompilationWithMscorlib40AndReferences(source, {libRef2})
Dim v = CompileAndVerify(compilation)
v.Diagnostics.Verify(
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports X = N.B"))
v.VerifyPdb("C.M",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C" name="M">
<sequencePoints>
<entry offset="0x0" startLine="6" startColumn="9" endLine="6" endColumn="28" document="1"/>
<entry offset="0x5" startLine="7" startColumn="5" endLine="7" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x6">
<alias name="X" target="N.B" kind="namespace" importlevel="file"/>
<namespace name="System" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharpTest/CodeActions/Preview/ErrorCases/ExceptionInCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ErrorCases
{
internal class ExceptionInCodeAction : CodeRefactoringProvider
{
public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
context.RegisterRefactoring(new ExceptionCodeAction(), context.Span);
return Task.CompletedTask;
}
internal class ExceptionCodeAction : CodeAction
{
public override string Title
{
get
{
throw new Exception($"Exception thrown from get_Title in {nameof(ExceptionCodeAction)}");
}
}
public override string EquivalenceKey
{
get
{
throw new Exception($"Exception thrown from get_EquivalenceKey in {nameof(ExceptionCodeAction)}");
}
}
protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from ComputePreviewOperationsAsync in {nameof(ExceptionCodeAction)}");
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from ComputeOperationsAsync in {nameof(ExceptionCodeAction)}");
protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from GetChangedDocumentAsync in {nameof(ExceptionCodeAction)}");
protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from GetChangedSolutionAsync in {nameof(ExceptionCodeAction)}");
protected override Task<Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from PostProcessChangesAsync in {nameof(ExceptionCodeAction)}");
public override int GetHashCode()
=> throw new Exception($"Exception thrown from GetHashCode in {nameof(ExceptionCodeAction)}");
public override bool Equals(object obj)
=> throw new Exception($"Exception thrown from Equals in {nameof(ExceptionCodeAction)}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ErrorCases
{
internal class ExceptionInCodeAction : CodeRefactoringProvider
{
public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
context.RegisterRefactoring(new ExceptionCodeAction(), context.Span);
return Task.CompletedTask;
}
internal class ExceptionCodeAction : CodeAction
{
public override string Title
{
get
{
throw new Exception($"Exception thrown from get_Title in {nameof(ExceptionCodeAction)}");
}
}
public override string EquivalenceKey
{
get
{
throw new Exception($"Exception thrown from get_EquivalenceKey in {nameof(ExceptionCodeAction)}");
}
}
protected override Task<IEnumerable<CodeActionOperation>> ComputePreviewOperationsAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from ComputePreviewOperationsAsync in {nameof(ExceptionCodeAction)}");
protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from ComputeOperationsAsync in {nameof(ExceptionCodeAction)}");
protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from GetChangedDocumentAsync in {nameof(ExceptionCodeAction)}");
protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from GetChangedSolutionAsync in {nameof(ExceptionCodeAction)}");
protected override Task<Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken)
=> throw new Exception($"Exception thrown from PostProcessChangesAsync in {nameof(ExceptionCodeAction)}");
public override int GetHashCode()
=> throw new Exception($"Exception thrown from GetHashCode in {nameof(ExceptionCodeAction)}");
public override bool Equals(object obj)
=> throw new Exception($"Exception thrown from Equals in {nameof(ExceptionCodeAction)}");
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Core/Portable/Emit/EditAndContinue/AddedOrChangedMethodInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal readonly struct AddedOrChangedMethodInfo
{
public readonly DebugId MethodId;
// locals:
public readonly ImmutableArray<EncLocalInfo> Locals;
// lambdas, closures:
public readonly ImmutableArray<LambdaDebugInfo> LambdaDebugInfo;
public readonly ImmutableArray<ClosureDebugInfo> ClosureDebugInfo;
// state machines:
public readonly string? StateMachineTypeName;
public readonly ImmutableArray<EncHoistedLocalInfo> StateMachineHoistedLocalSlotsOpt;
public readonly ImmutableArray<Cci.ITypeReference?> StateMachineAwaiterSlotsOpt;
public AddedOrChangedMethodInfo(
DebugId methodId,
ImmutableArray<EncLocalInfo> locals,
ImmutableArray<LambdaDebugInfo> lambdaDebugInfo,
ImmutableArray<ClosureDebugInfo> closureDebugInfo,
string? stateMachineTypeName,
ImmutableArray<EncHoistedLocalInfo> stateMachineHoistedLocalSlotsOpt,
ImmutableArray<Cci.ITypeReference?> stateMachineAwaiterSlotsOpt)
{
// An updated method will carry its id over,
// an added method id has generation set to the current generation ordinal.
Debug.Assert(methodId.Generation >= 0);
// each state machine has to have awaiters:
Debug.Assert(stateMachineAwaiterSlotsOpt.IsDefault == (stateMachineTypeName == null));
// a state machine might not have hoisted variables:
Debug.Assert(stateMachineHoistedLocalSlotsOpt.IsDefault || (stateMachineTypeName != null));
MethodId = methodId;
Locals = locals;
LambdaDebugInfo = lambdaDebugInfo;
ClosureDebugInfo = closureDebugInfo;
StateMachineTypeName = stateMachineTypeName;
StateMachineHoistedLocalSlotsOpt = stateMachineHoistedLocalSlotsOpt;
StateMachineAwaiterSlotsOpt = stateMachineAwaiterSlotsOpt;
}
public AddedOrChangedMethodInfo MapTypes(SymbolMatcher map)
{
var mappedLocals = ImmutableArray.CreateRange(Locals, MapLocalInfo, map);
var mappedHoistedLocalSlots = StateMachineHoistedLocalSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineHoistedLocalSlotsOpt, MapHoistedLocalSlot, map);
var mappedAwaiterSlots = StateMachineAwaiterSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineAwaiterSlotsOpt, static (typeRef, map) => (typeRef is null) ? null : map.MapReference(typeRef), map);
return new AddedOrChangedMethodInfo(MethodId, mappedLocals, LambdaDebugInfo, ClosureDebugInfo, StateMachineTypeName, mappedHoistedLocalSlots, mappedAwaiterSlots);
}
private static EncLocalInfo MapLocalInfo(EncLocalInfo info, SymbolMatcher map)
{
Debug.Assert(!info.IsDefault);
if (info.Type is null)
{
Debug.Assert(info.Signature != null);
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncLocalInfo(info.SlotInfo, typeRef, info.Constraints, info.Signature);
}
private static EncHoistedLocalInfo MapHoistedLocalSlot(EncHoistedLocalInfo info, SymbolMatcher map)
{
if (info.Type is null)
{
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncHoistedLocalInfo(info.SlotInfo, typeRef);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal readonly struct AddedOrChangedMethodInfo
{
public readonly DebugId MethodId;
// locals:
public readonly ImmutableArray<EncLocalInfo> Locals;
// lambdas, closures:
public readonly ImmutableArray<LambdaDebugInfo> LambdaDebugInfo;
public readonly ImmutableArray<ClosureDebugInfo> ClosureDebugInfo;
// state machines:
public readonly string? StateMachineTypeName;
public readonly ImmutableArray<EncHoistedLocalInfo> StateMachineHoistedLocalSlotsOpt;
public readonly ImmutableArray<Cci.ITypeReference?> StateMachineAwaiterSlotsOpt;
public AddedOrChangedMethodInfo(
DebugId methodId,
ImmutableArray<EncLocalInfo> locals,
ImmutableArray<LambdaDebugInfo> lambdaDebugInfo,
ImmutableArray<ClosureDebugInfo> closureDebugInfo,
string? stateMachineTypeName,
ImmutableArray<EncHoistedLocalInfo> stateMachineHoistedLocalSlotsOpt,
ImmutableArray<Cci.ITypeReference?> stateMachineAwaiterSlotsOpt)
{
// An updated method will carry its id over,
// an added method id has generation set to the current generation ordinal.
Debug.Assert(methodId.Generation >= 0);
// each state machine has to have awaiters:
Debug.Assert(stateMachineAwaiterSlotsOpt.IsDefault == (stateMachineTypeName == null));
// a state machine might not have hoisted variables:
Debug.Assert(stateMachineHoistedLocalSlotsOpt.IsDefault || (stateMachineTypeName != null));
MethodId = methodId;
Locals = locals;
LambdaDebugInfo = lambdaDebugInfo;
ClosureDebugInfo = closureDebugInfo;
StateMachineTypeName = stateMachineTypeName;
StateMachineHoistedLocalSlotsOpt = stateMachineHoistedLocalSlotsOpt;
StateMachineAwaiterSlotsOpt = stateMachineAwaiterSlotsOpt;
}
public AddedOrChangedMethodInfo MapTypes(SymbolMatcher map)
{
var mappedLocals = ImmutableArray.CreateRange(Locals, MapLocalInfo, map);
var mappedHoistedLocalSlots = StateMachineHoistedLocalSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineHoistedLocalSlotsOpt, MapHoistedLocalSlot, map);
var mappedAwaiterSlots = StateMachineAwaiterSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineAwaiterSlotsOpt, static (typeRef, map) => (typeRef is null) ? null : map.MapReference(typeRef), map);
return new AddedOrChangedMethodInfo(MethodId, mappedLocals, LambdaDebugInfo, ClosureDebugInfo, StateMachineTypeName, mappedHoistedLocalSlots, mappedAwaiterSlots);
}
private static EncLocalInfo MapLocalInfo(EncLocalInfo info, SymbolMatcher map)
{
Debug.Assert(!info.IsDefault);
if (info.Type is null)
{
Debug.Assert(info.Signature != null);
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncLocalInfo(info.SlotInfo, typeRef, info.Constraints, info.Signature);
}
private static EncHoistedLocalInfo MapHoistedLocalSlot(EncHoistedLocalInfo info, SymbolMatcher map)
{
if (info.Type is null)
{
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncHoistedLocalInfo(info.SlotInfo, typeRef);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundAggregateClause.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundAggregateClause
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return UnderlyingExpression.ExpressionSymbol
End Get
End Property
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return UnderlyingExpression.ResultKind
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 Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundAggregateClause
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return UnderlyingExpression.ExpressionSymbol
End Get
End Property
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
Return UnderlyingExpression.ResultKind
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/VisualBasic/GoToDefinition/VisualBasicGoToDefinitionService.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.GoToDefinition
<ExportLanguageService(GetType(IGoToDefinitionService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicGoToDefinitionService
Inherits AbstractGoToDefinitionService
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(threadingContext As IThreadingContext,
streamingPresenter As IStreamingFindUsagesPresenter)
MyBase.New(threadingContext, streamingPresenter)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.GoToDefinition
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.GoToDefinition
<ExportLanguageService(GetType(IGoToDefinitionService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicGoToDefinitionService
Inherits AbstractGoToDefinitionService
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(threadingContext As IThreadingContext,
streamingPresenter As IStreamingFindUsagesPresenter)
MyBase.New(threadingContext, streamingPresenter)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/VisualStudio/Core/Def/Implementation/Progression/GraphProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.CodeSchema;
using Microsoft.VisualStudio.GraphModel.Schemas;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Progression;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal class AbstractGraphProvider : IGraphProvider
{
private readonly IThreadingContext _threadingContext;
private readonly IGlyphService _glyphService;
private readonly IServiceProvider _serviceProvider;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly Workspace _workspace;
private readonly GraphQueryManager _graphQueryManager;
private bool _initialized = false;
protected AbstractGraphProvider(
IThreadingContext threadingContext,
IGlyphService glyphService,
SVsServiceProvider serviceProvider,
Workspace workspace,
IAsynchronousOperationListenerProvider listenerProvider)
{
_threadingContext = threadingContext;
_glyphService = glyphService;
_serviceProvider = serviceProvider;
_asyncListener = listenerProvider.GetListener(FeatureAttribute.GraphProvider);
_workspace = workspace;
_graphQueryManager = new GraphQueryManager(workspace, _asyncListener);
}
private void EnsureInitialized()
{
if (_initialized)
{
return;
}
var iconService = (IIconService)_serviceProvider.GetService(typeof(IIconService));
IconHelper.Initialize(_glyphService, iconService);
_initialized = true;
}
internal static List<IGraphQuery> GetGraphQueries(
IGraphContext context,
IThreadingContext threadingContext,
IAsynchronousOperationListener asyncListener)
{
var graphQueries = new List<IGraphQuery>();
if (context.Direction == GraphContextDirection.Self && context.RequestedProperties.Contains(DgmlNodeProperties.ContainsChildren))
{
graphQueries.Add(new ContainsChildrenGraphQuery());
}
if (context.Direction == GraphContextDirection.Contains ||
(context.Direction == GraphContextDirection.Target && context.LinkCategories.Contains(CodeLinkCategories.Contains)))
{
graphQueries.Add(new ContainsGraphQuery());
}
if (context.LinkCategories.Contains(CodeLinkCategories.InheritsFrom))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new InheritsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new InheritedByGraphQuery());
}
}
if (context.LinkCategories.Contains(CodeLinkCategories.SourceReferences))
{
graphQueries.Add(new IsUsedByGraphQuery());
}
if (context.LinkCategories.Contains(CodeLinkCategories.Calls))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new CallsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new IsCalledByGraphQuery());
}
}
if (context.LinkCategories.Contains(CodeLinkCategories.Implements))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new ImplementsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new ImplementedByGraphQuery());
}
}
if (context.LinkCategories.Contains(RoslynGraphCategories.Overrides))
{
if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new OverridesGraphQuery());
}
else if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new OverriddenByGraphQuery());
}
}
if (context.Direction == GraphContextDirection.Custom)
{
var searchParameters = context.GetValue<ISolutionSearchParameters>(typeof(ISolutionSearchParameters).GUID.ToString());
if (searchParameters != null)
{
// WARNING: searchParameters.SearchQuery returns an IVsSearchQuery object, which
// is a COM type. Therefore, it's probably best to grab the values we want now
// rather than get surprised by COM marshalling later.
graphQueries.Add(new SearchGraphQuery(
searchParameters.SearchQuery.SearchString, threadingContext, asyncListener));
}
}
return graphQueries;
}
public void BeginGetGraphData(IGraphContext context)
{
EnsureInitialized();
var graphQueries = GetGraphQueries(context, _threadingContext, _asyncListener);
if (graphQueries.Count > 0)
{
_graphQueryManager.AddQueries(context, graphQueries);
}
else
{
// It's an unknown query type, so we're done
context.OnCompleted();
}
}
public IEnumerable<GraphCommand> GetCommands(IEnumerable<GraphNode> nodes)
{
EnsureInitialized();
// Only nodes that explicitly state that they contain children (e.g., source files) and named types should
// be expandable.
if (nodes.Any(n => n.Properties.Any(p => p.Key == DgmlNodeProperties.ContainsChildren)) ||
nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType)))
{
yield return new GraphCommand(
GraphCommandDefinition.Contains,
targetCategories: null,
linkCategories: new[] { GraphCommonSchema.Contains },
trackChanges: true);
}
// All graph commands below this point apply only to Roslyn-owned nodes.
if (!nodes.All(n => IsRoslynNode(n)))
{
yield break;
}
// Only show 'Base Types' and 'Derived Types' on a class or interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Interface, TypeKind.Struct, TypeKind.Enum, TypeKind.Delegate)))
{
yield return new GraphCommand(
GraphCommandDefinition.BaseTypes,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.InheritsFrom },
trackChanges: true);
yield return new GraphCommand(
GraphCommandDefinition.DerivedTypes,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.InheritsFrom },
trackChanges: true);
}
// Only show 'Calls' on an applicable member in a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property, SymbolKind.Field)))
{
yield return new GraphCommand(
GraphCommandDefinition.Calls,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Calls },
trackChanges: true);
}
// Only show 'Is Called By' on an applicable member in a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct)))
{
yield return new GraphCommand(
GraphCommandDefinition.IsCalledBy,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Calls },
trackChanges: true);
}
// Show 'Is Used By'
yield return new GraphCommand(
GraphCommandDefinition.IsUsedBy,
targetCategories: new[] { CodeNodeCategories.SourceLocation },
linkCategories: new[] { CodeLinkCategories.SourceReferences },
trackChanges: true);
// Show 'Implements' on a class or struct, or an applicable member in a class or struct.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct)))
{
yield return new GraphCommand(
s_implementsCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Implements' on public, non-static members of a class or struct. Note: we should
// also show it on explicit interface impls in C#.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
!GetModifiers(n).IsStatic))
{
if (nodes.Any(n => CheckAccessibility(n, Accessibility.Public) ||
HasExplicitInterfaces(n)))
{
yield return new GraphCommand(
s_implementsCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
}
// Show 'Implemented By' on an interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Interface)))
{
yield return new GraphCommand(
s_implementedByCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Implemented By' on any member of an interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Interface)))
{
yield return new GraphCommand(
s_implementedByCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Overrides' on any applicable member of a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
GetModifiers(n).IsOverride))
{
yield return new GraphCommand(
s_overridesCommandDefinition,
targetCategories: null,
linkCategories: new[] { RoslynGraphCategories.Overrides },
trackChanges: true);
}
// Show 'Overridden By' on any applicable member of a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
IsOverridable(n)))
{
yield return new GraphCommand(
s_overriddenByCommandDefinition,
targetCategories: null,
linkCategories: new[] { RoslynGraphCategories.Overrides },
trackChanges: true);
}
}
private bool IsOverridable(GraphNode node)
{
var modifiers = GetModifiers(node);
return (modifiers.IsVirtual || modifiers.IsAbstract || modifiers.IsOverride) &&
!modifiers.IsSealed;
}
private DeclarationModifiers GetModifiers(GraphNode node)
=> (DeclarationModifiers)node[RoslynGraphProperties.SymbolModifiers];
private bool CheckAccessibility(GraphNode node, Accessibility accessibility)
=> node[RoslynGraphProperties.DeclaredAccessibility].Equals(accessibility);
private bool HasExplicitInterfaces(GraphNode node)
=> ((IList<SymbolKey>)node[RoslynGraphProperties.ExplicitInterfaceImplementations]).Count > 0;
private bool IsRoslynNode(GraphNode node)
{
return node[RoslynGraphProperties.SymbolKind] != null
&& node[RoslynGraphProperties.TypeKind] != null;
}
private bool IsAnySymbolKind(GraphNode node, params SymbolKind[] symbolKinds)
=> symbolKinds.Any(k => k.Equals(node[RoslynGraphProperties.SymbolKind]));
private bool IsAnyTypeKind(GraphNode node, params TypeKind[] typeKinds)
=> typeKinds.Any(k => node[RoslynGraphProperties.TypeKind].Equals(k));
private static readonly GraphCommandDefinition s_overridesCommandDefinition =
new("Overrides", ServicesVSResources.Overrides_, GraphContextDirection.Target, 700);
private static readonly GraphCommandDefinition s_overriddenByCommandDefinition =
new("OverriddenBy", ServicesVSResources.Overridden_By, GraphContextDirection.Source, 700);
private static readonly GraphCommandDefinition s_implementsCommandDefinition =
new("Implements", ServicesVSResources.Implements_, GraphContextDirection.Target, 600);
private static readonly GraphCommandDefinition s_implementedByCommandDefinition =
new("ImplementedBy", ServicesVSResources.Implemented_By, GraphContextDirection.Source, 600);
public T GetExtension<T>(GraphObject graphObject, T previous) where T : class
{
if (graphObject is GraphNode graphNode)
{
// If this is not a Roslyn node, bail out.
if (graphNode.GetValue(RoslynGraphProperties.ContextProjectId) == null)
return null;
// Has to have at least a symbolid, or source location to navigate to.
if (graphNode.GetValue<SymbolKey?>(RoslynGraphProperties.SymbolId) == null &&
graphNode.GetValue<SourceLocation>(CodeNodeProperties.SourceLocation).FileName == null)
{
return null;
}
if (typeof(T) == typeof(IGraphNavigateToItem))
return new GraphNavigatorExtension(_threadingContext, _workspace) as T;
if (typeof(T) == typeof(IGraphFormattedLabel))
return new GraphFormattedLabelExtension() as T;
}
return null;
}
public Graph Schema
{
get { 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.CodeSchema;
using Microsoft.VisualStudio.GraphModel.Schemas;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Progression;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal class AbstractGraphProvider : IGraphProvider
{
private readonly IThreadingContext _threadingContext;
private readonly IGlyphService _glyphService;
private readonly IServiceProvider _serviceProvider;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly Workspace _workspace;
private readonly GraphQueryManager _graphQueryManager;
private bool _initialized = false;
protected AbstractGraphProvider(
IThreadingContext threadingContext,
IGlyphService glyphService,
SVsServiceProvider serviceProvider,
Workspace workspace,
IAsynchronousOperationListenerProvider listenerProvider)
{
_threadingContext = threadingContext;
_glyphService = glyphService;
_serviceProvider = serviceProvider;
_asyncListener = listenerProvider.GetListener(FeatureAttribute.GraphProvider);
_workspace = workspace;
_graphQueryManager = new GraphQueryManager(workspace, _asyncListener);
}
private void EnsureInitialized()
{
if (_initialized)
{
return;
}
var iconService = (IIconService)_serviceProvider.GetService(typeof(IIconService));
IconHelper.Initialize(_glyphService, iconService);
_initialized = true;
}
internal static List<IGraphQuery> GetGraphQueries(
IGraphContext context,
IThreadingContext threadingContext,
IAsynchronousOperationListener asyncListener)
{
var graphQueries = new List<IGraphQuery>();
if (context.Direction == GraphContextDirection.Self && context.RequestedProperties.Contains(DgmlNodeProperties.ContainsChildren))
{
graphQueries.Add(new ContainsChildrenGraphQuery());
}
if (context.Direction == GraphContextDirection.Contains ||
(context.Direction == GraphContextDirection.Target && context.LinkCategories.Contains(CodeLinkCategories.Contains)))
{
graphQueries.Add(new ContainsGraphQuery());
}
if (context.LinkCategories.Contains(CodeLinkCategories.InheritsFrom))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new InheritsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new InheritedByGraphQuery());
}
}
if (context.LinkCategories.Contains(CodeLinkCategories.SourceReferences))
{
graphQueries.Add(new IsUsedByGraphQuery());
}
if (context.LinkCategories.Contains(CodeLinkCategories.Calls))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new CallsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new IsCalledByGraphQuery());
}
}
if (context.LinkCategories.Contains(CodeLinkCategories.Implements))
{
if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new ImplementsGraphQuery());
}
else if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new ImplementedByGraphQuery());
}
}
if (context.LinkCategories.Contains(RoslynGraphCategories.Overrides))
{
if (context.Direction == GraphContextDirection.Source)
{
graphQueries.Add(new OverridesGraphQuery());
}
else if (context.Direction == GraphContextDirection.Target)
{
graphQueries.Add(new OverriddenByGraphQuery());
}
}
if (context.Direction == GraphContextDirection.Custom)
{
var searchParameters = context.GetValue<ISolutionSearchParameters>(typeof(ISolutionSearchParameters).GUID.ToString());
if (searchParameters != null)
{
// WARNING: searchParameters.SearchQuery returns an IVsSearchQuery object, which
// is a COM type. Therefore, it's probably best to grab the values we want now
// rather than get surprised by COM marshalling later.
graphQueries.Add(new SearchGraphQuery(
searchParameters.SearchQuery.SearchString, threadingContext, asyncListener));
}
}
return graphQueries;
}
public void BeginGetGraphData(IGraphContext context)
{
EnsureInitialized();
var graphQueries = GetGraphQueries(context, _threadingContext, _asyncListener);
if (graphQueries.Count > 0)
{
_graphQueryManager.AddQueries(context, graphQueries);
}
else
{
// It's an unknown query type, so we're done
context.OnCompleted();
}
}
public IEnumerable<GraphCommand> GetCommands(IEnumerable<GraphNode> nodes)
{
EnsureInitialized();
// Only nodes that explicitly state that they contain children (e.g., source files) and named types should
// be expandable.
if (nodes.Any(n => n.Properties.Any(p => p.Key == DgmlNodeProperties.ContainsChildren)) ||
nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType)))
{
yield return new GraphCommand(
GraphCommandDefinition.Contains,
targetCategories: null,
linkCategories: new[] { GraphCommonSchema.Contains },
trackChanges: true);
}
// All graph commands below this point apply only to Roslyn-owned nodes.
if (!nodes.All(n => IsRoslynNode(n)))
{
yield break;
}
// Only show 'Base Types' and 'Derived Types' on a class or interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Interface, TypeKind.Struct, TypeKind.Enum, TypeKind.Delegate)))
{
yield return new GraphCommand(
GraphCommandDefinition.BaseTypes,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.InheritsFrom },
trackChanges: true);
yield return new GraphCommand(
GraphCommandDefinition.DerivedTypes,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.InheritsFrom },
trackChanges: true);
}
// Only show 'Calls' on an applicable member in a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property, SymbolKind.Field)))
{
yield return new GraphCommand(
GraphCommandDefinition.Calls,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Calls },
trackChanges: true);
}
// Only show 'Is Called By' on an applicable member in a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct)))
{
yield return new GraphCommand(
GraphCommandDefinition.IsCalledBy,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Calls },
trackChanges: true);
}
// Show 'Is Used By'
yield return new GraphCommand(
GraphCommandDefinition.IsUsedBy,
targetCategories: new[] { CodeNodeCategories.SourceLocation },
linkCategories: new[] { CodeLinkCategories.SourceReferences },
trackChanges: true);
// Show 'Implements' on a class or struct, or an applicable member in a class or struct.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct)))
{
yield return new GraphCommand(
s_implementsCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Implements' on public, non-static members of a class or struct. Note: we should
// also show it on explicit interface impls in C#.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
!GetModifiers(n).IsStatic))
{
if (nodes.Any(n => CheckAccessibility(n, Accessibility.Public) ||
HasExplicitInterfaces(n)))
{
yield return new GraphCommand(
s_implementsCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
}
// Show 'Implemented By' on an interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.NamedType) &&
IsAnyTypeKind(n, TypeKind.Interface)))
{
yield return new GraphCommand(
s_implementedByCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Implemented By' on any member of an interface.
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Interface)))
{
yield return new GraphCommand(
s_implementedByCommandDefinition,
targetCategories: null,
linkCategories: new[] { CodeLinkCategories.Implements },
trackChanges: true);
}
// Show 'Overrides' on any applicable member of a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
GetModifiers(n).IsOverride))
{
yield return new GraphCommand(
s_overridesCommandDefinition,
targetCategories: null,
linkCategories: new[] { RoslynGraphCategories.Overrides },
trackChanges: true);
}
// Show 'Overridden By' on any applicable member of a class or struct
if (nodes.Any(n => IsAnySymbolKind(n, SymbolKind.Event, SymbolKind.Method, SymbolKind.Property) &&
IsAnyTypeKind(n, TypeKind.Class, TypeKind.Struct) &&
IsOverridable(n)))
{
yield return new GraphCommand(
s_overriddenByCommandDefinition,
targetCategories: null,
linkCategories: new[] { RoslynGraphCategories.Overrides },
trackChanges: true);
}
}
private bool IsOverridable(GraphNode node)
{
var modifiers = GetModifiers(node);
return (modifiers.IsVirtual || modifiers.IsAbstract || modifiers.IsOverride) &&
!modifiers.IsSealed;
}
private DeclarationModifiers GetModifiers(GraphNode node)
=> (DeclarationModifiers)node[RoslynGraphProperties.SymbolModifiers];
private bool CheckAccessibility(GraphNode node, Accessibility accessibility)
=> node[RoslynGraphProperties.DeclaredAccessibility].Equals(accessibility);
private bool HasExplicitInterfaces(GraphNode node)
=> ((IList<SymbolKey>)node[RoslynGraphProperties.ExplicitInterfaceImplementations]).Count > 0;
private bool IsRoslynNode(GraphNode node)
{
return node[RoslynGraphProperties.SymbolKind] != null
&& node[RoslynGraphProperties.TypeKind] != null;
}
private bool IsAnySymbolKind(GraphNode node, params SymbolKind[] symbolKinds)
=> symbolKinds.Any(k => k.Equals(node[RoslynGraphProperties.SymbolKind]));
private bool IsAnyTypeKind(GraphNode node, params TypeKind[] typeKinds)
=> typeKinds.Any(k => node[RoslynGraphProperties.TypeKind].Equals(k));
private static readonly GraphCommandDefinition s_overridesCommandDefinition =
new("Overrides", ServicesVSResources.Overrides_, GraphContextDirection.Target, 700);
private static readonly GraphCommandDefinition s_overriddenByCommandDefinition =
new("OverriddenBy", ServicesVSResources.Overridden_By, GraphContextDirection.Source, 700);
private static readonly GraphCommandDefinition s_implementsCommandDefinition =
new("Implements", ServicesVSResources.Implements_, GraphContextDirection.Target, 600);
private static readonly GraphCommandDefinition s_implementedByCommandDefinition =
new("ImplementedBy", ServicesVSResources.Implemented_By, GraphContextDirection.Source, 600);
public T GetExtension<T>(GraphObject graphObject, T previous) where T : class
{
if (graphObject is GraphNode graphNode)
{
// If this is not a Roslyn node, bail out.
if (graphNode.GetValue(RoslynGraphProperties.ContextProjectId) == null)
return null;
// Has to have at least a symbolid, or source location to navigate to.
if (graphNode.GetValue<SymbolKey?>(RoslynGraphProperties.SymbolId) == null &&
graphNode.GetValue<SourceLocation>(CodeNodeProperties.SourceLocation).FileName == null)
{
return null;
}
if (typeof(T) == typeof(IGraphNavigateToItem))
return new GraphNavigatorExtension(_threadingContext, _workspace) as T;
if (typeof(T) == typeof(IGraphFormattedLabel))
return new GraphFormattedLabelExtension() as T;
}
return null;
}
public Graph Schema
{
get { return null; }
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Portable/Scanner/CharacterInfo.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 the definition of the Scanner, which produces tokens from text
'-----------------------------------------------------------------------------
Option Strict On
Option Explicit On
Option Infer On
Imports System.Globalization
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Provides members for determining Syntax facts about characters and Unicode conversions.
''' </summary>
Partial Public Class SyntaxFacts
'/*****************************************************************************/
'// MakeFullWidth - Converts a half-width to full-width character
Friend Shared Function MakeFullWidth(c As Char) As Char
Debug.Assert(IsHalfWidth(c))
Return Convert.ToChar(Convert.ToUInt16(c) + s_fullwidth)
End Function
Friend Shared Function IsHalfWidth(c As Char) As Boolean
Return c >= ChrW(&H21S) AndAlso c <= ChrW(&H7ES)
End Function
'// MakeHalfWidth - Converts a full-width character to half-width
Friend Shared Function MakeHalfWidth(c As Char) As Char
Debug.Assert(IsFullWidth(c))
Return Convert.ToChar(Convert.ToUInt16(c) - s_fullwidth)
End Function
'// IsFullWidth - Returns if the character is full width
Friend Shared Function IsFullWidth(c As Char) As Boolean
' Do not use "AndAlso" or it will not inline.
Return c > ChrW(&HFF00US) And c < ChrW(&HFF5FUS)
End Function
''' <summary>
''' Determines if Unicode character represents a whitespace.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character represents whitespace.</returns>
Public Shared Function IsWhitespace(c As Char) As Boolean
Return (SPACE = c) OrElse (CHARACTER_TABULATION = c) OrElse (c > ChrW(128) AndAlso IsWhitespaceNotAscii(c))
End Function
''' <summary>
''' Determines if Unicode character represents a XML whitespace.
''' </summary>
''' <param name="c">The unicode character</param>
''' <returns>A boolean value set to True if character represents XML whitespace.</returns>
Public Shared Function IsXmlWhitespace(c As Char) As Boolean
Return (SPACE = c) OrElse (CHARACTER_TABULATION = c) OrElse (c > ChrW(128) AndAlso XmlCharType.IsWhiteSpace(c))
End Function
Friend Shared Function IsWhitespaceNotAscii(ch As Char) As Boolean
Select Case ch
Case NO_BREAK_SPACE, IDEOGRAPHIC_SPACE, ChrW(&H2000S) To ChrW(&H200BS)
Return True
Case Else
Return CharUnicodeInfo.GetUnicodeCategory(ch) = UnicodeCategory.SpaceSeparator
End Select
End Function
Private Const s_fullwidth = CInt(&HFF00L - &H0020L)
Friend Const CHARACTER_TABULATION As Char = ChrW(&H0009)
Friend Const LINE_FEED As Char = ChrW(&H000A)
Friend Const CARRIAGE_RETURN As Char = ChrW(&H000D)
Friend Const SPACE As Char = ChrW(&H0020)
Friend Const NO_BREAK_SPACE As Char = ChrW(&H00A0)
Friend Const IDEOGRAPHIC_SPACE As Char = ChrW(&H3000)
Friend Const LINE_SEPARATOR As Char = ChrW(&H2028)
Friend Const PARAGRAPH_SEPARATOR As Char = ChrW(&H2029)
Friend Const NEXT_LINE As Char = ChrW(&H0085)
Friend Const LEFT_SINGLE_QUOTATION_MARK As Char = ChrW(&H2018) REM ‘
Friend Const RIGHT_SINGLE_QUOTATION_MARK As Char = ChrW(&H2019) REM ’
Friend Const LEFT_DOUBLE_QUOTATION_MARK As Char = ChrW(&H201C) REM “
Friend Const RIGHT_DOUBLE_QUOTATION_MARK As Char = ChrW(&H201D) REM ”
Friend Const FULLWIDTH_APOSTROPHE As Char = ChrW(s_fullwidth + AscW("'"c)) REM '
Friend Const FULLWIDTH_QUOTATION_MARK As Char = ChrW(s_fullwidth + AscW(""""c)) REM "
Friend Const FULLWIDTH_DIGIT_ZERO As Char = ChrW(s_fullwidth + AscW("0"c)) REM 0
Friend Const FULLWIDTH_DIGIT_ONE As Char = ChrW(s_fullwidth + AscW("1"c)) REM 1
Friend Const FULLWIDTH_DIGIT_SEVEN As Char = ChrW(s_fullwidth + AscW("7"c)) REM 7
Friend Const FULLWIDTH_DIGIT_NINE As Char = ChrW(s_fullwidth + AscW("9"c)) REM 9
Friend Const FULLWIDTH_LOW_LINE As Char = ChrW(s_fullwidth + AscW("_"c)) REM _
Friend Const FULLWIDTH_COLON As Char = ChrW(s_fullwidth + AscW(":"c)) REM :
Friend Const FULLWIDTH_SOLIDUS As Char = ChrW(s_fullwidth + AscW("/"c)) REM /
Friend Const FULLWIDTH_HYPHEN_MINUS As Char = ChrW(s_fullwidth + AscW("-"c)) REM -
Friend Const FULLWIDTH_PLUS_SIGN As Char = ChrW(s_fullwidth + AscW("+"c)) REM +
Friend Const FULLWIDTH_NUMBER_SIGN As Char = ChrW(s_fullwidth + AscW("#"c)) REM #
Friend Const FULLWIDTH_EQUALS_SIGN As Char = ChrW(s_fullwidth + AscW("="c)) REM =
Friend Const FULLWIDTH_LESS_THAN_SIGN As Char = ChrW(s_fullwidth + AscW("<"c)) REM <
Friend Const FULLWIDTH_GREATER_THAN_SIGN As Char = ChrW(s_fullwidth + AscW(">"c)) REM >
Friend Const FULLWIDTH_LEFT_PARENTHESIS As Char = ChrW(s_fullwidth + AscW("("c)) REM (
Friend Const FULLWIDTH_LEFT_SQUARE_BRACKET As Char = ChrW(s_fullwidth + AscW("["c)) REM [
Friend Const FULLWIDTH_RIGHT_SQUARE_BRACKET As Char = ChrW(s_fullwidth + AscW("]"c)) REM ]
Friend Const FULLWIDTH_LEFT_CURLY_BRACKET As Char = ChrW(s_fullwidth + AscW("{"c)) REM {
Friend Const FULLWIDTH_RIGHT_CURLY_BRACKET As Char = ChrW(s_fullwidth + AscW("}"c)) REM }
Friend Const FULLWIDTH_AMPERSAND As Char = ChrW(s_fullwidth + AscW("&"c)) REM &
Friend Const FULLWIDTH_DOLLAR_SIGN As Char = ChrW(s_fullwidth + AscW("$"c)) REM $
Friend Const FULLWIDTH_QUESTION_MARK As Char = ChrW(s_fullwidth + AscW("?"c)) REM ?
Friend Const FULLWIDTH_FULL_STOP As Char = ChrW(s_fullwidth + AscW("."c)) REM .
Friend Const FULLWIDTH_COMMA As Char = ChrW(s_fullwidth + AscW(","c)) REM ,
Friend Const FULLWIDTH_PERCENT_SIGN As Char = ChrW(s_fullwidth + AscW("%"c)) REM %
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_B As Char = ChrW(s_fullwidth + AscW("B"c)) REM B
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_H As Char = ChrW(s_fullwidth + AscW("H"c)) REM H
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_O As Char = ChrW(s_fullwidth + AscW("O"c)) REM O
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_E As Char = ChrW(s_fullwidth + AscW("E"c)) REM E
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_A As Char = ChrW(s_fullwidth + AscW("A"c)) REM A
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_F As Char = ChrW(s_fullwidth + AscW("F"c)) REM F
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_C As Char = ChrW(s_fullwidth + AscW("C"c)) REM C
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_P As Char = ChrW(s_fullwidth + AscW("P"c)) REM P
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_M As Char = ChrW(s_fullwidth + AscW("M"c)) REM M
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_B As Char = ChrW(s_fullwidth + AscW("b"c)) REM b
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_H As Char = ChrW(s_fullwidth + AscW("h"c)) REM h
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_O As Char = ChrW(s_fullwidth + AscW("o"c)) REM o
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_E As Char = ChrW(s_fullwidth + AscW("e"c)) REM e
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_A As Char = ChrW(s_fullwidth + AscW("a"c)) REM a
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_F As Char = ChrW(s_fullwidth + AscW("f"c)) REM f
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_C As Char = ChrW(s_fullwidth + AscW("c"c)) REM c
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_P As Char = ChrW(s_fullwidth + AscW("p"c)) REM p
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_M As Char = ChrW(s_fullwidth + AscW("m"c)) REM m
Friend Const FULLWIDTH_LEFT_PARENTHESIS_STRING As String = FULLWIDTH_LEFT_PARENTHESIS
Friend Const FULLWIDTH_RIGHT_PARENTHESIS_STRING As String = ChrW(s_fullwidth + AscW(")"c))
Friend Const FULLWIDTH_LEFT_CURLY_BRACKET_STRING As String = FULLWIDTH_LEFT_CURLY_BRACKET
Friend Const FULLWIDTH_RIGHT_CURLY_BRACKET_STRING As String = FULLWIDTH_RIGHT_CURLY_BRACKET
Friend Const FULLWIDTH_FULL_STOP_STRING As String = FULLWIDTH_FULL_STOP
Friend Const FULLWIDTH_COMMA_STRING As String = FULLWIDTH_COMMA
Friend Const FULLWIDTH_EQUALS_SIGN_STRING As String = FULLWIDTH_EQUALS_SIGN
Friend Const FULLWIDTH_PLUS_SIGN_STRING As String = FULLWIDTH_PLUS_SIGN
Friend Const FULLWIDTH_HYPHEN_MINUS_STRING As String = FULLWIDTH_HYPHEN_MINUS
Friend Const FULLWIDTH_ASTERISK_STRING As String = ChrW(s_fullwidth + AscW("*"c))
Friend Const FULLWIDTH_SOLIDUS_STRING As String = FULLWIDTH_SOLIDUS
Friend Const FULLWIDTH_REVERSE_SOLIDUS_STRING As String = ChrW(s_fullwidth + AscW("\"c))
Friend Const FULLWIDTH_COLON_STRING As String = FULLWIDTH_COLON
Friend Const FULLWIDTH_CIRCUMFLEX_ACCENT_STRING As String = ChrW(s_fullwidth + AscW("^"c))
Friend Const FULLWIDTH_AMPERSAND_STRING As String = FULLWIDTH_AMPERSAND
Friend Const FULLWIDTH_NUMBER_SIGN_STRING As String = FULLWIDTH_NUMBER_SIGN
Friend Const FULLWIDTH_EXCLAMATION_MARK_STRING As String = ChrW(s_fullwidth + AscW("!"c))
Friend Const FULLWIDTH_QUESTION_MARK_STRING As String = FULLWIDTH_QUESTION_MARK
Friend Const FULLWIDTH_COMMERCIAL_AT_STRING As String = ChrW(s_fullwidth + AscW("@"c))
Friend Const FULLWIDTH_LESS_THAN_SIGN_STRING As String = FULLWIDTH_LESS_THAN_SIGN
Friend Const FULLWIDTH_GREATER_THAN_SIGN_STRING As String = FULLWIDTH_GREATER_THAN_SIGN
''' <summary>
''' Determines if the Unicode character is a newline character.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character is a newline character.</returns>
Public Shared Function IsNewLine(c As Char) As Boolean
Return CARRIAGE_RETURN = c OrElse LINE_FEED = c OrElse (c >= NEXT_LINE AndAlso (NEXT_LINE = c OrElse LINE_SEPARATOR = c OrElse PARAGRAPH_SEPARATOR = c))
End Function
Friend Shared Function IsSingleQuote(c As Char) As Boolean
' // Besides the half width and full width ', we also check for Unicode
' // LEFT SINGLE QUOTATION MARK and RIGHT SINGLE QUOTATION MARK because
' // IME editors paste them in. This isn't really technically correct
' // because we ignore the left-ness or right-ness, but see VS 170991
Return c = "'"c OrElse (c >= LEFT_SINGLE_QUOTATION_MARK AndAlso (c = FULLWIDTH_APOSTROPHE Or c = LEFT_SINGLE_QUOTATION_MARK Or c = RIGHT_SINGLE_QUOTATION_MARK))
End Function
Friend Shared Function IsDoubleQuote(c As Char) As Boolean
' // Besides the half width and full width ", we also check for Unicode
' // LEFT DOUBLE QUOTATION MARK and RIGHT DOUBLE QUOTATION MARK because
' // IME editors paste them in. This isn't really technically correct
' // because we ignore the left-ness or right-ness, but see VS 170991
Return c = """"c OrElse (c >= LEFT_DOUBLE_QUOTATION_MARK AndAlso (c = FULLWIDTH_QUOTATION_MARK Or c = LEFT_DOUBLE_QUOTATION_MARK Or c = RIGHT_DOUBLE_QUOTATION_MARK))
End Function
Friend Shared Function IsLeftCurlyBracket(c As Char) As Boolean
Return c = "{"c OrElse c = FULLWIDTH_LEFT_CURLY_BRACKET
End Function
Friend Shared Function IsRightCurlyBracket(c As Char) As Boolean
Return c = "}"c OrElse c = FULLWIDTH_RIGHT_CURLY_BRACKET
End Function
''' <summary>
''' Determines if the unicode character is a colon character.
''' </summary>
''' <param name="c">The unicode character.</param>
''' <returns>A boolean value set to True if character is a colon character.</returns>
Public Shared Function IsColon(c As Char) As Boolean
Return c = ":"c OrElse c = FULLWIDTH_COLON
End Function
''' <summary>
''' Determines if the unicode character is a underscore character.
''' </summary>
''' <param name="c">The unicode character.</param>
''' <returns>A boolean value set to True if character is an underscore character.</returns>
Public Shared Function IsUnderscore(c As Char) As Boolean
' NOTE: fullwidth _ is not considered any special.
Return c = "_"c
End Function
''' <summary>
''' Determines if the unicode character is a hash character.
''' </summary>
''' <param name="c">The unicode character.</param>
''' <returns>A boolean value set to True if character is a hash character.</returns>
Public Shared Function IsHash(c As Char) As Boolean
Return c = "#"c OrElse c = FULLWIDTH_NUMBER_SIGN
End Function
''' <summary>
''' Determines if the Unicode character can be the starting character of a Visual Basic identifier.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character can be part of a valid start character in an identifier.</returns>
Public Shared Function IsIdentifierStartCharacter(
c As Char
) As Boolean
'TODO: make easy cases fast (or check if they already are)
Dim CharacterProperties As UnicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c)
Return IsPropAlpha(CharacterProperties) OrElse
IsPropLetterDigit(CharacterProperties) OrElse
IsPropConnectorPunctuation(CharacterProperties)
End Function
' TODO: replace CByte with something faster.
Friend Shared Function IntegralLiteralCharacterValue(
Digit As Char
) As Byte
If IsFullWidth(Digit) Then
Digit = MakeHalfWidth(Digit)
End If
Dim u As Integer = AscW(Digit)
If IsDecimalDigit(Digit) Then
Return CByte(u - AscW("0"c))
ElseIf Digit >= "A"c AndAlso Digit <= "F"c Then
Return CByte(u + (10 - AscW("A"c)))
Else
Debug.Assert(Digit >= "a"c AndAlso Digit <= "f"c, "Surprising digit.")
Return CByte(u + (10 - AscW("a"c)))
End If
End Function
Friend Shared Function BeginsBaseLiteral(c As Char) As Boolean
Return (c = "H"c Or c = "O"c Or c = "B"c Or c = "h"c Or c = "o"c Or c = "b"c) OrElse
(IsFullWidth(c) AndAlso (c = FULLWIDTH_LATIN_CAPITAL_LETTER_H Or c = FULLWIDTH_LATIN_SMALL_LETTER_H) Or
(c = FULLWIDTH_LATIN_CAPITAL_LETTER_O Or c = FULLWIDTH_LATIN_SMALL_LETTER_O) Or
(c = FULLWIDTH_LATIN_CAPITAL_LETTER_B Or c = FULLWIDTH_LATIN_SMALL_LETTER_B))
End Function
Private Shared ReadOnly s_isIDChar As Boolean() =
{
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, True, True,
True, True, True, True, True, True, True, True, False, False,
False, False, False, False, False, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, False, False, False, False, True, False, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, True, True, False, False, False, False, False
}
Friend Shared Function IsNarrowIdentifierCharacter(c As UInt16) As Boolean
Return s_isIDChar(c)
'Select Case c
' Case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
' 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
' 41, 42, 43, 44, 45, 46, 47
' Return False
' Case 48, 49, 50, 51, 52, 53, 54, 55, 56, 57
' Return True
' Case 58, 59, 60, 61, 62, 63, 64
' Return False
' Case 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
' 81, 82, 83, 84, 85, 86, 87, 88, 89, 90
' Return True
' Case 91, 92, 93, 94
' Return False
' Case 95
' Return True
' Case 96
' Return False
' Case 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
' 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122
' Return True
'End Select
Return False
End Function
''' <summary>
''' Determines if the Unicode character can be a part of a Visual Basic identifier.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character can be part of a valid identifier.</returns>
Public Shared Function IsIdentifierPartCharacter(c As Char) As Boolean
If c < ChrW(128) Then
Return IsNarrowIdentifierCharacter(Convert.ToUInt16(c))
End If
Return IsWideIdentifierCharacter(c)
End Function
''' <summary>
''' Determines if the name is a valid identifier.
''' </summary>
''' <param name="name">The identifier name.</param>
''' <returns>A boolean value set to True if name is valid identifier.</returns>
Public Shared Function IsValidIdentifier(name As String) As Boolean
If String.IsNullOrEmpty(name) Then
Return False
End If
If Not IsIdentifierStartCharacter(name(0)) Then
Return False
End If
Dim nameLength As Integer = name.Length
For i As Integer = 1 To nameLength - 1 ' NB: start at 1
If Not IsIdentifierPartCharacter(name(i)) Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Creates a half width form Unicode character string.
''' </summary>
''' <param name="text">The text representing the original identifier. This can be in full width or half width Unicode form. </param>
''' <returns>A string representing the text in a half width Unicode form.</returns>
Public Shared Function MakeHalfWidthIdentifier(text As String) As String
If text Is Nothing Then
Return text
End If
Dim characters As Char() = Nothing
For i = 0 To text.Length - 1
Dim c = text(i)
If IsFullWidth(c) Then
If characters Is Nothing Then
characters = New Char(text.Length - 1) {}
text.CopyTo(0, characters, 0, i)
End If
characters(i) = MakeHalfWidth(c)
ElseIf characters IsNot Nothing Then
characters(i) = c
End If
Next
Return If(characters Is Nothing, text, New String(characters))
End Function
Friend Shared Function IsWideIdentifierCharacter(c As Char) As Boolean
Dim CharacterProperties As UnicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c)
Return IsPropAlphaNumeric(CharacterProperties) OrElse
IsPropLetterDigit(CharacterProperties) OrElse
IsPropConnectorPunctuation(CharacterProperties) OrElse
IsPropCombining(CharacterProperties) OrElse
IsPropOtherFormat(CharacterProperties)
End Function
Friend Shared Function BeginsExponent(c As Char) As Boolean
Return c = "E"c Or c = "e"c Or c = FULLWIDTH_LATIN_CAPITAL_LETTER_E Or c = FULLWIDTH_LATIN_SMALL_LETTER_E
End Function
Friend Shared Function IsBinaryDigit(c As Char) As Boolean
Return (c >= "0"c And c <= "1"c) Or
(c >= FULLWIDTH_DIGIT_ZERO And c <= FULLWIDTH_DIGIT_ONE)
End Function
Friend Shared Function IsOctalDigit(c As Char) As Boolean
Return (c >= "0"c And c <= "7"c) Or
(c >= FULLWIDTH_DIGIT_ZERO And c <= FULLWIDTH_DIGIT_SEVEN)
End Function
Friend Shared Function IsDecimalDigit(c As Char) As Boolean
Return (c >= "0"c And c <= "9"c) Or
(c >= FULLWIDTH_DIGIT_ZERO And c <= FULLWIDTH_DIGIT_NINE)
End Function
Friend Shared Function IsHexDigit(c As Char) As Boolean
Return IsDecimalDigit(c) OrElse
(c >= "a"c And c <= "f"c) OrElse
(c >= "A"c And c <= "F"c) OrElse
(c >= FULLWIDTH_LATIN_SMALL_LETTER_A And c <= FULLWIDTH_LATIN_SMALL_LETTER_F) OrElse
(c >= FULLWIDTH_LATIN_CAPITAL_LETTER_A And c <= FULLWIDTH_LATIN_CAPITAL_LETTER_F)
End Function
Friend Shared Function IsDateSeparatorCharacter(c As Char) As Boolean
Return c = "/"c Or c = "-"c Or c = FULLWIDTH_SOLIDUS Or c = FULLWIDTH_HYPHEN_MINUS
End Function
Friend Shared ReadOnly DaysToMonth365() As Integer = New Integer(13 - 1) {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
Friend Shared ReadOnly DaysToMonth366() As Integer = New Integer(13 - 1) {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}
Friend Shared Function IsLetterC(ch As Char) As Boolean
Return _
ch = "c"c Or ch = "C"c Or ch = FULLWIDTH_LATIN_CAPITAL_LETTER_C Or ch = FULLWIDTH_LATIN_SMALL_LETTER_C
End Function
''' <summary>
''' matches one char or another.
''' Typical usage is for matching lowercase and uppercase.
''' </summary>
Friend Shared Function MatchOneOrAnother(ch As Char, one As Char, another As Char) As Boolean
Return ch = one Or ch = another
End Function
''' <summary>
''' matches one char or another.
''' it will try normal width and then fullwidth variations.
''' Typical usage is for matching lowercase and uppercase.
''' </summary>
Friend Shared Function MatchOneOrAnotherOrFullwidth(ch As Char, one As Char, another As Char) As Boolean
Debug.Assert(IsHalfWidth(one))
Debug.Assert(IsHalfWidth(another))
If IsFullWidth(ch) Then
ch = MakeHalfWidth(ch)
End If
Return ch = one Or ch = another
End Function
Friend Shared Function IsPropAlpha(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties <= UnicodeCategory.OtherLetter
End Function
Friend Shared Function IsPropAlphaNumeric(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties <= UnicodeCategory.DecimalDigitNumber
End Function
Friend Shared Function IsPropLetterDigit(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties = UnicodeCategory.LetterNumber
End Function
Friend Shared Function IsPropConnectorPunctuation(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties = UnicodeCategory.ConnectorPunctuation
End Function
Friend Shared Function IsPropCombining(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties >= UnicodeCategory.NonSpacingMark AndAlso
CharacterProperties <= UnicodeCategory.EnclosingMark
End Function
Friend Shared Function IsConnectorPunctuation(c As Char) As Boolean
Return CharUnicodeInfo.GetUnicodeCategory(c) = UnicodeCategory.ConnectorPunctuation
End Function
Friend Shared Function IsSpaceSeparator(c As Char) As Boolean
Return CharUnicodeInfo.GetUnicodeCategory(c) = UnicodeCategory.SpaceSeparator
End Function
Friend Shared Function IsPropOtherFormat(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties = UnicodeCategory.Format
End Function
Friend Shared Function IsSurrogate(c As Char) As Boolean
Return Char.IsSurrogate(c)
End Function
Friend Shared Function IsHighSurrogate(c As Char) As Boolean
Return Char.IsHighSurrogate(c)
End Function
Friend Shared Function IsLowSurrogate(c As Char) As Boolean
Return Char.IsLowSurrogate(c)
End Function
Friend Shared Function ReturnFullWidthOrSelf(c As Char) As Char
If IsHalfWidth(c) Then
Return MakeFullWidth(c)
End If
Return c
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.
'-----------------------------------------------------------------------------
' Contains the definition of the Scanner, which produces tokens from text
'-----------------------------------------------------------------------------
Option Strict On
Option Explicit On
Option Infer On
Imports System.Globalization
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Provides members for determining Syntax facts about characters and Unicode conversions.
''' </summary>
Partial Public Class SyntaxFacts
'/*****************************************************************************/
'// MakeFullWidth - Converts a half-width to full-width character
Friend Shared Function MakeFullWidth(c As Char) As Char
Debug.Assert(IsHalfWidth(c))
Return Convert.ToChar(Convert.ToUInt16(c) + s_fullwidth)
End Function
Friend Shared Function IsHalfWidth(c As Char) As Boolean
Return c >= ChrW(&H21S) AndAlso c <= ChrW(&H7ES)
End Function
'// MakeHalfWidth - Converts a full-width character to half-width
Friend Shared Function MakeHalfWidth(c As Char) As Char
Debug.Assert(IsFullWidth(c))
Return Convert.ToChar(Convert.ToUInt16(c) - s_fullwidth)
End Function
'// IsFullWidth - Returns if the character is full width
Friend Shared Function IsFullWidth(c As Char) As Boolean
' Do not use "AndAlso" or it will not inline.
Return c > ChrW(&HFF00US) And c < ChrW(&HFF5FUS)
End Function
''' <summary>
''' Determines if Unicode character represents a whitespace.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character represents whitespace.</returns>
Public Shared Function IsWhitespace(c As Char) As Boolean
Return (SPACE = c) OrElse (CHARACTER_TABULATION = c) OrElse (c > ChrW(128) AndAlso IsWhitespaceNotAscii(c))
End Function
''' <summary>
''' Determines if Unicode character represents a XML whitespace.
''' </summary>
''' <param name="c">The unicode character</param>
''' <returns>A boolean value set to True if character represents XML whitespace.</returns>
Public Shared Function IsXmlWhitespace(c As Char) As Boolean
Return (SPACE = c) OrElse (CHARACTER_TABULATION = c) OrElse (c > ChrW(128) AndAlso XmlCharType.IsWhiteSpace(c))
End Function
Friend Shared Function IsWhitespaceNotAscii(ch As Char) As Boolean
Select Case ch
Case NO_BREAK_SPACE, IDEOGRAPHIC_SPACE, ChrW(&H2000S) To ChrW(&H200BS)
Return True
Case Else
Return CharUnicodeInfo.GetUnicodeCategory(ch) = UnicodeCategory.SpaceSeparator
End Select
End Function
Private Const s_fullwidth = CInt(&HFF00L - &H0020L)
Friend Const CHARACTER_TABULATION As Char = ChrW(&H0009)
Friend Const LINE_FEED As Char = ChrW(&H000A)
Friend Const CARRIAGE_RETURN As Char = ChrW(&H000D)
Friend Const SPACE As Char = ChrW(&H0020)
Friend Const NO_BREAK_SPACE As Char = ChrW(&H00A0)
Friend Const IDEOGRAPHIC_SPACE As Char = ChrW(&H3000)
Friend Const LINE_SEPARATOR As Char = ChrW(&H2028)
Friend Const PARAGRAPH_SEPARATOR As Char = ChrW(&H2029)
Friend Const NEXT_LINE As Char = ChrW(&H0085)
Friend Const LEFT_SINGLE_QUOTATION_MARK As Char = ChrW(&H2018) REM ‘
Friend Const RIGHT_SINGLE_QUOTATION_MARK As Char = ChrW(&H2019) REM ’
Friend Const LEFT_DOUBLE_QUOTATION_MARK As Char = ChrW(&H201C) REM “
Friend Const RIGHT_DOUBLE_QUOTATION_MARK As Char = ChrW(&H201D) REM ”
Friend Const FULLWIDTH_APOSTROPHE As Char = ChrW(s_fullwidth + AscW("'"c)) REM '
Friend Const FULLWIDTH_QUOTATION_MARK As Char = ChrW(s_fullwidth + AscW(""""c)) REM "
Friend Const FULLWIDTH_DIGIT_ZERO As Char = ChrW(s_fullwidth + AscW("0"c)) REM 0
Friend Const FULLWIDTH_DIGIT_ONE As Char = ChrW(s_fullwidth + AscW("1"c)) REM 1
Friend Const FULLWIDTH_DIGIT_SEVEN As Char = ChrW(s_fullwidth + AscW("7"c)) REM 7
Friend Const FULLWIDTH_DIGIT_NINE As Char = ChrW(s_fullwidth + AscW("9"c)) REM 9
Friend Const FULLWIDTH_LOW_LINE As Char = ChrW(s_fullwidth + AscW("_"c)) REM _
Friend Const FULLWIDTH_COLON As Char = ChrW(s_fullwidth + AscW(":"c)) REM :
Friend Const FULLWIDTH_SOLIDUS As Char = ChrW(s_fullwidth + AscW("/"c)) REM /
Friend Const FULLWIDTH_HYPHEN_MINUS As Char = ChrW(s_fullwidth + AscW("-"c)) REM -
Friend Const FULLWIDTH_PLUS_SIGN As Char = ChrW(s_fullwidth + AscW("+"c)) REM +
Friend Const FULLWIDTH_NUMBER_SIGN As Char = ChrW(s_fullwidth + AscW("#"c)) REM #
Friend Const FULLWIDTH_EQUALS_SIGN As Char = ChrW(s_fullwidth + AscW("="c)) REM =
Friend Const FULLWIDTH_LESS_THAN_SIGN As Char = ChrW(s_fullwidth + AscW("<"c)) REM <
Friend Const FULLWIDTH_GREATER_THAN_SIGN As Char = ChrW(s_fullwidth + AscW(">"c)) REM >
Friend Const FULLWIDTH_LEFT_PARENTHESIS As Char = ChrW(s_fullwidth + AscW("("c)) REM (
Friend Const FULLWIDTH_LEFT_SQUARE_BRACKET As Char = ChrW(s_fullwidth + AscW("["c)) REM [
Friend Const FULLWIDTH_RIGHT_SQUARE_BRACKET As Char = ChrW(s_fullwidth + AscW("]"c)) REM ]
Friend Const FULLWIDTH_LEFT_CURLY_BRACKET As Char = ChrW(s_fullwidth + AscW("{"c)) REM {
Friend Const FULLWIDTH_RIGHT_CURLY_BRACKET As Char = ChrW(s_fullwidth + AscW("}"c)) REM }
Friend Const FULLWIDTH_AMPERSAND As Char = ChrW(s_fullwidth + AscW("&"c)) REM &
Friend Const FULLWIDTH_DOLLAR_SIGN As Char = ChrW(s_fullwidth + AscW("$"c)) REM $
Friend Const FULLWIDTH_QUESTION_MARK As Char = ChrW(s_fullwidth + AscW("?"c)) REM ?
Friend Const FULLWIDTH_FULL_STOP As Char = ChrW(s_fullwidth + AscW("."c)) REM .
Friend Const FULLWIDTH_COMMA As Char = ChrW(s_fullwidth + AscW(","c)) REM ,
Friend Const FULLWIDTH_PERCENT_SIGN As Char = ChrW(s_fullwidth + AscW("%"c)) REM %
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_B As Char = ChrW(s_fullwidth + AscW("B"c)) REM B
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_H As Char = ChrW(s_fullwidth + AscW("H"c)) REM H
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_O As Char = ChrW(s_fullwidth + AscW("O"c)) REM O
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_E As Char = ChrW(s_fullwidth + AscW("E"c)) REM E
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_A As Char = ChrW(s_fullwidth + AscW("A"c)) REM A
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_F As Char = ChrW(s_fullwidth + AscW("F"c)) REM F
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_C As Char = ChrW(s_fullwidth + AscW("C"c)) REM C
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_P As Char = ChrW(s_fullwidth + AscW("P"c)) REM P
Friend Const FULLWIDTH_LATIN_CAPITAL_LETTER_M As Char = ChrW(s_fullwidth + AscW("M"c)) REM M
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_B As Char = ChrW(s_fullwidth + AscW("b"c)) REM b
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_H As Char = ChrW(s_fullwidth + AscW("h"c)) REM h
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_O As Char = ChrW(s_fullwidth + AscW("o"c)) REM o
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_E As Char = ChrW(s_fullwidth + AscW("e"c)) REM e
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_A As Char = ChrW(s_fullwidth + AscW("a"c)) REM a
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_F As Char = ChrW(s_fullwidth + AscW("f"c)) REM f
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_C As Char = ChrW(s_fullwidth + AscW("c"c)) REM c
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_P As Char = ChrW(s_fullwidth + AscW("p"c)) REM p
Friend Const FULLWIDTH_LATIN_SMALL_LETTER_M As Char = ChrW(s_fullwidth + AscW("m"c)) REM m
Friend Const FULLWIDTH_LEFT_PARENTHESIS_STRING As String = FULLWIDTH_LEFT_PARENTHESIS
Friend Const FULLWIDTH_RIGHT_PARENTHESIS_STRING As String = ChrW(s_fullwidth + AscW(")"c))
Friend Const FULLWIDTH_LEFT_CURLY_BRACKET_STRING As String = FULLWIDTH_LEFT_CURLY_BRACKET
Friend Const FULLWIDTH_RIGHT_CURLY_BRACKET_STRING As String = FULLWIDTH_RIGHT_CURLY_BRACKET
Friend Const FULLWIDTH_FULL_STOP_STRING As String = FULLWIDTH_FULL_STOP
Friend Const FULLWIDTH_COMMA_STRING As String = FULLWIDTH_COMMA
Friend Const FULLWIDTH_EQUALS_SIGN_STRING As String = FULLWIDTH_EQUALS_SIGN
Friend Const FULLWIDTH_PLUS_SIGN_STRING As String = FULLWIDTH_PLUS_SIGN
Friend Const FULLWIDTH_HYPHEN_MINUS_STRING As String = FULLWIDTH_HYPHEN_MINUS
Friend Const FULLWIDTH_ASTERISK_STRING As String = ChrW(s_fullwidth + AscW("*"c))
Friend Const FULLWIDTH_SOLIDUS_STRING As String = FULLWIDTH_SOLIDUS
Friend Const FULLWIDTH_REVERSE_SOLIDUS_STRING As String = ChrW(s_fullwidth + AscW("\"c))
Friend Const FULLWIDTH_COLON_STRING As String = FULLWIDTH_COLON
Friend Const FULLWIDTH_CIRCUMFLEX_ACCENT_STRING As String = ChrW(s_fullwidth + AscW("^"c))
Friend Const FULLWIDTH_AMPERSAND_STRING As String = FULLWIDTH_AMPERSAND
Friend Const FULLWIDTH_NUMBER_SIGN_STRING As String = FULLWIDTH_NUMBER_SIGN
Friend Const FULLWIDTH_EXCLAMATION_MARK_STRING As String = ChrW(s_fullwidth + AscW("!"c))
Friend Const FULLWIDTH_QUESTION_MARK_STRING As String = FULLWIDTH_QUESTION_MARK
Friend Const FULLWIDTH_COMMERCIAL_AT_STRING As String = ChrW(s_fullwidth + AscW("@"c))
Friend Const FULLWIDTH_LESS_THAN_SIGN_STRING As String = FULLWIDTH_LESS_THAN_SIGN
Friend Const FULLWIDTH_GREATER_THAN_SIGN_STRING As String = FULLWIDTH_GREATER_THAN_SIGN
''' <summary>
''' Determines if the Unicode character is a newline character.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character is a newline character.</returns>
Public Shared Function IsNewLine(c As Char) As Boolean
Return CARRIAGE_RETURN = c OrElse LINE_FEED = c OrElse (c >= NEXT_LINE AndAlso (NEXT_LINE = c OrElse LINE_SEPARATOR = c OrElse PARAGRAPH_SEPARATOR = c))
End Function
Friend Shared Function IsSingleQuote(c As Char) As Boolean
' // Besides the half width and full width ', we also check for Unicode
' // LEFT SINGLE QUOTATION MARK and RIGHT SINGLE QUOTATION MARK because
' // IME editors paste them in. This isn't really technically correct
' // because we ignore the left-ness or right-ness, but see VS 170991
Return c = "'"c OrElse (c >= LEFT_SINGLE_QUOTATION_MARK AndAlso (c = FULLWIDTH_APOSTROPHE Or c = LEFT_SINGLE_QUOTATION_MARK Or c = RIGHT_SINGLE_QUOTATION_MARK))
End Function
Friend Shared Function IsDoubleQuote(c As Char) As Boolean
' // Besides the half width and full width ", we also check for Unicode
' // LEFT DOUBLE QUOTATION MARK and RIGHT DOUBLE QUOTATION MARK because
' // IME editors paste them in. This isn't really technically correct
' // because we ignore the left-ness or right-ness, but see VS 170991
Return c = """"c OrElse (c >= LEFT_DOUBLE_QUOTATION_MARK AndAlso (c = FULLWIDTH_QUOTATION_MARK Or c = LEFT_DOUBLE_QUOTATION_MARK Or c = RIGHT_DOUBLE_QUOTATION_MARK))
End Function
Friend Shared Function IsLeftCurlyBracket(c As Char) As Boolean
Return c = "{"c OrElse c = FULLWIDTH_LEFT_CURLY_BRACKET
End Function
Friend Shared Function IsRightCurlyBracket(c As Char) As Boolean
Return c = "}"c OrElse c = FULLWIDTH_RIGHT_CURLY_BRACKET
End Function
''' <summary>
''' Determines if the unicode character is a colon character.
''' </summary>
''' <param name="c">The unicode character.</param>
''' <returns>A boolean value set to True if character is a colon character.</returns>
Public Shared Function IsColon(c As Char) As Boolean
Return c = ":"c OrElse c = FULLWIDTH_COLON
End Function
''' <summary>
''' Determines if the unicode character is a underscore character.
''' </summary>
''' <param name="c">The unicode character.</param>
''' <returns>A boolean value set to True if character is an underscore character.</returns>
Public Shared Function IsUnderscore(c As Char) As Boolean
' NOTE: fullwidth _ is not considered any special.
Return c = "_"c
End Function
''' <summary>
''' Determines if the unicode character is a hash character.
''' </summary>
''' <param name="c">The unicode character.</param>
''' <returns>A boolean value set to True if character is a hash character.</returns>
Public Shared Function IsHash(c As Char) As Boolean
Return c = "#"c OrElse c = FULLWIDTH_NUMBER_SIGN
End Function
''' <summary>
''' Determines if the Unicode character can be the starting character of a Visual Basic identifier.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character can be part of a valid start character in an identifier.</returns>
Public Shared Function IsIdentifierStartCharacter(
c As Char
) As Boolean
'TODO: make easy cases fast (or check if they already are)
Dim CharacterProperties As UnicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c)
Return IsPropAlpha(CharacterProperties) OrElse
IsPropLetterDigit(CharacterProperties) OrElse
IsPropConnectorPunctuation(CharacterProperties)
End Function
' TODO: replace CByte with something faster.
Friend Shared Function IntegralLiteralCharacterValue(
Digit As Char
) As Byte
If IsFullWidth(Digit) Then
Digit = MakeHalfWidth(Digit)
End If
Dim u As Integer = AscW(Digit)
If IsDecimalDigit(Digit) Then
Return CByte(u - AscW("0"c))
ElseIf Digit >= "A"c AndAlso Digit <= "F"c Then
Return CByte(u + (10 - AscW("A"c)))
Else
Debug.Assert(Digit >= "a"c AndAlso Digit <= "f"c, "Surprising digit.")
Return CByte(u + (10 - AscW("a"c)))
End If
End Function
Friend Shared Function BeginsBaseLiteral(c As Char) As Boolean
Return (c = "H"c Or c = "O"c Or c = "B"c Or c = "h"c Or c = "o"c Or c = "b"c) OrElse
(IsFullWidth(c) AndAlso (c = FULLWIDTH_LATIN_CAPITAL_LETTER_H Or c = FULLWIDTH_LATIN_SMALL_LETTER_H) Or
(c = FULLWIDTH_LATIN_CAPITAL_LETTER_O Or c = FULLWIDTH_LATIN_SMALL_LETTER_O) Or
(c = FULLWIDTH_LATIN_CAPITAL_LETTER_B Or c = FULLWIDTH_LATIN_SMALL_LETTER_B))
End Function
Private Shared ReadOnly s_isIDChar As Boolean() =
{
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, True, True,
True, True, True, True, True, True, True, True, False, False,
False, False, False, False, False, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, False, False, False, False, True, False, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True, True,
True, True, True, False, False, False, False, False
}
Friend Shared Function IsNarrowIdentifierCharacter(c As UInt16) As Boolean
Return s_isIDChar(c)
'Select Case c
' Case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
' 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
' 41, 42, 43, 44, 45, 46, 47
' Return False
' Case 48, 49, 50, 51, 52, 53, 54, 55, 56, 57
' Return True
' Case 58, 59, 60, 61, 62, 63, 64
' Return False
' Case 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
' 81, 82, 83, 84, 85, 86, 87, 88, 89, 90
' Return True
' Case 91, 92, 93, 94
' Return False
' Case 95
' Return True
' Case 96
' Return False
' Case 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
' 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122
' Return True
'End Select
Return False
End Function
''' <summary>
''' Determines if the Unicode character can be a part of a Visual Basic identifier.
''' </summary>
''' <param name="c">The Unicode character.</param>
''' <returns>A boolean value set to True if character can be part of a valid identifier.</returns>
Public Shared Function IsIdentifierPartCharacter(c As Char) As Boolean
If c < ChrW(128) Then
Return IsNarrowIdentifierCharacter(Convert.ToUInt16(c))
End If
Return IsWideIdentifierCharacter(c)
End Function
''' <summary>
''' Determines if the name is a valid identifier.
''' </summary>
''' <param name="name">The identifier name.</param>
''' <returns>A boolean value set to True if name is valid identifier.</returns>
Public Shared Function IsValidIdentifier(name As String) As Boolean
If String.IsNullOrEmpty(name) Then
Return False
End If
If Not IsIdentifierStartCharacter(name(0)) Then
Return False
End If
Dim nameLength As Integer = name.Length
For i As Integer = 1 To nameLength - 1 ' NB: start at 1
If Not IsIdentifierPartCharacter(name(i)) Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Creates a half width form Unicode character string.
''' </summary>
''' <param name="text">The text representing the original identifier. This can be in full width or half width Unicode form. </param>
''' <returns>A string representing the text in a half width Unicode form.</returns>
Public Shared Function MakeHalfWidthIdentifier(text As String) As String
If text Is Nothing Then
Return text
End If
Dim characters As Char() = Nothing
For i = 0 To text.Length - 1
Dim c = text(i)
If IsFullWidth(c) Then
If characters Is Nothing Then
characters = New Char(text.Length - 1) {}
text.CopyTo(0, characters, 0, i)
End If
characters(i) = MakeHalfWidth(c)
ElseIf characters IsNot Nothing Then
characters(i) = c
End If
Next
Return If(characters Is Nothing, text, New String(characters))
End Function
Friend Shared Function IsWideIdentifierCharacter(c As Char) As Boolean
Dim CharacterProperties As UnicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c)
Return IsPropAlphaNumeric(CharacterProperties) OrElse
IsPropLetterDigit(CharacterProperties) OrElse
IsPropConnectorPunctuation(CharacterProperties) OrElse
IsPropCombining(CharacterProperties) OrElse
IsPropOtherFormat(CharacterProperties)
End Function
Friend Shared Function BeginsExponent(c As Char) As Boolean
Return c = "E"c Or c = "e"c Or c = FULLWIDTH_LATIN_CAPITAL_LETTER_E Or c = FULLWIDTH_LATIN_SMALL_LETTER_E
End Function
Friend Shared Function IsBinaryDigit(c As Char) As Boolean
Return (c >= "0"c And c <= "1"c) Or
(c >= FULLWIDTH_DIGIT_ZERO And c <= FULLWIDTH_DIGIT_ONE)
End Function
Friend Shared Function IsOctalDigit(c As Char) As Boolean
Return (c >= "0"c And c <= "7"c) Or
(c >= FULLWIDTH_DIGIT_ZERO And c <= FULLWIDTH_DIGIT_SEVEN)
End Function
Friend Shared Function IsDecimalDigit(c As Char) As Boolean
Return (c >= "0"c And c <= "9"c) Or
(c >= FULLWIDTH_DIGIT_ZERO And c <= FULLWIDTH_DIGIT_NINE)
End Function
Friend Shared Function IsHexDigit(c As Char) As Boolean
Return IsDecimalDigit(c) OrElse
(c >= "a"c And c <= "f"c) OrElse
(c >= "A"c And c <= "F"c) OrElse
(c >= FULLWIDTH_LATIN_SMALL_LETTER_A And c <= FULLWIDTH_LATIN_SMALL_LETTER_F) OrElse
(c >= FULLWIDTH_LATIN_CAPITAL_LETTER_A And c <= FULLWIDTH_LATIN_CAPITAL_LETTER_F)
End Function
Friend Shared Function IsDateSeparatorCharacter(c As Char) As Boolean
Return c = "/"c Or c = "-"c Or c = FULLWIDTH_SOLIDUS Or c = FULLWIDTH_HYPHEN_MINUS
End Function
Friend Shared ReadOnly DaysToMonth365() As Integer = New Integer(13 - 1) {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
Friend Shared ReadOnly DaysToMonth366() As Integer = New Integer(13 - 1) {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}
Friend Shared Function IsLetterC(ch As Char) As Boolean
Return _
ch = "c"c Or ch = "C"c Or ch = FULLWIDTH_LATIN_CAPITAL_LETTER_C Or ch = FULLWIDTH_LATIN_SMALL_LETTER_C
End Function
''' <summary>
''' matches one char or another.
''' Typical usage is for matching lowercase and uppercase.
''' </summary>
Friend Shared Function MatchOneOrAnother(ch As Char, one As Char, another As Char) As Boolean
Return ch = one Or ch = another
End Function
''' <summary>
''' matches one char or another.
''' it will try normal width and then fullwidth variations.
''' Typical usage is for matching lowercase and uppercase.
''' </summary>
Friend Shared Function MatchOneOrAnotherOrFullwidth(ch As Char, one As Char, another As Char) As Boolean
Debug.Assert(IsHalfWidth(one))
Debug.Assert(IsHalfWidth(another))
If IsFullWidth(ch) Then
ch = MakeHalfWidth(ch)
End If
Return ch = one Or ch = another
End Function
Friend Shared Function IsPropAlpha(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties <= UnicodeCategory.OtherLetter
End Function
Friend Shared Function IsPropAlphaNumeric(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties <= UnicodeCategory.DecimalDigitNumber
End Function
Friend Shared Function IsPropLetterDigit(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties = UnicodeCategory.LetterNumber
End Function
Friend Shared Function IsPropConnectorPunctuation(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties = UnicodeCategory.ConnectorPunctuation
End Function
Friend Shared Function IsPropCombining(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties >= UnicodeCategory.NonSpacingMark AndAlso
CharacterProperties <= UnicodeCategory.EnclosingMark
End Function
Friend Shared Function IsConnectorPunctuation(c As Char) As Boolean
Return CharUnicodeInfo.GetUnicodeCategory(c) = UnicodeCategory.ConnectorPunctuation
End Function
Friend Shared Function IsSpaceSeparator(c As Char) As Boolean
Return CharUnicodeInfo.GetUnicodeCategory(c) = UnicodeCategory.SpaceSeparator
End Function
Friend Shared Function IsPropOtherFormat(CharacterProperties As UnicodeCategory) As Boolean
Return CharacterProperties = UnicodeCategory.Format
End Function
Friend Shared Function IsSurrogate(c As Char) As Boolean
Return Char.IsSurrogate(c)
End Function
Friend Shared Function IsHighSurrogate(c As Char) As Boolean
Return Char.IsHighSurrogate(c)
End Function
Friend Shared Function IsLowSurrogate(c As Char) As Boolean
Return Char.IsLowSurrogate(c)
End Function
Friend Shared Function ReturnFullWidthOrSelf(c As Char) As Char
If IsHalfWidth(c) Then
Return MakeFullWidth(c)
End If
Return c
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/XmlEmbeddedExpressionHighlighter.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class XmlEmbeddedExpressionHighlighter
Inherits AbstractKeywordHighlighter(Of XmlEmbeddedExpressionSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub addHighlights(xmlEmbeddExpression As XmlEmbeddedExpressionSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
With xmlEmbeddExpression
If Not .ContainsDiagnostics AndAlso
Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then
highlights.Add(.LessThanPercentEqualsToken.Span)
highlights.Add(.PercentGreaterThanToken.Span)
End If
End With
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class XmlEmbeddedExpressionHighlighter
Inherits AbstractKeywordHighlighter(Of XmlEmbeddedExpressionSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub addHighlights(xmlEmbeddExpression As XmlEmbeddedExpressionSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
With xmlEmbeddExpression
If Not .ContainsDiagnostics AndAlso
Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then
highlights.Add(.LessThanPercentEqualsToken.Span)
highlights.Add(.PercentGreaterThanToken.Span)
End If
End With
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/SymbolErrorTests.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.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' this place is dedicated to various parser and/or symbol errors
Public Class SymbolErrorTests
Inherits BasicTestBase
#Region "Targeted Error Tests"
<Fact>
Public Sub BC30002ERR_UndefinedType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedType1">
<file name="a.vb"><![CDATA[
Structure myStruct
Sub Scen1(FixedRankArray_7(,) As unknowntype)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'unknowntype' is not defined.
Sub Scen1(FixedRankArray_7(,) As unknowntype)
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30002ERR_UndefinedType1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedType1">
<file name="a.vb"><![CDATA[
Namespace NS1
Structure myStruct
Sub Scen1()
End Sub
End Structure
End Namespace
Namespace NS2
Structure myStruct1
Sub Scen1(ByVal S As myStruct)
End Sub
End Structure
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'myStruct' is not defined.
Sub Scen1(ByVal S As myStruct)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30015ERR_InheritsFromRestrictedType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsFromRestrictedType1">
<file name="a.vb"><![CDATA[
Structure myStruct1
Class C1
'COMPILEERROR: BC30015, "System.Enum"
Inherits System.Enum
End Class
Class C2
'COMPILEERROR: BC30015, "System.MulticastDelegate"
Inherits System.MulticastDelegate
End Class
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30015: Inheriting from '[Enum]' is not valid.
Inherits System.Enum
~~~~~~~~~~~
BC30015: Inheriting from 'MulticastDelegate' is not valid.
Inherits System.MulticastDelegate
~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30022ERR_ReadOnlyHasSet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ReadOnlyHasSet">
<file name="a.vb"><![CDATA[
Class C1
Private newPropertyValue As String
Public ReadOnly Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30022: Properties declared 'ReadOnly' cannot have a 'Set'.
Set(ByVal value As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30022ERR_ReadOnlyHasSet2()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="ReadOnlyHasSet2">
<file name="a.vb"><![CDATA[
Class C1
Inherits D2
Public Overrides ReadOnly Property P_rw_rw_r As Integer
Get
Return MyBase.P_rw_rw_r
End Get
Set(value As Integer)
MyBase.P_rw_rw_r = value
End Set
End Property
End Class
]]></file>
</compilation>, ClassesWithReadWriteProperties)
Dim expectedErrors1 = <errors><![CDATA[
BC30022: Properties declared 'ReadOnly' cannot have a 'Set'.
Set(value As Integer)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30023ERR_WriteOnlyHasGet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="WriteOnlyHasGet">
<file name="a.vb"><![CDATA[
Class C1
Private newPropertyValue As String
Public WriteOnly Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30023: Properties declared 'WriteOnly' cannot have a 'Get'.
Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30023ERR_WriteOnlyHasGet2()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="WriteOnlyHasGet2">
<file name="a.vb"><![CDATA[
Class C1
Inherits D2
Public Overrides WriteOnly Property P_rw_rw_w As Integer
Get
Return MyBase.P_rw_rw_w
End Get
Set(value As Integer)
MyBase.P_rw_rw_w = value
End Set
End Property
End Class
]]></file>
</compilation>, ClassesWithReadWriteProperties)
Dim expectedErrors1 = <errors><![CDATA[
BC30023: Properties declared 'WriteOnly' cannot have a 'Get'.
Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30031ERR_FullyQualifiedNameTooLong1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
Namespace EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE.FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
Namespace HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH.IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
Namespace n
Delegate Sub s()
End Namespace
Namespace KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
Namespace NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
Namespace QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ.RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR.SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
Namespace TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU.VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVv
Class CCCCC(Of T)
Sub s1()
End Sub
Dim x As Integer
Class nestedCCCC
End Class
End Class
Structure ssssss
End Structure
Module mmmmmm
End Module
Enum eee
dummy
End Enum
Interface iii
End Interface
Delegate Sub s()
Delegate Function f() As Integer
End Namespace
End Namespace
End Namespace
End Namespace
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
Dim namespaceName As String = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD.EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE.FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG.HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH.IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ.KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP.QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ.RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR.SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS.TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU.VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVv"
Dim expectedErrors = <errors>
BC37220: Name '<%= namespaceName %>.CCCCC`1' exceeds the maximum length allowed in metadata.
Class CCCCC(Of T)
~~~~~
BC37220: Name '<%= namespaceName %>.ssssss' exceeds the maximum length allowed in metadata.
Structure ssssss
~~~~~~
BC37220: Name '<%= namespaceName %>.mmmmmm' exceeds the maximum length allowed in metadata.
Module mmmmmm
~~~~~~
BC37220: Name '<%= namespaceName %>.eee' exceeds the maximum length allowed in metadata.
Enum eee
~~~
BC37220: Name '<%= namespaceName %>.iii' exceeds the maximum length allowed in metadata.
Interface iii
~~~
BC37220: Name '<%= namespaceName %>.s' exceeds the maximum length allowed in metadata.
Delegate Sub s()
~
BC37220: Name '<%= namespaceName %>.f' exceeds the maximum length allowed in metadata.
Delegate Function f() As Integer
~
</errors>
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
CompilationUtils.AssertTheseEmitDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30050ERR_ParamArrayNotArray()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ERR_ParamArrayNotArray">
<file name="a.vb"><![CDATA[
Option Explicit
Structure myStruct1
Public sub m1(ParamArray byval q)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30050: ParamArray parameter must be an array.
Public sub m1(ParamArray byval q)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30051ERR_ParamArrayRank()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamArrayRank">
<file name="a.vb"><![CDATA[
Class zzz
Shared Sub Main()
End Sub
Sub abc(ByVal ParamArray s(,) As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30051: ParamArray parameter must be a one-dimensional array.
Sub abc(ByVal ParamArray s(,) As Integer)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30121ERR_MultipleExtends()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleExtends">
<file name="a.vb"><![CDATA[
Class C1(of T)
Inherits Object
Inherits system.StringComparer
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits system.StringComparer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30124ERR_PropMustHaveGetSet_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
'COMPILEERROR: BC30124, "aprop"
Property aprop() As String
Get
Return "30124"
End Get
End Property
End Class
Partial Class C1
'COMPILEERROR: BC30124, "aprop"
Property aprop() As String
Set(ByVal Value As String)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Property aprop() As String
~~~~~
BC30269: 'Public Property aprop As String' has multiple definitions with identical signatures.
Property aprop() As String
~~~~~
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Property aprop() As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30124ERR_PropMustHaveGetSet_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Property P
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30125ERR_WriteOnlyHasNoWrite_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
'COMPILEERROR: BC30125, "aprop"
WriteOnly Property aprop() As String
End Property
End Class
Partial Class C1
Property aprop() As String
Set(ByVal Value As String)
End Set
Get
Return "30125"
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30125: 'WriteOnly' property must provide a 'Set'.
WriteOnly Property aprop() As String
~~~~~
BC30366: 'Public WriteOnly Property aprop As String' and 'Public Property aprop As String' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
WriteOnly Property aprop() As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30126ERR_ReadOnlyHasNoGet_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
'COMPILEERROR: BC30126, "aprop"
ReadOnly Property aprop() As String
End Property
End Class
Partial Class C1
Property aprop() As String
Set(ByVal Value As String)
End Set
Get
Return "30126"
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30126: 'ReadOnly' property must provide a 'Get'.
ReadOnly Property aprop() As String
~~~~~
BC30366: 'Public ReadOnly Property aprop As String' and 'Public Property aprop As String' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
ReadOnly Property aprop() As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30149ERR_UnimplementedMember3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedMember3">
<file name="a.vb"><![CDATA[
Interface Ibase
Function one() As String
End Interface
Interface Iderived
Inherits Ibase
Function two() As String
End Interface
Class C1
Implements Iderived
End Class
Partial Class C1
Public Function two() As String Implements Iderived.two
Return "two"
End Function
End Class
Class C2
Implements Iderived
End Class
Partial Class C2
Public Function one() As String Implements Iderived.one
Return "one"
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'C1' must implement 'Function one() As String' for interface 'Ibase'.
Implements Iderived
~~~~~~~~
BC30149: Class 'C2' must implement 'Function two() As String' for interface 'Iderived'.
Implements Iderived
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Spec changed in Roslyn
<WorkItem(528701, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528701")>
<Fact>
Public Sub BC30154ERR_UnimplementedProperty3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedProperty3">
<file name="a.vb"><![CDATA[
Interface PropInterface
Property Scen1() As System.Collections.Generic.IEnumerable(Of Integer)
End Interface
Class HasProps
'COMPILEERROR:BC30154,"PropInterface"
Implements PropInterface
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'HasProps' must implement 'Property Scen1 As IEnumerable(Of Integer)' for interface 'PropInterface'.
Implements PropInterface
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30177ERR_DuplicateModifierCategoryUsed()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateModifierCategoryUsed">
<file name="a.vb"><![CDATA[
MustInherit Class C1
MustOverride notoverridable Overridable Function StringFunc() As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
MustOverride notoverridable Overridable Function StringFunc() As String
~~~~~~~~~~~~~~
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
MustOverride notoverridable Overridable Function StringFunc() As String
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30177ERR_DuplicateModifierCategoryUsed_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateModifierCategoryUsed">
<file name="a.vb"><![CDATA[
MustInherit Class C1
MustOverride Overridable Function StringFunc() As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
MustOverride Overridable Function StringFunc() As String
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30178ERR_DuplicateSpecifier()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateSpecifier">
<file name="a.vb"><![CDATA[
Class test
Shared Shared Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30178: Specifier is duplicated.
Shared Shared Sub Goo()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30178ERR_DuplicateSpecifier_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateSpecifier">
<file name="a.vb"><![CDATA[
class test
friend shared friend function Goo()
End function
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30178: Specifier is duplicated.
friend shared friend function Goo()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for duplicate type declarations
<Fact>
Public Sub BC30179ERR_TypeConflict6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class cc1
End Class
Class cC1
End Class
Class Cc1
End Class
structure CC1
end structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: class 'cc1' and structure 'CC1' conflict in namespace '<Default>'.
Class cc1
~~~
BC30179: class 'cC1' and structure 'CC1' conflict in namespace '<Default>'.
Class cC1
~~~
BC30179: class 'Cc1' and structure 'CC1' conflict in namespace '<Default>'.
Class Cc1
~~~
BC30179: structure 'CC1' and class 'cc1' conflict in namespace '<Default>'.
structure CC1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30179ERR_TypeConflict6_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Enum Unicode
one
End Enum
Class Unicode
End Class
Module Unicode
End Module
Interface Unicode
End Interface
Delegate Sub Unicode()
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: enum 'Unicode' and class 'Unicode' conflict in namespace '<Default>'.
Enum Unicode
~~~~~~~
BC30179: class 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Class Unicode
~~~~~~~
BC30179: module 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Module Unicode
~~~~~~~
BC30179: interface 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Interface Unicode
~~~~~~~
BC30179: delegate Class 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Delegate Sub Unicode()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")>
<Fact>
Public Sub BC30179ERR_TypeConflict6_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Interface I
ReadOnly Property P
ReadOnly Property Q
End Interface
Interface I ' BC30179
Property Q
End Interface
Structure S
Class T
End Class
Interface I
End Interface
End Structure
Structure S ' BC30179
Structure T
End Structure
Dim I
End Structure
Enum E
A
B
End Enum
Enum E ' BC30179
A
End Enum
Class S ' BC30179
Dim T
End Class
Delegate Sub D()
Delegate Function D(s$) ' BC30179
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: interface 'I' and interface 'I' conflict in namespace 'N'.
Interface I ' BC30179
~
BC30179: structure 'S' and class 'S' conflict in namespace 'N'.
Structure S
~
BC30179: structure 'S' and class 'S' conflict in namespace 'N'.
Structure S ' BC30179
~
BC30179: enum 'E' and enum 'E' conflict in namespace 'N'.
Enum E
~
BC30179: enum 'E' and enum 'E' conflict in namespace 'N'.
Enum E ' BC30179
~
BC30179: class 'S' and structure 'S' conflict in namespace 'N'.
Class S ' BC30179
~
BC30179: delegate Class 'D' and delegate Class 'D' conflict in namespace 'N'.
Delegate Function D(s$) ' BC30179
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")>
<Fact>
Public Sub BC30179ERR_TypeConflict6_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Interface I
ReadOnly Property P
ReadOnly Property Q
End Interface
Interface I ' BC30179
Property Q
End Interface
Structure S
Class T
End Class
Interface I
End Interface
End Structure
Structure S ' BC30179
Structure T
End Structure
Dim I
End Structure
Enum E
A
B
End Enum
Enum E ' BC30179
A
End Enum
Class S ' BC30179
Dim T
End Class
Delegate Sub D()
Delegate Function D(s$) ' BC30179
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: interface 'I' and interface 'I' conflict in class 'C'.
Interface I ' BC30179
~
BC30179: structure 'S' and class 'S' conflict in class 'C'.
Structure S
~
BC30179: structure 'S' and class 'S' conflict in class 'C'.
Structure S ' BC30179
~
BC30179: enum 'E' and enum 'E' conflict in class 'C'.
Enum E
~
BC30179: enum 'E' and enum 'E' conflict in class 'C'.
Enum E ' BC30179
~
BC30179: class 'S' and structure 'S' conflict in class 'C'.
Class S ' BC30179
~
BC30179: delegate Class 'D' and delegate Class 'D' conflict in class 'C'.
Delegate Function D(s$) ' BC30179
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30179ERR_TypeConflict6_DupNestedEnumDeclarations()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateEnum1">
<file name="a.vb"><![CDATA[
Structure S1
Enum goo
bar
End Enum
Enum goo
bar
another_bar
End Enum
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: enum 'goo' and enum 'goo' conflict in structure 'S1'.
Enum goo
~~~
BC30179: enum 'goo' and enum 'goo' conflict in structure 'S1'.
Enum goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30179ERR_TypeConflict6_DupEnumDeclarations()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateEnum2">
<file name="a.vb"><![CDATA[
Enum goo
bar
End Enum
Enum goo
bar
another_bar
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: enum 'goo' and enum 'goo' conflict in namespace '<Default>'.
Enum goo
~~~
BC30179: enum 'goo' and enum 'goo' conflict in namespace '<Default>'.
Enum goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30182_ERR_UnrecognizedType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnrecognizedType">
<file name="a.vb"><![CDATA[
Namespace NS
Class C1
Function GOO() As NS
End Function
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30182: Type expected.
Function GOO() As NS
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30182_ERR_UnrecognizedType_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnrecognizedType">
<file name="a.vb"><![CDATA[
Namespace NS
Class C1
inherits NS
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30182: Type expected.
inherits NS
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Structure S1
Public Function Goo()
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Function Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_1()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
option strict on
Public Class c1
Shared Operator + (ByVal c As c1, ByVal b As c1)
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_StrictDisallowsImplicitProc, "+"),
Diagnostic(ERRID.WRN_DefAsgNoRetValOpRef1, "End Operator").WithArguments("+"))
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Interface I
ReadOnly Property P
End Interface
Structure S
WriteOnly Property P
Set(value As Object)
End Set
End Property
End Structure
Class C
Property P(i As Integer)
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
ReadOnly Property P
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
WriteOnly Property P
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Property P(i As Integer)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Delegate Sub D()
Delegate Function E(o As Object)
Delegate Function F() As Object
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Delegate Function E(o As Object)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_Declare()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module M
Declare Sub test Lib "???" (a As Integer)
Declare Sub F Lib "bar" ()
Declare Function G Lib "bar" ()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Declare Function G Lib "bar" ()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30211ERR_StrictDisallowsImplicitArgs()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Structure S1
Public Function Goo(byval x) as integer
return 1
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Public Function Goo(byval x) as integer
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30211ERR_StrictDisallowsImplicitArgs_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Interface I
ReadOnly Property P(i) As Object
End Interface
Structure S
WriteOnly Property P(x) As Object
Set(value)
End Set
End Property
End Structure
Class C
Property P(val) As I
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
ReadOnly Property P(i) As Object
~
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
WriteOnly Property P(x) As Object
~
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Set(value)
~~~~~
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Property P(val) As I
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30230ERR_ModuleCantInherit()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantInherit">
<file name="a.vb"><![CDATA[
interface I1
End interface
module M1
Inherits I1
End module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30230: 'Inherits' not valid in Modules.
Inherits I1
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30231ERR_ModuleCantImplement()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantImplement">
<file name="a.vb"><![CDATA[
Module M1
Implements Object
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30231: 'Implements' not valid in Modules.
Implements Object
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30232ERR_BadImplementsType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadImplementsType">
<file name="a.vb"><![CDATA[
Class cls1
Implements system.Enum
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30232: Implemented type must be an interface.
Implements system.Enum
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30233ERR_BadConstFlags1()
Dim source =
<compilation name="delegates">
<file name="a.vb"><![CDATA[
Option strict on
imports system
Class C1
' BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
Public Const Shared c As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
Public Const ReadOnly e As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Shared ReadOnly Const f As String = "goo"
End Class
Module M1
' Roslyn: Only BC30593: Variables in Modules cannot be declared 'Shared'.
' Dev10: Additional BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
Public Const Shared c As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
Public Const ReadOnly e As String = "goo"
End Module
Structure S1
' BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
Public Const Shared c As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
Public Const ReadOnly e As String = "goo"
End Structure
]]></file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected><![CDATA[
BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Const Shared c As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
~~~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Const ReadOnly e As String = "goo"
~~~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Shared ReadOnly Const f As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Shared ReadOnly Const f As String = "goo"
~~~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Public Shared Const b As String = "goo"
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Public Const Shared c As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
~~~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Const ReadOnly e As String = "goo"
~~~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Const Shared c As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
~~~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Const ReadOnly e As String = "goo"
~~~~~~~~
]]></expected>)
End Sub
<WorkItem(528365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528365")>
<Fact>
Public Sub BC30233ERR_BadConstFlags1_02()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadConstFlags1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
Module M1
'COMPILEERROR: BC30233, "Static"
Static Const p As Integer = AscW("10")
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30235: 'Static' is not valid on a member variable declaration.
Static Const p As Integer = AscW("10")
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30234ERR_BadWithEventsFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadWithEventsFlags1">
<file name="a.vb"><![CDATA[
Module M1
'COMPILEERROR: BC30234, "ReadOnly"
ReadOnly WithEvents var1 As Object
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30234: 'ReadOnly' is not valid on a WithEvents declaration.
ReadOnly WithEvents var1 As Object
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30235ERR_BadDimFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadDimFlags1">
<file name="a.vb"><![CDATA[
Class cls1
Default i As Integer
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30235: 'Default' is not valid on a member variable declaration.
Default i As Integer
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30237ERR_DuplicateParamName1_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option strict on
Module m
Sub s1(ByVal a As Integer, ByVal a As Integer, a as string)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30237: Parameter already declared with name 'a'.
Sub s1(ByVal a As Integer, ByVal a As Integer, a as string)
~
BC30237: Parameter already declared with name 'a'.
Sub s1(ByVal a As Integer, ByVal a As Integer, a as string)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30237ERR_DuplicateParamName1_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P(ByVal a, ByVal b)
Set(ByVal b)
End Set
End Property
Property Q(x, y, x)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30237: Parameter already declared with name 'b'.
Set(ByVal b)
~
BC30237: Parameter already declared with name 'x'.
Property Q(x, y, x)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30237ERR_DuplicateParamName1_ExternalMethods()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
<MethodImplAttribute(MethodCodeType:=MethodCodeType.Runtime)>
Shared Sub Runtime(a As Integer, a As Integer)
End Sub
<MethodImpl(MethodImplOptions.InternalCall)>
Shared Sub InternalCall(b As Integer, b As Integer)
End Sub
<DllImport("goo")>
Shared Sub DllImp(c As Integer, c As Integer)
End Sub
Declare Sub DeclareSub Lib "bar" (d As Integer, d As Integer)
End Class
]]></file>
</compilation>
CreateCompilationWithMscorlib40(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_DuplicateParamName1, "a").WithArguments("a"),
Diagnostic(ERRID.ERR_DuplicateParamName1, "b").WithArguments("b"),
Diagnostic(ERRID.ERR_DuplicateParamName1, "c").WithArguments("c"))
End Sub
<Fact>
Public Sub BC30242ERR_BadMethodFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadMethodFlags1">
<file name="a.vb"><![CDATA[
Structure S1
Default function goo()
End function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30242: 'Default' is not valid on a method declaration.
Default function goo()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30243ERR_BadEventFlags1()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadEventFlags1">
<file name="a.vb"><![CDATA[
Class c1
Shared Event e1()
Public Event e2()
Sub raiser1()
RaiseEvent e1()
End Sub
Sub raiser2()
RaiseEvent e2()
End Sub
End Class
Class c2
Inherits c1
'COMPILEERROR: BC30243, "Overrides"
Overrides Event e1()
'COMPILEERROR: BC30243, "Overloads"
Overloads Event e2(ByVal i As Integer)
'COMPILEERROR: BC30243, "Overloads", BC30243, "Overrides"
Overloads Overrides Event e3(ByVal i As Integer)
'COMPILEERROR: BC30243, "NotOverridable"
NotOverridable Event e4()
'COMPILEERROR: BC30243, "Default"
Default Event e5()
'COMPILEERROR: BC30243, "Static"
Static Event e6()
End Class
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_BadEventFlags1, "Overrides").WithArguments("Overrides"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Overloads").WithArguments("Overloads"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Overloads").WithArguments("Overloads"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Overrides").WithArguments("Overrides"),
Diagnostic(ERRID.ERR_BadEventFlags1, "NotOverridable").WithArguments("NotOverridable"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Default").WithArguments("Default"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Static").WithArguments("Static"),
Diagnostic(ERRID.WRN_OverrideType5, "e1").WithArguments("event", "e1", "event", "class", "c1"),
Diagnostic(ERRID.WRN_OverrideType5, "e2").WithArguments("event", "e2", "event", "class", "c1"))
End Sub
' BC30244ERR_BadDeclareFlags1
' see AttributeTests
<WorkItem(527697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527697")>
<Fact>
Public Sub BC30246ERR_BadLocalConstFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadLocalConstFlags1">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
'COMPILEERROR: BC30246, "Shared"
Shared Const x As Integer = 10
End Sub
End Module
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"),
Diagnostic(ERRID.WRN_UnusedLocalConst, "x").WithArguments("x"))
End Sub
<WorkItem(538967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538967")>
<Fact>
Public Sub BC30247ERR_BadLocalDimFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadLocalDimFlags1">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
'COMPILEERROR: BC30247, "Shared"
Shared x As Integer = 10
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30247: 'Shared' is not valid on a local variable declaration.
Shared x As Integer = 10
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30257ERR_InheritanceCycle1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InheritanceCycle1">
<file name="a.vb"><![CDATA[
Public Class C1
Inherits C2
End Class
Public Class C2
Inherits C1
End Class
Module M1
Sub Main()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30257: Class 'C1' cannot inherit from itself:
'C1' inherits from 'C2'.
'C2' inherits from 'C1'.
Inherits C2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30258ERR_InheritsFromNonClass()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsFrom2">
<file name="a.vb"><![CDATA[
Structure myStruct1
Class C1
Inherits myStruct1
End Class
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30258: Classes can inherit only from other classes.
Inherits myStruct1
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for duplicate type declarations
' DEV code
<Fact>
Public Sub BC30260ERR_MultiplyDefinedType3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
class c
sub i(ByVal i As Integer)
End Sub
dim i(,,) as integer
Public i, i As Integer
Private i As Integer
Sub i()
End Sub
end class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
dim i(,,) as integer
~
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
Public i, i As Integer
~
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
Public i, i As Integer
~
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
Private i As Integer
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30260ERR_MultiplyDefinedType3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Enum E As Short
A
End Enum
Function E()
End Function
End Class
Interface I
Structure S
End Structure
Sub S()
End Interface
Structure S
Class C
End Class
Property C
Interface I
End Interface
Private I
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30260: 'E' is already declared as 'Enum E' in this class.
Function E()
~
BC30260: 'S' is already declared as 'Structure S' in this interface.
Sub S()
~
BC30260: 'C' is already declared as 'Class C' in this structure.
Property C
~
BC30260: 'I' is already declared as 'Interface I' in this structure.
Private I
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30260ERR_MultiplyDefinedType3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class C
Overloads Property P
Overloads Function P(o)
Return Nothing
End Function
Overloads Shared Property Q(o)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Overloads Sub Q()
End Sub
Class R
End Class
ReadOnly Property R(x, y)
Get
Return Nothing
End Get
End Property
Private WriteOnly Property S As Integer
Set(value As Integer)
End Set
End Property
Structure S
End Structure
Private Shared ReadOnly Property T As Integer
Get
Return 0
End Get
End Property
Private T
Friend MustOverride Overloads Function U()
Protected Property U
Protected V As Object
Friend Shared Property V
End Class
]]></file>
</compilation>)
' Note: Unlike Dev10, the error with 'S' is reported on the property
' rather than the struct, even though the struct appears first in source.
' That is because types are resolved before other members.
Dim expectedErrors1 = <errors><![CDATA[
BC30260: 'P' is already declared as 'Public Overloads Property P As Object' in this class.
Overloads Function P(o)
~
BC30260: 'Q' is already declared as 'Public Shared Overloads Property Q(o As Object) As Object' in this class.
Overloads Sub Q()
~
BC30260: 'R' is already declared as 'Class R' in this class.
ReadOnly Property R(x, y)
~
BC30260: 'S' is already declared as 'Structure S' in this class.
Private WriteOnly Property S As Integer
~
BC30260: 'T' is already declared as 'Private Shared ReadOnly Property T As Integer' in this class.
Private T
~
BC30260: 'U' is already declared as 'Friend MustOverride Overloads Function U() As Object' in this class.
Protected Property U
~
BC30260: 'V' is already declared as 'Protected V As Object' in this class.
Friend Shared Property V
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30266ERR_BadOverrideAccess2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadLocalDimFlags1">
<file name="a.vb"><![CDATA[
Namespace NS1
Class base
Protected Overridable Function scen2(Of t)(ByVal x As t) As String
Return "30266"
End Function
Public Overridable Function scen1(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
Partial Class base
Friend Overridable Function scen3(Of t)(ByVal x As t) As String
Return "30266"
End Function
Protected Friend Overridable Function scen4(Of t)(ByVal x As t) As String
Return "30266"
End Function
Private Protected Overridable Function scen5(Of t)(ByVal x As t) As String
Return "30266"
End Function
Protected Overridable Function scen6(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
Partial Class derived
'COMPILEERROR: BC30266, "scen4"
Protected Overrides Function scen4(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
Class derived
Inherits base
'COMPILEERROR: BC30266, "scen2"
Friend Overrides Function scen2(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen3"
Public Overrides Function scen3(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen1"
Protected Overrides Function scen1(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen5"
Protected Overrides Function scen5(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen6"
Private Protected Overrides Function scen6(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
End Namespace
]]></file>
</compilation>,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_5))
Dim expectedErrors1 = <errors><![CDATA[
BC30266: 'Protected Overrides Function scen4(Of t)(x As t) As String' cannot override 'Protected Friend Overridable Function scen4(Of t)(x As t) As String' because they have different access levels.
Protected Overrides Function scen4(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Friend Overrides Function scen2(Of t)(x As t) As String' cannot override 'Protected Overridable Function scen2(Of t)(x As t) As String' because they have different access levels.
Friend Overrides Function scen2(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Public Overrides Function scen3(Of t)(x As t) As String' cannot override 'Friend Overridable Function scen3(Of t)(x As t) As String' because they have different access levels.
Public Overrides Function scen3(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Protected Overrides Function scen1(Of t)(x As t) As String' cannot override 'Public Overridable Function scen1(Of t)(x As t) As String' because they have different access levels.
Protected Overrides Function scen1(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Protected Overrides Function scen5(Of t)(x As t) As String' cannot override 'Private Protected Overridable Function scen5(Of t)(x As t) As String' because they have different access levels.
Protected Overrides Function scen5(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Private Protected Overrides Function scen6(Of t)(x As t) As String' cannot override 'Protected Overridable Function scen6(Of t)(x As t) As String' because they have different access levels.
Private Protected Overrides Function scen6(Of t)(ByVal x As t) As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30267ERR_CantOverrideNotOverridable2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverrideNotOverridable2">
<file name="a.vb"><![CDATA[
Class c1
Class c1_0
Overridable Sub goo()
End Sub
End Class
Class c1_1
Inherits c1_0
NotOverridable Overrides Sub goo()
End Sub
End Class
Class c1_2
Inherits c1_1
'COMPILEERROR: BC30267, "goo"
Overrides Sub goo()
End Sub
End Class
End Class
Class c1_2
Inherits c1.c1_1
'COMPILEERROR: BC30267, "goo"
Overrides Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30267: 'Public Overrides Sub goo()' cannot override 'Public NotOverridable Overrides Sub goo()' because it is declared 'NotOverridable'.
Overrides Sub goo()
~~~
BC30267: 'Public Overrides Sub goo()' cannot override 'Public NotOverridable Overrides Sub goo()' because it is declared 'NotOverridable'.
Overrides Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30269ERR_DuplicateProcDef1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Class C1
Public Sub New() ' 1
End Sub
Public Sub New() ' 2
End Sub
Shared Sub New() ' ok :)
End Sub
Public Sub Goo1() ' 1
End Sub
Public Sub Goo1() ' 2
End Sub
Public Sub Goo1() ' 3
End Sub
Public overloads Sub Goo2() ' 1
End Sub
Public overloads Sub Goo2() ' 2
End Sub
Public Sub Goo3(Of T)(X As T) ' 1
End Sub
Public Sub Goo3(Of TT)(X As TT) ' 2
End Sub
Public Sub GooOK(x as Integer) ' 1
End Sub
Public Sub GooOK(x as Decimal) ' 2
End Sub
Public Shared Sub Main()
End Sub
End Class
Class Base
public overridable sub goo4() ' base
End sub
End Class
Class Derived
Inherits Base
public overrides sub goo4() ' derived 1
End sub
public overloads sub goo4() ' derived 2
End sub
End Class
Class PartialClass
Public Sub Goo5() ' 1
End Sub
Public Sub Goo6(x as integer)
End Sub
End Class
Partial Class PartialClass
Public Sub Goo5() ' 2
End Sub
Public Sub Goo6(y as integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Public Sub New()' has multiple definitions with identical signatures.
Public Sub New() ' 1
~~~
BC30269: 'Public Sub Goo1()' has multiple definitions with identical signatures.
Public Sub Goo1() ' 1
~~~~
BC30269: 'Public Sub Goo1()' has multiple definitions with identical signatures.
Public Sub Goo1() ' 2
~~~~
BC30269: 'Public Overloads Sub Goo2()' has multiple definitions with identical signatures.
Public overloads Sub Goo2() ' 1
~~~~
BC30269: 'Public Sub Goo3(Of T)(X As T)' has multiple definitions with identical signatures.
Public Sub Goo3(Of T)(X As T) ' 1
~~~~
BC30269: 'Public Overrides Sub goo4()' has multiple definitions with identical signatures.
public overrides sub goo4() ' derived 1
~~~~
BC30269: 'Public Sub Goo5()' has multiple definitions with identical signatures.
Public Sub Goo5() ' 1
~~~~
BC30269: 'Public Sub Goo6(x As Integer)' has multiple definitions with identical signatures.
Public Sub Goo6(x as integer)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30269ERR_DuplicateProcDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Interface ii
Sub abc()
End Interface
Structure teststruct
Implements ii
'COMPILEERROR: BC30269, "abc"
Public Sub abc() Implements ii.abc
End Sub
'COMPILEERROR: BC30269, "New"
Public Sub New(ByVal x As String)
End Sub
End Structure
Partial Structure teststruct
Implements ii
Public Sub New(ByVal x As String)
End Sub
Public Sub abc() Implements ii.abc
End Sub
End Structure
]]></file>
</compilation>)
' TODO: The last error is expected to go away once "Implements" is supported.
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Public Sub abc()' has multiple definitions with identical signatures.
Public Sub abc() Implements ii.abc
~~~
BC30269: 'Public Sub New(x As String)' has multiple definitions with identical signatures.
Public Sub New(ByVal x As String)
~~~
BC30583: 'ii.abc' cannot be implemented more than once.
Public Sub abc() Implements ii.abc
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(543162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543162")>
<Fact()>
Public Sub BC30269ERR_DuplicateProcDef1_Shared()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Class C1
Public Sub New1() ' 1
End Sub
Public Shared Sub New1() ' 2
End Sub
End Class
]]></file>
</compilation>)
AssertTheseDiagnostics(compilation1, errs:=<expected><![CDATA[
BC30269: 'Public Sub New1()' has multiple definitions with identical signatures.
Public Sub New1() ' 1
~~~~
]]></expected>)
End Sub
<Fact>
Public Sub BC30270ERR_BadInterfaceMethodFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceMethodFlags1">
<file name="a.vb"><![CDATA[
Imports System.Collections
Interface I
Public Function A()
Private Function B()
Protected Function C()
Friend Function D()
Shared Function E()
MustInherit Function F()
NotInheritable Function G()
Overrides Function H()
Partial Function J()
NotOverridable Function K()
Overridable Function L()
Iterator Function Goo() as IEnumerator
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30270: 'Public' is not valid on an interface method declaration.
Public Function A()
~~~~~~
BC30270: 'Private' is not valid on an interface method declaration.
Private Function B()
~~~~~~~
BC30270: 'Protected' is not valid on an interface method declaration.
Protected Function C()
~~~~~~~~~
BC30270: 'Friend' is not valid on an interface method declaration.
Friend Function D()
~~~~~~
BC30270: 'Shared' is not valid on an interface method declaration.
Shared Function E()
~~~~~~
BC30242: 'MustInherit' is not valid on a method declaration.
MustInherit Function F()
~~~~~~~~~~~
BC30242: 'NotInheritable' is not valid on a method declaration.
NotInheritable Function G()
~~~~~~~~~~~~~~
BC30270: 'Overrides' is not valid on an interface method declaration.
Overrides Function H()
~~~~~~~~~
BC30270: 'Partial' is not valid on an interface method declaration.
Partial Function J()
~~~~~~~
BC30270: 'NotOverridable' is not valid on an interface method declaration.
NotOverridable Function K()
~~~~~~~~~~~~~~
BC30270: 'Overridable' is not valid on an interface method declaration.
Overridable Function L()
~~~~~~~~~~~
BC30270: 'Iterator' is not valid on an interface method declaration.
Iterator Function Goo() as IEnumerator
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30273ERR_BadInterfacePropertyFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfacePropertyFlags1">
<file name="a.vb"><![CDATA[
Imports System.Collections
Interface I
Public Property A
Private Property B
Protected Property C
Friend Property D
Shared Property E
MustInherit Property F
NotInheritable Property G
Overrides Property H
NotOverridable Property J
Overridable Property K
ReadOnly Property L ' No error
WriteOnly Property M ' No error
Default Property N(o) ' No error
Iterator Property Goo() as IEnumerator
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30273: 'Public' is not valid on an interface property declaration.
Public Property A
~~~~~~
BC30273: 'Private' is not valid on an interface property declaration.
Private Property B
~~~~~~~
BC30273: 'Protected' is not valid on an interface property declaration.
Protected Property C
~~~~~~~~~
BC30273: 'Friend' is not valid on an interface property declaration.
Friend Property D
~~~~~~
BC30273: 'Shared' is not valid on an interface property declaration.
Shared Property E
~~~~~~
BC30639: Properties cannot be declared 'MustInherit'.
MustInherit Property F
~~~~~~~~~~~
BC30639: Properties cannot be declared 'NotInheritable'.
NotInheritable Property G
~~~~~~~~~~~~~~
BC30273: 'Overrides' is not valid on an interface property declaration.
Overrides Property H
~~~~~~~~~
BC30273: 'NotOverridable' is not valid on an interface property declaration.
NotOverridable Property J
~~~~~~~~~~~~~~
BC30273: 'Overridable' is not valid on an interface property declaration.
Overridable Property K
~~~~~~~~~~~
BC30273: 'Iterator' is not valid on an interface property declaration.
Iterator Property Goo() as IEnumerator
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30275ERR_InterfaceCantUseEventSpecifier1()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceCantUseEventSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
'COMPILEERROR: BC30275, "friend"
Friend Event goo()
End Interface
Interface I2
'COMPILEERROR: BC30275, "protected"
Protected Event goo()
End Interface
Interface I3
'COMPILEERROR: BC30275, "Private"
Private Event goo()
End Interface
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InterfaceCantUseEventSpecifier1, "Friend").WithArguments("Friend"),
Diagnostic(ERRID.ERR_InterfaceCantUseEventSpecifier1, "Protected").WithArguments("Protected"),
Diagnostic(ERRID.ERR_InterfaceCantUseEventSpecifier1, "Private").WithArguments("Private"))
End Sub
<WorkItem(539943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539943")>
<Fact>
Public Sub BC30280ERR_BadEmptyEnum1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadEmptyEnum1">
<file name="a.vb"><![CDATA[
Enum SEX
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30280: Enum 'SEX' must contain at least one member.
Enum SEX
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30283ERR_CantOverrideConstructor()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverrideConstructor">
<file name="a.vb"><![CDATA[
Class Class2
Inherits Class1
Overrides Sub New()
End Sub
End Class
Class Class1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30283: 'Sub New' cannot be declared 'Overrides'.
Overrides Sub New()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30284ERR_OverrideNotNeeded3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideNotNeeded3">
<file name="a.vb"><![CDATA[
Imports System
Namespace NS30284
Public Class Class1
Dim xprop2, xprop3, xprop5
End Class
Public Class Class2
Inherits Class1
Interface interface1
ReadOnly Property prop1()
WriteOnly Property prop2()
WriteOnly Property prop3()
ReadOnly Property prop5()
End Interface
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal val As Short)
MyBase.New()
End Sub
'COMPILEERROR: BC30284, "prop1"
Overrides WriteOnly Property prop1() As String
Set(ByVal Value As String)
End Set
End Property
'COMPILEERROR: BC30284, "prop2"
Overrides ReadOnly Property prop2() As String
Get
Return "30284"
End Get
End Property
'COMPILEERROR: BC30284, "prop3"
Overrides Property prop3() As String
Get
Return "30284"
End Get
Set(ByVal Value As String)
End Set
End Property
'COMPILEERROR: BC30284, "prop5"
Overrides ReadOnly Property prop5()
Get
Return "30284"
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30284: property 'prop1' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides WriteOnly Property prop1() As String
~~~~~
BC30284: property 'prop2' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides ReadOnly Property prop2() As String
~~~~~
BC30284: property 'prop3' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides Property prop3() As String
~~~~~
BC30284: property 'prop5' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides ReadOnly Property prop5()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' <Fact()>
' Public Sub BC30293ERR_RecordEmbeds2()
' Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib(
' <compilation name="RecordEmbeds2">
' <file name="a.vb"><![CDATA[
' Class C1
' End Class
' Class C2
' Inherits C1
' Overrides WriteOnly Property prop1() As String
' Set(ByVal value As String)
' End Set
' End Property
' End Class
' ]]></file>
' </compilation>)
' Dim expectedErrors1 = <errors><![CDATA[
'BC30293: property 'prop1' cannot be declared 'Overrides' because it does not override a property in a base class.
' Overrides WriteOnly Property prop1() As String
' ~~~~~~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
' End Sub
<Fact>
Public Sub BC30294ERR_RecordCycle2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="RecordCycle2">
<file name="a.vb"><![CDATA[
Public Structure yyy
Dim a As yyy
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30294: Structure 'yyy' cannot contain an instance of itself:
'yyy' contains 'yyy' (variable 'a').
Dim a As yyy
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30296ERR_InterfaceCycle1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceCycle1">
<file name="a.vb"><![CDATA[
Public Class c0
Protected Class cls1
Public Interface I2
Interface I2
Inherits I2
End Interface
End Interface
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30296: Interface 'c0.cls1.I2.I2' cannot inherit from itself:
'c0.cls1.I2.I2' inherits from 'c0.cls1.I2.I2'.
Inherits I2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30299ERR_InheritsFromCantInherit3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsFromCantInherit3">
<file name="a.vb"><![CDATA[
Class c1
NotInheritable Class c1_1
Class c1_4
Inherits c1_1
End Class
End Class
Class c1_2
Inherits c1_1
End Class
End Class
Class c1_3
Inherits c1.c1_1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30299: 'c1_4' cannot inherit from class 'c1_1' because 'c1_1' is declared 'NotInheritable'.
Inherits c1_1
~~~~
BC30299: 'c1_2' cannot inherit from class 'c1_1' because 'c1_1' is declared 'NotInheritable'.
Inherits c1_1
~~~~
BC30299: 'c1_3' cannot inherit from class 'c1_1' because 'c1_1' is declared 'NotInheritable'.
Inherits c1.c1_1
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30300ERR_OverloadWithOptional2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithOptional2">
<file name="a.vb"><![CDATA[
Class Cla30300
'COMPILEERROR: BC30300, "goo"
Public Function goo(ByVal arg As ULong)
Return "BC30300"
End Function
Public Function goo(Optional ByVal arg As ULong = 1)
Return "BC30300"
End Function
'COMPILEERROR: BC30300, "goo1"
Public Function goo1()
Return "BC30300"
End Function
Public Function goo1(Optional ByVal arg As ULong = 1)
Return "BC30300"
End Function
'COMPILEERROR: BC30300, "goo2"
Public Function goo2(ByVal arg As Integer)
Return "BC30300"
End Function
Public Function goo2(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
Return "BC30300"
End Function
'COMPILEERROR: BC30300, "goo3"
Public Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
Return "BC30300"
End Function
Public Function goo3(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
Return "BC30300"
End Function
End Class
Interface Scen2_1
'COMPILEERROR: BC30300, "goo"
Function goo(ByVal arg As ULong)
Function goo(Optional ByVal arg As ULong = 1)
'COMPILEERROR: BC30300, "goo1"
Function goo1()
Function goo1(Optional ByVal arg As ULong = 1)
'COMPILEERROR: BC30300, "goo2"
Function goo2(ByVal arg As Integer)
Function goo2(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
'COMPILEERROR: BC30300, "goo3"
Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
Function goo3(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30300: 'Public Function goo(arg As ULong) As Object' and 'Public Function goo([arg As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Public Function goo(ByVal arg As ULong)
~~~
BC30300: 'Public Function goo3(arg As Integer, arg1 As ULong) As Object' and 'Public Function goo3(arg As Integer, [arg1 As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Public Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
~~~~
BC30300: 'Function goo(arg As ULong) As Object' and 'Function goo([arg As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Function goo(ByVal arg As ULong)
~~~
BC30300: 'Function goo3(arg As Integer, arg1 As ULong) As Object' and 'Function goo3(arg As Integer, [arg1 As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30301ERR_OverloadWithReturnType2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Class C1
End Class
Class C2
End Class
Class C3
Public Function Goo1(x as Integer) as Boolean ' 1
return true
End Function
Public Function Goo1(x as Integer) as Boolean ' 2
return true
End Function
Public Function Goo1(x as Integer) as Boolean ' 3
return true
End Function
Public Function Goo1(x as Integer) as Decimal ' 4
return 2.2
End Function
Public Function Goo1(x as Integer) as String ' 5
return "42"
End Function
Public Function Goo2(Of T as C1)(x as Integer) as T ' 1
return nothing
End Function
Public Function Goo2(Of S as C2)(x as Integer) as S ' 2
return nothing
End Function
Public Function Goo3(x as Integer) as Boolean ' 1
return true
End Function
Public Function Goo3(x as Decimal) as Boolean ' 2
return true
End Function
Public Function Goo3(x as Integer) as Boolean ' 3
return true
End Function
Public Function Goo3(x as Integer) as Boolean ' 4
return true
End Function
Public Function Goo3(x as Integer) as String ' 5
return true
End Function
Public Shared Sub Main()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Public Function Goo1(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo1(x as Integer) as Boolean ' 1
~~~~
BC30269: 'Public Function Goo1(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo1(x as Integer) as Boolean ' 2
~~~~
BC30301: 'Public Function Goo1(x As Integer) As Boolean' and 'Public Function Goo1(x As Integer) As Decimal' cannot overload each other because they differ only by return types.
Public Function Goo1(x as Integer) as Boolean ' 3
~~~~
BC30301: 'Public Function Goo1(x As Integer) As Decimal' and 'Public Function Goo1(x As Integer) As String' cannot overload each other because they differ only by return types.
Public Function Goo1(x as Integer) as Decimal ' 4
~~~~
BC30269: 'Public Function Goo2(Of T As C1)(x As Integer) As T' has multiple definitions with identical signatures.
Public Function Goo2(Of T as C1)(x as Integer) as T ' 1
~~~~
BC30269: 'Public Function Goo3(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo3(x as Integer) as Boolean ' 1
~~~~
BC30269: 'Public Function Goo3(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo3(x as Integer) as Boolean ' 3
~~~~
BC30301: 'Public Function Goo3(x As Integer) As Boolean' and 'Public Function Goo3(x As Integer) As String' cannot overload each other because they differ only by return types.
Public Function Goo3(x as Integer) as Boolean ' 4
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30301ERR_OverloadWithReturnType2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithReturnType2">
<file name="a.vb"><![CDATA[
Class Cla30301
'COMPILEERROR: BC30301, "goo"
Public Function goo(ByVal arg As ULong)
Return "BC30301"
End Function
Public Function goo(ByVal arg As ULong) As String
Return "BC30301"
End Function
'COMPILEERROR: BC30301, "goo1"
Public Function goo1()
Return "BC30301"
End Function
Public Function goo1() As String
Return "BC30301"
End Function
End Class
Interface Interface30301
'COMPILEERROR: BC30301, "goo"
Function goo(ByVal arg As ULong)
Function goo(ByVal arg As ULong) As String
'COMPILEERROR: BC30301, "goo1"
Function goo1()
Function goo1() As String
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30301: 'Public Function goo(arg As ULong) As Object' and 'Public Function goo(arg As ULong) As String' cannot overload each other because they differ only by return types.
Public Function goo(ByVal arg As ULong)
~~~
BC30301: 'Public Function goo1() As Object' and 'Public Function goo1() As String' cannot overload each other because they differ only by return types.
Public Function goo1()
~~~~
BC30301: 'Function goo(arg As ULong) As Object' and 'Function goo(arg As ULong) As String' cannot overload each other because they differ only by return types.
Function goo(ByVal arg As ULong)
~~~
BC30301: 'Function goo1() As Object' and 'Function goo1() As String' cannot overload each other because they differ only by return types.
Function goo1()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_01()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Class C
Dim A% As Integer
Dim B& As Long
Dim C@ As Decimal
Dim D! As Single
Dim E# As Double
Dim F$ As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Dim A% As Integer
~~
BC30302: Type character '&' cannot be used in a declaration with an explicit type.
Dim B& As Long
~~
BC30302: Type character '@' cannot be used in a declaration with an explicit type.
Dim C@ As Decimal
~~
BC30302: Type character '!' cannot be used in a declaration with an explicit type.
Dim D! As Single
~~
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
Dim E# As Double
~~
BC30302: Type character '$' cannot be used in a declaration with an explicit type.
Dim F$ As String
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_02()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Class C
Property A% As Integer
Property B& As Long
Property C@ As Decimal
Property D! As Single
Property E# As Double
Property F$ As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Property A% As Integer
~~
BC30302: Type character '&' cannot be used in a declaration with an explicit type.
Property B& As Long
~~
BC30302: Type character '@' cannot be used in a declaration with an explicit type.
Property C@ As Decimal
~~
BC30302: Type character '!' cannot be used in a declaration with an explicit type.
Property D! As Single
~~
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
Property E# As Double
~~
BC30302: Type character '$' cannot be used in a declaration with an explicit type.
Property F$ As String
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_03()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Option Infer On
Class C
Shared Sub Main()
For Each x% In New Integer() {1, 1}
Next
For Each x& In New Long() {1, 1}
Next
For Each x! In New Double() {1, 1}
Next
For Each x# In New Double() {1, 1}
Next
For Each x@ In New Decimal() {1, 1}
Next
'COMPILEERROR: BC30302
For Each x% As Long In New Long() {1, 1, 1}
Next
For Each x# As Single In New Double() {1, 1, 1}
Next
For Each x@ As Decimal In New Decimal() {1, 1, 1}
Next
For Each x! As Object In New Long() {1, 1, 1}
Next
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
For Each x% As Long In New Long() {1, 1, 1}
~~
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
For Each x# As Single In New Double() {1, 1, 1}
~~
BC30302: Type character '@' cannot be used in a declaration with an explicit type.
For Each x@ As Decimal In New Decimal() {1, 1, 1}
~~
BC30302: Type character '!' cannot be used in a declaration with an explicit type.
For Each x! As Object In New Long() {1, 1, 1}
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_04()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Infer On
Imports System
Module Module1
Sub Main()
Dim arr15#(,) As Double ' Invalid
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
Dim arr15#(,) As Double ' Invalid
~~~~~~
BC42024: Unused local variable: 'arr15'.
Dim arr15#(,) As Double ' Invalid
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30303ERR_TypeCharOnSub()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeCharOnSub">
<file name="a.vb"><![CDATA[
Interface I1
Sub x%()
Sub x#()
Sub x@()
Sub x!()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Sub x()' has multiple definitions with identical signatures.
Sub x%()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x%()
~~
BC30269: 'Sub x()' has multiple definitions with identical signatures.
Sub x#()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x#()
~~
BC30269: 'Sub x()' has multiple definitions with identical signatures.
Sub x@()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x@()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x!()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30305ERR_PartialMethodDefaultParameterValue2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
'COMPILEERROR: BC30305, "Goo6"
Partial Private Sub Goo6(Optional ByVal x As Integer = 1)
End Sub
Private Sub Goo6(Optional ByVal x As Integer = 2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC37203: Optional parameter of a method 'Private Sub Goo6([x As Integer = 2])' does not have the same default value as the corresponding parameter of the partial method 'Private Sub Goo6([x As Integer = 1])'.
Private Sub Goo6(Optional ByVal x As Integer = 2)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30305ERR_OverloadWithDefault2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
'COMPILEERROR: BC30305, "Goo6"
Partial Private Sub Goo6(Optional ByVal x As Integer = 1)
End Sub
Sub Goo6(Optional ByVal x As Integer = 2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31441: Method 'Goo6' must be declared 'Private' in order to implement partial method 'Goo6'.
Sub Goo6(Optional ByVal x As Integer = 2)
~~~~
BC37203: Optional parameter of a method 'Public Sub Goo6([x As Integer = 2])' does not have the same default value as the corresponding parameter of the partial method 'Private Sub Goo6([x As Integer = 1])'.
Sub Goo6(Optional ByVal x As Integer = 2)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(ParamArray x() As Integer)
End Sub
Private Sub Goo6(x() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC37204: Parameter of a method 'Private Sub Goo6(x As Integer())' differs by ParamArray modifier from the corresponding parameter of the partial method 'Private Sub Goo6(ParamArray x As Integer())'.
Private Sub Goo6(x() As Integer)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(x() As Integer)
End Sub
Private Sub Goo6(ParamArray x() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC37204: Parameter of a method 'Private Sub Goo6(ParamArray x As Integer())' differs by ParamArray modifier from the corresponding parameter of the partial method 'Private Sub Goo6(x As Integer())'.
Private Sub Goo6(ParamArray x() As Integer)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
''' <remarks>Only use with PEModuleSymbol and PEParameterSymbol</remarks>
Private Sub AssertHasExactlyOneParamArrayAttribute(m As ModuleSymbol, paramSymbol As ParameterSymbol)
Dim peModule = DirectCast(m, PEModuleSymbol).Module
Dim paramHandle = DirectCast(paramSymbol, PEParameterSymbol).Handle
Assert.Equal(1, peModule.GetParamArrayCountOrThrow(paramHandle))
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Private Sub Goo6(x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(x() As Integer)
End Sub
Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(ParamArray x() As Integer)
End Sub
Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Private Sub Goo6(ParamArray x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_7()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30663: Attribute 'ParamArrayAttribute' cannot be applied multiple times.
Private Sub Goo6(<System.ParamArray()> x() As Integer)
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_8()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(ParamArray x() As Integer)
End Sub
Private Sub Goo6(ParamArray x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_9()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(x() As Integer)
End Sub
Private Sub Goo6(x() As Integer)
End Sub
Sub Use()
Goo6(Nothing)
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.False(GooParam.IsParamArray)
End Sub)
End Sub
<Fact()>
Public Sub BC30307ERR_OverrideWithDefault2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Module mod30307
Class Class1
Overridable Sub Scen1(Optional ByVal x As String = "bob")
End Sub
Overridable Sub Scen2(Optional ByVal x As Object = "bob")
End Sub
Overridable Function Scen3(Optional ByVal x As Integer = 3)
End Function
Overridable Function Scen4(Optional ByVal x As Integer = 3)
End Function
End Class
Class class2
Inherits Class1
'COMPILEERROR: BC30307, "Scen1"
Overrides Sub Scen1(Optional ByVal x As String = "BOB")
End Sub
'COMPILEERROR: BC30307, "Scen2"
Overrides Sub Scen2(Optional ByVal x As Object = "BOB")
End Sub
Overrides Function Scen3(Optional ByVal x As Integer = 2 + 1)
End Function
'COMPILEERROR: BC30307, "Scen4"
Overrides Function Scen4(Optional ByVal x As Integer = 4)
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30307: 'Public Overrides Sub Scen1([x As String = "BOB"])' cannot override 'Public Overridable Sub Scen1([x As String = "bob"])' because they differ by the default values of optional parameters.
Overrides Sub Scen1(Optional ByVal x As String = "BOB")
~~~~~
BC30307: 'Public Overrides Sub Scen2([x As Object = "BOB"])' cannot override 'Public Overridable Sub Scen2([x As Object = "bob"])' because they differ by the default values of optional parameters.
Overrides Sub Scen2(Optional ByVal x As Object = "BOB")
~~~~~
BC30307: 'Public Overrides Function Scen4([x As Integer = 4]) As Object' cannot override 'Public Overridable Function Scen4([x As Integer = 3]) As Object' because they differ by the default values of optional parameters.
Overrides Function Scen4(Optional ByVal x As Integer = 4)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30308ERR_OverrideWithOptional2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverrideWithOptional2">
<file name="a.vb"><![CDATA[
Module mod30308
Class Class1
Overridable Sub Scen1(Optional ByVal x As String = "bob")
End Sub
Overridable Sub Scen2(Optional ByVal x As Object = "bob")
End Sub
Overridable Function Scen3(Optional ByVal x As Integer = 3)
End Function
Overridable Function Scen4(Optional ByVal x As Integer = 3)
End Function
End Class
Class class2
Inherits Class1
'COMPILEERROR: BC30308, "Scen1"
Overrides Sub Scen1(ByVal x As String)
End Sub
'COMPILEERROR: BC30308, "Scen2"
Overrides Sub Scen2(ByVal x As Object)
End Sub
Overrides Function Scen3(ByVal x As Integer)
End Function
'COMPILEERROR: BC30308, "Scen4"
Overrides Function Scen4(ByVal x As Integer)
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30308: 'Public Overrides Sub Scen1(x As String)' cannot override 'Public Overridable Sub Scen1([x As String = "bob"])' because they differ by optional parameters.
Overrides Sub Scen1(ByVal x As String)
~~~~~
BC30308: 'Public Overrides Sub Scen2(x As Object)' cannot override 'Public Overridable Sub Scen2([x As Object = "bob"])' because they differ by optional parameters.
Overrides Sub Scen2(ByVal x As Object)
~~~~~
BC30308: 'Public Overrides Function Scen3(x As Integer) As Object' cannot override 'Public Overridable Function Scen3([x As Integer = 3]) As Object' because they differ by optional parameters.
Overrides Function Scen3(ByVal x As Integer)
~~~~~
BC30308: 'Public Overrides Function Scen4(x As Integer) As Object' cannot override 'Public Overridable Function Scen4([x As Integer = 3]) As Object' because they differ by optional parameters.
Overrides Function Scen4(ByVal x As Integer)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30345ERR_OverloadWithByref2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithByref2">
<file name="a.vb"><![CDATA[
Public Class Cls30345
Public overloads Sub Goo1(ByVal x as Integer) ' 1
End Sub
Public overloads Sub Goo1(ByRef x as Integer) ' 2
End Sub
Public overloads Function Goo2(ByVal x as Integer) as Integer' 1
return 1
End Function
Public overloads Function Goo2(ByRef x as Integer) as Decimal' 2
return 2.2
End Function
Public Shared Sub Main()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30345: 'Public Overloads Sub Goo1(x As Integer)' and 'Public Overloads Sub Goo1(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Public overloads Sub Goo1(ByVal x as Integer) ' 1
~~~~
BC30301: 'Public Overloads Function Goo2(x As Integer) As Integer' and 'Public Overloads Function Goo2(ByRef x As Integer) As Decimal' cannot overload each other because they differ only by return types.
Public overloads Function Goo2(ByVal x as Integer) as Integer' 1
~~~~
BC30345: 'Public Overloads Function Goo2(x As Integer) As Integer' and 'Public Overloads Function Goo2(ByRef x As Integer) As Decimal' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Public overloads Function Goo2(ByVal x as Integer) as Integer' 1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30345ERR_OverloadWithByref2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithByref2">
<file name="a.vb"><![CDATA[
Public Class Cls30345
'COMPILEERROR: BC30345, "Goo"
Partial Private Sub Goo(Optional ByVal x As Integer = 2)
End Sub
Sub Goo(Optional ByRef x As Integer = 2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30345: 'Private Sub Goo([x As Integer = 2])' and 'Public Sub Goo([ByRef x As Integer = 2])' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Partial Private Sub Goo(Optional ByVal x As Integer = 2)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30354ERR_InheritsFromNonInterface()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InheritsFromNonInterface">
<file name="a.vb"><![CDATA[
Module M1
Interface I1
Inherits System.Enum
End Interface
Interface I2
Inherits Scen1
End Interface
Interface I3
Inherits System.Exception
End Interface
NotInheritable Class Scen1
End Class
END Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30354: Interface can inherit only from another interface.
Inherits System.Enum
~~~~~~~~~~~
BC30354: Interface can inherit only from another interface.
Inherits Scen1
~~~~~
BC30354: Interface can inherit only from another interface.
Inherits System.Exception
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30359ERR_DuplicateDefaultProps1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
Default Property P(o)
ReadOnly Property Q(o)
Default WriteOnly Property R(o) ' BC30359
Default Property P(x, y)
Default Property Q(x, y) ' BC30359
Property R(x, y)
End Interface
Class C
Default Property P(o)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
ReadOnly Property Q(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property R(o) ' BC30359
Set(value)
End Set
End Property
Default Property P(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Default Property Q(x, y) ' BC30359
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
Structure S
Default Property P(o)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
ReadOnly Property Q(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property R(o) ' BC30359
Set(value)
End Set
End Property
Default Property P(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Default Property Q(x, y) ' BC30359
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
compilation1.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC30359: 'Default' can be applied to only one property name in a interface.
Default WriteOnly Property R(o) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a interface.
Default Property Q(x, y) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a class.
Default WriteOnly Property R(o) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a class.
Default Property Q(x, y) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a structure.
Default WriteOnly Property R(o) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a structure.
Default Property Q(x, y) ' BC30359
~
]]></errors>)
End Sub
' Property names with different case.
<Fact>
Public Sub BC30359ERR_DuplicateDefaultProps1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
Default ReadOnly Property P(o)
Default WriteOnly Property p(x, y)
End Interface
Class C
Default ReadOnly Property q(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property Q(x, y)
Set(value)
End Set
End Property
End Class
Structure S
Default ReadOnly Property R(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property r(x, y)
Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
compilation1.AssertNoErrors()
End Sub
<Fact>
Public Sub BC30361ERR_DefaultMissingFromProperty2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DefaultMissingFromProperty2">
<file name="a.vb"><![CDATA[
MustInherit Class C
Default Overridable Overloads ReadOnly Property P(x, y)
Get
Return Nothing
End Get
End Property
MustOverride Overloads Property P
End Class
Interface I
Overloads WriteOnly Property Q(o)
Overloads ReadOnly Property Q
Default Overloads Property Q(x, y)
End Interface
Structure S
ReadOnly Property R(x)
Get
Return Nothing
End Get
End Property
Default ReadOnly Property R(x, y)
Get
Return Nothing
End Get
End Property
Default ReadOnly Property R(x, y, z)
Get
Return Nothing
End Get
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30361: 'Public Overridable Overloads ReadOnly Default Property P(x As Object, y As Object) As Object' and 'Public MustOverride Overloads Property P As Object' cannot overload each other because only one is declared 'Default'.
MustOverride Overloads Property P
~
BC30361: 'Default Property Q(x As Object, y As Object) As Object' and 'WriteOnly Property Q(o As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads WriteOnly Property Q(o)
~
BC30361: 'Default Property Q(x As Object, y As Object) As Object' and 'ReadOnly Property Q As Object' cannot overload each other because only one is declared 'Default'.
Overloads ReadOnly Property Q
~
BC30361: 'Public ReadOnly Default Property R(x As Object, y As Object) As Object' and 'Public ReadOnly Property R(x As Object) As Object' cannot overload each other because only one is declared 'Default'.
ReadOnly Property R(x)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Property names with different case.
<Fact>
Public Sub BC30361ERR_DefaultMissingFromProperty2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DefaultMissingFromProperty2">
<file name="a.vb"><![CDATA[
Interface I
Default Overloads ReadOnly Property P(o)
Overloads WriteOnly Property p(x, y)
End Interface
Class C
Overloads ReadOnly Property q(o)
Get
Return Nothing
End Get
End Property
Default Overloads WriteOnly Property Q(x, y)
Set(value)
End Set
End Property
End Class
Structure S
Overloads ReadOnly Property R(o)
Get
Return Nothing
End Get
End Property
Default Overloads WriteOnly Property r(x, y)
Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
compilation1.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC30361: 'ReadOnly Default Property P(o As Object) As Object' and 'WriteOnly Property p(x As Object, y As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads WriteOnly Property p(x, y)
~
BC30361: 'Public Overloads WriteOnly Default Property Q(x As Object, y As Object) As Object' and 'Public Overloads ReadOnly Property q(o As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads ReadOnly Property q(o)
~
BC30361: 'Public Overloads WriteOnly Default Property r(x As Object, y As Object) As Object' and 'Public Overloads ReadOnly Property R(o As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads ReadOnly Property R(o)
~
]]></errors>)
End Sub
<Fact>
Public Sub BC30362ERR_OverridingPropertyKind2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverridingPropertyKind2">
<file name="a.vb"><![CDATA[
Public Class Class1
Dim xprop11, xprop12
Public Overridable ReadOnly Property prop10()
Get
Return "Class1 prop10"
End Get
End Property
Public Overridable WriteOnly Property prop11()
Set(ByVal Value)
xprop11 = Value
End Set
End Property
Public Overridable Property prop12()
Get
prop12 = xprop12
End Get
Set(ByVal Value)
xprop12 = Value
End Set
End Property
End Class
Public Class Class2
Inherits Class1
'COMPILEERROR: BC30362, "prop10"
Overrides WriteOnly Property prop10()
Set(ByVal Value)
End Set
End Property
'COMPILEERROR: BC30362, "prop11"
Overrides ReadOnly Property prop11()
Get
End Get
End Property
'COMPILEERROR: BC30362, "prop12"
Overrides ReadOnly Property prop12()
Get
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30362: 'Public Overrides WriteOnly Property prop10 As Object' cannot override 'Public Overridable ReadOnly Property prop10 As Object' because they differ by 'ReadOnly' or 'WriteOnly'.
Overrides WriteOnly Property prop10()
~~~~~~
BC30362: 'Public Overrides ReadOnly Property prop11 As Object' cannot override 'Public Overridable WriteOnly Property prop11 As Object' because they differ by 'ReadOnly' or 'WriteOnly'.
Overrides ReadOnly Property prop11()
~~~~~~
BC30362: 'Public Overrides ReadOnly Property prop12 As Object' cannot override 'Public Overridable Property prop12 As Object' because they differ by 'ReadOnly' or 'WriteOnly'.
Overrides ReadOnly Property prop12()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30362ERR_OverridingPropertyKind3()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="OverridingPropertyKind3">
<file name="a.vb"><![CDATA[
Class D3
Inherits D2
Public Overrides Property P_rw_rw_r As Integer
Get
Return MyBase.P_rw_rw_r
End Get
Set(value As Integer)
MyBase.P_rw_r_w = value
End Set
End Property
Public Overrides Property P_rw_rw_w As Integer
Get
Return MyBase.P_rw_rw_r
End Get
Set(value As Integer)
MyBase.P_rw_rw_w = value
End Set
End Property
End Class
]]></file>
</compilation>, ClassesWithReadWriteProperties)
Dim expectedErrors1 = <errors><![CDATA[
BC30362: 'Public Overrides Property P_rw_rw_r As Integer' cannot override 'Public Overrides ReadOnly Property P_rw_rw_r As Integer' because they differ by 'ReadOnly' or 'WriteOnly'.
Public Overrides Property P_rw_rw_r As Integer
~~~~~~~~~
BC30362: 'Public Overrides Property P_rw_rw_w As Integer' cannot override 'Public Overrides WriteOnly Property P_rw_rw_w As Integer' because they differ by 'ReadOnly' or 'WriteOnly'.
Public Overrides Property P_rw_rw_w As Integer
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30364ERR_BadFlagsOnNew1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadFlagsOnNew1">
<file name="a.vb"><![CDATA[
Class S1
overridable SUB NEW()
end sub
End Class
Class S2
Shadows SUB NEW()
end sub
End Class
Class S3
MustOverride SUB NEW()
End Class
Class S4
notoverridable SUB NEW()
end sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30364: 'Sub New' cannot be declared 'overridable'.
overridable SUB NEW()
~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'Shadows'.
Shadows SUB NEW()
~~~~~~~
BC30364: 'Sub New' cannot be declared 'MustOverride'.
MustOverride SUB NEW()
~~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'notoverridable'.
notoverridable SUB NEW()
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30366ERR_OverloadingPropertyKind2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadingPropertyKind2">
<file name="a.vb"><![CDATA[
Class Cls30366(Of T)
' COMPILEERROR: BC30366, "P1"
ReadOnly Property P1() As T
Get
End Get
End Property
' COMPILEERROR: BC30366, "P2"
WriteOnly Property P2() As T
Set(ByVal Value As T)
End Set
End Property
Default Property P3(ByVal i As Integer) As T
Get
End Get
Set(ByVal Value As T)
End Set
End Property
End Class
Partial Class Cls30366(Of T)
WriteOnly Property P1() As T
Set(ByVal Value As T)
End Set
End Property
ReadOnly Property P2() As T
Get
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30366: 'Public ReadOnly Property P1 As T' and 'Public WriteOnly Property P1 As T' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
ReadOnly Property P1() As T
~~
BC30366: 'Public WriteOnly Property P2 As T' and 'Public ReadOnly Property P2 As T' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
WriteOnly Property P2() As T
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30368ERR_OverloadWithArrayVsParamArray2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithArrayVsParamArray2">
<file name="a.vb"><![CDATA[
Class Cls30368_1(Of T)
Sub goo(ByVal p() As String)
End Sub
Sub goo(ByVal ParamArray v() As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30368: 'Public Sub goo(p As String())' and 'Public Sub goo(ParamArray v As String())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Sub goo(ByVal p() As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30368ERR_OverloadWithArrayVsParamArray2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithArrayVsParamArray2">
<file name="a.vb"><![CDATA[
Class Cls30368_1(Of T)
Sub goo(ByVal p() As String)
End Sub
Sub goo(ByVal ParamArray v() As String)
End Sub
End Class
Class Cls30368(Of T)
Overloads Property Goo1(ByVal x()) As String
Get
Goo1 = "get: VariantArray"
End Get
Set(ByVal Value As String)
End Set
End Property
Overloads Property Goo1(ByVal ParamArray x()) As String
Get
Goo1 = "get: ParamArray"
End Get
Set(ByVal Value As String)
End Set
End Property
Overloads Property Goo2(ByVal x()) As String
Get
Goo2 = "get: FixedArray"
End Get
Set(ByVal Value As String)
End Set
End Property
Overloads Property Goo2(ByVal ParamArray x()) As String
Get
Goo2 = "get: ParamArray"
End Get
Set(ByVal Value As String)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30368: 'Public Sub goo(p As String())' and 'Public Sub goo(ParamArray v As String())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Sub goo(ByVal p() As String)
~~~
BC30368: 'Public Overloads Property Goo1(x As Object()) As String' and 'Public Overloads Property Goo1(ParamArray x As Object()) As String' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Overloads Property Goo1(ByVal x()) As String
~~~~
BC30368: 'Public Overloads Property Goo2(x As Object()) As String' and 'Public Overloads Property Goo2(ParamArray x As Object()) As String' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Overloads Property Goo2(ByVal x()) As String
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30371ERR_ModuleAsType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
End Module
Module M2
End Module
Module M3
End Module
Interface IA(Of T As M1)
End Interface
Interface IB
Sub M(Of T As M2)()
End Interface
Interface IC(Of T)
End Interface
Class C
Shared Sub M(o As IC(Of M3))
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30371: Module 'M1' cannot be used as a type.
Interface IA(Of T As M1)
~~
BC30371: Module 'M2' cannot be used as a type.
Sub M(Of T As M2)()
~~
BC30371: Module 'M3' cannot be used as a type.
Shared Sub M(o As IC(Of M3))
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30371ERR_ModuleAsType1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
Class C1
Function goo As M1
Return Nothing
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30371: Module 'M1' cannot be used as a type.
Function goo As M1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30385ERR_BadDelegateFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadDelegateFlags1">
<file name="a.vb"><![CDATA[
Class C1
MustOverride Delegate Sub Del1()
NotOverridable Delegate Sub Del2()
Shared Delegate Sub Del3()
Overrides Delegate Sub Del4()
Overloads Delegate Sub Del5(ByRef y As Integer)
Partial Delegate Sub Del6()
Default Delegate Sub Del7()
ReadOnly Delegate Sub Del8()
WriteOnly Delegate Sub Del9()
MustInherit Delegate Sub Del10()
NotInheritable Delegate Sub Del11()
Widening Delegate Sub Del12()
Narrowing Delegate Sub Del13()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30385: 'MustOverride' is not valid on a Delegate declaration.
MustOverride Delegate Sub Del1()
~~~~~~~~~~~~
BC30385: 'NotOverridable' is not valid on a Delegate declaration.
NotOverridable Delegate Sub Del2()
~~~~~~~~~~~~~~
BC30385: 'Shared' is not valid on a Delegate declaration.
Shared Delegate Sub Del3()
~~~~~~
BC30385: 'Overrides' is not valid on a Delegate declaration.
Overrides Delegate Sub Del4()
~~~~~~~~~
BC30385: 'Overloads' is not valid on a Delegate declaration.
Overloads Delegate Sub Del5(ByRef y As Integer)
~~~~~~~~~
BC30385: 'Partial' is not valid on a Delegate declaration.
Partial Delegate Sub Del6()
~~~~~~~
BC30385: 'Default' is not valid on a Delegate declaration.
Default Delegate Sub Del7()
~~~~~~~
BC30385: 'ReadOnly' is not valid on a Delegate declaration.
ReadOnly Delegate Sub Del8()
~~~~~~~~
BC30385: 'WriteOnly' is not valid on a Delegate declaration.
WriteOnly Delegate Sub Del9()
~~~~~~~~~
BC30385: 'MustInherit' is not valid on a Delegate declaration.
MustInherit Delegate Sub Del10()
~~~~~~~~~~~
BC30385: 'NotInheritable' is not valid on a Delegate declaration.
NotInheritable Delegate Sub Del11()
~~~~~~~~~~~~~~
BC30385: 'Widening' is not valid on a Delegate declaration.
Widening Delegate Sub Del12()
~~~~~~~~
BC30385: 'Narrowing' is not valid on a Delegate declaration.
Narrowing Delegate Sub Del13()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538884")>
<Fact>
Public Sub BC30385ERR_BadDelegateFlags1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadDelegateFlags1">
<file name="a.vb"><![CDATA[
Structure S1
MustOverride Delegate Sub Del1()
NotOverridable Delegate Sub Del1()
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30385: 'MustOverride' is not valid on a Delegate declaration.
MustOverride Delegate Sub Del1()
~~~~~~~~~~~~
BC30385: 'NotOverridable' is not valid on a Delegate declaration.
NotOverridable Delegate Sub Del1()
~~~~~~~~~~~~~~
BC30179: delegate Class 'Del1' and delegate Class 'Del1' conflict in structure 'S1'.
NotOverridable Delegate Sub Del1()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30389ERR_InaccessibleSymbol2_AccessCheckCrossAssemblyDerived()
Dim other As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AccessCheckCrossAssemblyDerived1">
<file name="a.vb"><![CDATA[
Public Class C
Public Shared c_pub As Integer
Friend Shared c_int As Integer
Protected Shared c_pro As Integer
Protected Friend Shared c_intpro As Integer
Private Shared c_priv As Integer
End Class
Friend Class D
Public Shared d_pub As Integer
End Class
]]></file>
</compilation>)
CompilationUtils.AssertNoErrors(other)
Dim comp As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="AccessCheckCrossAssemblyDerived2">
<file name="a.vb"><![CDATA[
Public Class A
Inherits C
Public Sub m()
Dim aa As Integer = C.c_pub
Dim bb As Integer = C.c_int
Dim cc As Integer = C.c_pro
Dim dd As Integer = C.c_intpro
Dim ee As Integer = C.c_priv
Dim ff As Integer = D.d_pub
End Sub
End Class
]]></file>
</compilation>,
{New VisualBasicCompilationReference(other)})
'BC30389: 'C.c_int' is not accessible in this context because it is 'Friend'.
' Dim bb As Integer = C.c_int
' ~~~~~~~
'BC30389: 'C.c_priv' is not accessible in this context because it is 'Private'.
' Dim ee As Integer = C.c_priv
' ~~~~~~~~
'BC30389: 'D' is not accessible in this context because it is 'Friend'.
' Dim ff As Integer = D.d_pub
' ~
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleSymbol2, "C.c_int").WithArguments("C.c_int", "Friend"),
Diagnostic(ERRID.ERR_InaccessibleSymbol2, "C.c_priv").WithArguments("C.c_priv", "Private"),
Diagnostic(ERRID.ERR_InaccessibleSymbol2, "D").WithArguments("D", "Friend"))
End Sub
<Fact>
Public Sub BC30395ERR_BadRecordFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ERR_BadRecordFlags1">
<file name="a.vb"><![CDATA[
MustOverride Structure Del1
End Structure
NotOverridable Structure Del2
End Structure
Shared Structure Del3
End Structure
Overrides Structure Del4
End Structure
Overloads Structure Del5
End Structure
Partial Structure Del6
End Structure
Default Structure Del7
End Structure
ReadOnly Structure Del8
End Structure
WriteOnly Structure Del9
End Structure
Widening Structure Del12
End Structure
Narrowing Structure Del13
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30395: 'MustOverride' is not valid on a Structure declaration.
MustOverride Structure Del1
~~~~~~~~~~~~
BC30395: 'NotOverridable' is not valid on a Structure declaration.
NotOverridable Structure Del2
~~~~~~~~~~~~~~
BC30395: 'Shared' is not valid on a Structure declaration.
Shared Structure Del3
~~~~~~
BC30395: 'Overrides' is not valid on a Structure declaration.
Overrides Structure Del4
~~~~~~~~~
BC30395: 'Overloads' is not valid on a Structure declaration.
Overloads Structure Del5
~~~~~~~~~
BC30395: 'Default' is not valid on a Structure declaration.
Default Structure Del7
~~~~~~~
BC30395: 'ReadOnly' is not valid on a Structure declaration.
ReadOnly Structure Del8
~~~~~~~~
BC30395: 'WriteOnly' is not valid on a Structure declaration.
WriteOnly Structure Del9
~~~~~~~~~
BC30395: 'Widening' is not valid on a Structure declaration.
Widening Structure Del12
~~~~~~~~
BC30395: 'Narrowing' is not valid on a Structure declaration.
Narrowing Structure Del13
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30396ERR_BadEnumFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadEnumFlags1">
<file name="a.vb"><![CDATA[
MustOverride enum Del1
male
End enum
NotOverridable enum Del2
male
End enum
Shared enum Del3
male
End enum
Overrides enum Del4
male
End enum
Overloads enum Del5
male
End enum
Partial enum Del6
male
End enum
Default enum Del7
male
End enum
ReadOnly enum Del8
male
End enum
WriteOnly enum Del9
male
End enum
Widening enum Del12
male
End enum
Narrowing enum Del13
male
End enum
MustInherit Enum Del14
male
End Enum
NotInheritable Enum Del15
male
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30396: 'MustOverride' is not valid on an Enum declaration.
MustOverride enum Del1
~~~~~~~~~~~~
BC30396: 'NotOverridable' is not valid on an Enum declaration.
NotOverridable enum Del2
~~~~~~~~~~~~~~
BC30396: 'Shared' is not valid on an Enum declaration.
Shared enum Del3
~~~~~~
BC30396: 'Overrides' is not valid on an Enum declaration.
Overrides enum Del4
~~~~~~~~~
BC30396: 'Overloads' is not valid on an Enum declaration.
Overloads enum Del5
~~~~~~~~~
BC30396: 'Partial' is not valid on an Enum declaration.
Partial enum Del6
~~~~~~~
BC30396: 'Default' is not valid on an Enum declaration.
Default enum Del7
~~~~~~~
BC30396: 'ReadOnly' is not valid on an Enum declaration.
ReadOnly enum Del8
~~~~~~~~
BC30396: 'WriteOnly' is not valid on an Enum declaration.
WriteOnly enum Del9
~~~~~~~~~
BC30396: 'Widening' is not valid on an Enum declaration.
Widening enum Del12
~~~~~~~~
BC30396: 'Narrowing' is not valid on an Enum declaration.
Narrowing enum Del13
~~~~~~~~~
BC30396: 'MustInherit' is not valid on an Enum declaration.
MustInherit Enum Del14
~~~~~~~~~~~
BC30396: 'NotInheritable' is not valid on an Enum declaration.
NotInheritable Enum Del15
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30397ERR_BadInterfaceFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceFlags1">
<file name="a.vb"><![CDATA[
Class C1
MustOverride Interface Del1
End Interface
NotOverridable Interface Del2
End Interface
Shared Interface Del3
End Interface
Overrides Interface Del4
End Interface
Overloads Interface Del5
End Interface
Default Interface Del7
End Interface
ReadOnly Interface Del8
End Interface
WriteOnly Interface Del9
End Interface
Widening Interface Del12
End Interface
Narrowing Interface Del13
End Interface
MustInherit Interface Del14
End Interface
NotInheritable Interface Del15
End Interface
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30397: 'MustOverride' is not valid on an Interface declaration.
MustOverride Interface Del1
~~~~~~~~~~~~
BC30397: 'NotOverridable' is not valid on an Interface declaration.
NotOverridable Interface Del2
~~~~~~~~~~~~~~
BC30397: 'Shared' is not valid on an Interface declaration.
Shared Interface Del3
~~~~~~
BC30397: 'Overrides' is not valid on an Interface declaration.
Overrides Interface Del4
~~~~~~~~~
BC30397: 'Overloads' is not valid on an Interface declaration.
Overloads Interface Del5
~~~~~~~~~
BC30397: 'Default' is not valid on an Interface declaration.
Default Interface Del7
~~~~~~~
BC30397: 'ReadOnly' is not valid on an Interface declaration.
ReadOnly Interface Del8
~~~~~~~~
BC30397: 'WriteOnly' is not valid on an Interface declaration.
WriteOnly Interface Del9
~~~~~~~~~
BC30397: 'Widening' is not valid on an Interface declaration.
Widening Interface Del12
~~~~~~~~
BC30397: 'Narrowing' is not valid on an Interface declaration.
Narrowing Interface Del13
~~~~~~~~~
BC30397: 'MustInherit' is not valid on an Interface declaration.
MustInherit Interface Del14
~~~~~~~~~~~
BC30397: 'NotInheritable' is not valid on an Interface declaration.
NotInheritable Interface Del15
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30398ERR_OverrideWithByref2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverrideWithByref2">
<file name="a.vb"><![CDATA[
Module mod30398
Class Class1
Overridable Sub Scen1(ByRef x As String)
End Sub
Overridable Sub Scen2(ByRef x As Object)
End Sub
Overridable Function Scen3(ByRef x As Integer)
End Function
Overridable Function Scen4(ByRef x As Integer)
End Function
End Class
Class class2
Inherits Class1
'COMPILEERROR: BC30398, "Scen1"
Overrides Sub Scen1(ByVal x As String)
End Sub
'COMPILEERROR: BC30398, "Scen2"
Overrides Sub Scen2(ByVal x As Object)
End Sub
Overrides Function Scen3(ByVal x As Integer)
End Function
'COMPILEERROR: BC30398, "Scen4"
Overrides Function Scen4(ByVal x As Integer)
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30398: 'Public Overrides Sub Scen1(x As String)' cannot override 'Public Overridable Sub Scen1(ByRef x As String)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Sub Scen1(ByVal x As String)
~~~~~
BC30398: 'Public Overrides Sub Scen2(x As Object)' cannot override 'Public Overridable Sub Scen2(ByRef x As Object)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Sub Scen2(ByVal x As Object)
~~~~~
BC30398: 'Public Overrides Function Scen3(x As Integer) As Object' cannot override 'Public Overridable Function Scen3(ByRef x As Integer) As Object' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Function Scen3(ByVal x As Integer)
~~~~~
BC30398: 'Public Overrides Function Scen4(x As Integer) As Object' cannot override 'Public Overridable Function Scen4(ByRef x As Integer) As Object' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Function Scen4(ByVal x As Integer)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30401ERR_IdentNotMemberOfInterface4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IdentNotMemberOfInterface4">
<file name="a.vb"><![CDATA[
Interface IA
Function F() As Integer
Property P As Object
End Interface
Interface IB
End Interface
Class A
Implements IA
Public Function F(o As Object) As Integer Implements IA.F
Return Nothing
End Function
Public Property P As Boolean Implements IA.P
End Class
Class B
Implements IB
Public Function F() As Integer Implements IB.F
Return Nothing
End Function
Public Property P As Boolean Implements IB.P
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'A' must implement 'Function F() As Integer' for interface 'IA'.
Implements IA
~~
BC30149: Class 'A' must implement 'Property P As Object' for interface 'IA'.
Implements IA
~~
BC30401: 'F' cannot implement 'F' because there is no matching function on interface 'IA'.
Public Function F(o As Object) As Integer Implements IA.F
~~~~
BC30401: 'P' cannot implement 'P' because there is no matching property on interface 'IA'.
Public Property P As Boolean Implements IA.P
~~~~
BC30401: 'F' cannot implement 'F' because there is no matching function on interface 'IB'.
Public Function F() As Integer Implements IB.F
~~~~
BC30401: 'P' cannot implement 'P' because there is no matching property on interface 'IB'.
Public Property P As Boolean Implements IB.P
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30412ERR_WithEventsRequiresClass()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="WithEventsRequiresClass">
<file name="a.vb"><![CDATA[
Class ClsTest30412
'COMPILEERROR: BC30412, "Field003WithEvents"
Public WithEvents Field003WithEvents = {1, 2, 3}
End Class
Class ClsTest30412_2
'COMPILEERROR: BC30412, "Field002WithEvents"
Public WithEvents Field002WithEvents = New List(Of Integer) From {1, 2, 3}
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30412: 'WithEvents' variables must have an 'As' clause.
Public WithEvents Field003WithEvents = {1, 2, 3}
~~~~~~~~~~~~~~~~~~
BC30412: 'WithEvents' variables must have an 'As' clause.
Public WithEvents Field002WithEvents = New List(Of Integer) From {1, 2, 3}
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30413ERR_WithEventsAsStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="WithEventsAsStruct">
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Structure S
End Structure
Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U)
WithEvents _i As I
WithEvents _a As A
WithEvents _s As S
WithEvents _1 As T1
WithEvents _2 As T2
WithEvents _3 As T3
WithEvents _4 As T4
WithEvents _5 As T5
WithEvents _6 As T6
WithEvents _7 As T7
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _s As S
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _1 As T1
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _3 As T3
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _4 As T4
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _5 As T5
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _7 As T7
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30433ERR_ModuleCantUseMethodSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Protected Sub M()
End Sub
Shared Sub N()
End Sub
MustOverride Sub O()
Overridable Sub P()
End Sub
Overrides Sub Q()
End Sub
Shadows Sub R()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30433: Methods in a Module cannot be declared 'Protected'.
Protected Sub M()
~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Shared'.
Shared Sub N()
~~~~~~
BC30433: Methods in a Module cannot be declared 'MustOverride'.
MustOverride Sub O()
~~~~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Overridable'.
Overridable Sub P()
~~~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Overrides'.
Overrides Sub Q()
~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Shadows'.
Shadows Sub R()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30434ERR_ModuleCantUseEventSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseEventSpecifier1">
<file name="a.vb"><![CDATA[
Module Shdmod
'COMPILEERROR: BC30434, "Shadows"
Shadows Event testx()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30434: Events in a Module cannot be declared 'Shadows'.
Shadows Event testx()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure S
Protected F
Protected Property P
Property Q
Protected Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R
Get
Return Nothing
End Get
Protected Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected F
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Property P
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Get
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Set(value)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure S
Protected Friend F
Protected Friend Property P
Property Q
Protected Friend Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R
Get
Return Nothing
End Get
Protected Friend Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend F
~~~~~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Property P
~~~~~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Get
~~~~~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Set(value)
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure S
Property P
Protected Get
Return Nothing
End Get
Protected Friend Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Get
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Set(value)
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(531467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531467")>
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Structure ms
Dim s As Integer
Public Overridable Property p1()
Get
Return Nothing
End Get
Friend Set(ByVal Value)
End Set
End Property
Public NotOverridable Property p2()
Get
Return Nothing
End Get
Friend Set(ByVal Value)
End Set
End Property
Public MustOverride Property p3()
Public Overridable Sub T1()
End Sub
Public NotOverridable Sub T2()
End Sub
Public MustOverride Sub T3()
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Overridable'.
Public Overridable Property p1()
~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'NotOverridable'.
Public NotOverridable Property p2()
~~~~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Public NotOverridable Property p2()
~~
BC30435: Members in a Structure cannot be declared 'MustOverride'.
Public MustOverride Property p3()
~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Overridable'.
Public Overridable Sub T1()
~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'NotOverridable'.
Public NotOverridable Sub T2()
~~~~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Public NotOverridable Sub T2()
~~
BC30435: Members in a Structure cannot be declared 'MustOverride'.
Public MustOverride Sub T3()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30436ERR_ModuleCantUseMemberSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseMemberSpecifier1">
<file name="a.vb"><![CDATA[
Module m1
Protected Enum myenum As Integer
one
End Enum
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30735: Type in a Module cannot be declared 'Protected'.
Protected Enum myenum As Integer
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30437ERR_InvalidOverrideDueToReturn2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class base(Of t)
'COMPILEERROR: BC30437, "toString"
Overrides Function tostring() As t
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30437: 'Public Overrides Function tostring() As t' cannot override 'Public Overridable Overloads Function ToString() As String' because they differ by their return types.
Overrides Function tostring() As t
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30438ERR_ConstantWithNoValue()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Namespace NS30438
Class c1
'COMPILEERROR: BC30438,"c1"
Const c1 As UInt16
End Class
Structure s1
'COMPILEERROR: BC30438,"c1"
Const c1 As UInt16
End Structure
Friend Module USign_001mod
'COMPILEERROR: BC30438,"c1"
Const c1 As UInt16
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30438: Constants must have a value.
Const c1 As UInt16
~~
BC30438: Constants must have a value.
Const c1 As UInt16
~~
BC30438: Constants must have a value.
Const c1 As UInt16
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(542127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542127")>
<Fact>
Public Sub BC30438ERR_ConstantWithNoValue02()
Dim source =
<compilation name="delegates">
<file name="a.vb"><![CDATA[
Option strict on
imports system
Class C1
Sub GOO()
'COMPILEERROR: BC30438
Const l6 As UInt16
Const l7 as new UInt16
End Sub
End Class
]]></file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected><![CDATA[
BC30438: Constants must have a value.
Const l6 As UInt16
~~
BC30438: Constants must have a value.
Const l7 as new UInt16
~~
BC30246: 'new' is not valid on a local constant declaration.
Const l7 as new UInt16
~~~
]]></expected>)
End Sub
<Fact>
Public Sub BC30443ERR_DuplicatePropertyGet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicatePropertyGet">
<file name="a.vb"><![CDATA[
Class C
Property P
Get
Return Nothing
End Get
Get
Return Nothing
End Get
Set
End Set
Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30443: 'Get' is already declared.
Get
~~~
BC30443: 'Get' is already declared.
Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30444ERR_DuplicatePropertySet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicatePropertySet">
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P
Set
End Set
Set
End Set
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30444: 'Set' is already declared.
Set
~~~
BC30444: 'Set' is already declared.
Set
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' <Fact()>
' Public Sub BC30445ERR_ConstAggregate()
' Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib(
'<compilation name="DuplicatePropertySet">
' <file name="a.vb"><![CDATA[
' Module Constant
' Const d() As Long = {1, 2}, e() As Long = {1, 2}
' Sub main()
' End Sub
' End Module
' ]]></file>
'</compilation>)
' Dim expectedErrors1 = <errors><![CDATA[
' BC30445: 'Set' is already declared.
' Set(ByRef value)
' ~~~~~~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
' End Sub
<Fact>
Public Sub BC30461ERR_BadClassFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadClassFlags1">
<file name="a.vb"><![CDATA[
NotOverridable class C1
End class
Shared class C2
End class
Overrides class C3
End class
Overloads class C4
End class
Partial class C5
End class
Default class C6
End class
ReadOnly class C7
End class
WriteOnly class C8
End class
Widening class C9
End class
Narrowing class C10
End class
MustInherit class C11
End class
NotInheritable class C12
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30461: Classes cannot be declared 'NotOverridable'.
NotOverridable class C1
~~~~~~~~~~~~~~
BC30461: Classes cannot be declared 'Shared'.
Shared class C2
~~~~~~
BC30461: Classes cannot be declared 'Overrides'.
Overrides class C3
~~~~~~~~~
BC30461: Classes cannot be declared 'Overloads'.
Overloads class C4
~~~~~~~~~
BC30461: Classes cannot be declared 'Default'.
Default class C6
~~~~~~~
BC30461: Classes cannot be declared 'ReadOnly'.
ReadOnly class C7
~~~~~~~~
BC30461: Classes cannot be declared 'WriteOnly'.
WriteOnly class C8
~~~~~~~~~
BC30461: Classes cannot be declared 'Widening'.
Widening class C9
~~~~~~~~
BC30461: Classes cannot be declared 'Narrowing'.
Narrowing class C10
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30467ERR_NonNamespaceOrClassOnImport2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicatePropertySet">
<file name="a.vb"><![CDATA[
'COMPILEERROR: BC30467, "ns1.intfc1"
Imports ns1.Intfc1
'COMPILEERROR: BC30467, "ns1.intfc2(Of String)"
Imports ns1.Intfc2(Of String)
Namespace ns1
Public Interface Intfc1
Sub Intfc1goo()
End Interface
Public Interface Intfc2(Of t)
Inherits Intfc1
Sub intfc2goo()
End Interface
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30467: 'Intfc1' for the Imports 'Intfc1' does not refer to a Namespace, Class, Structure, Enum or Module.
Imports ns1.Intfc1
~~~~~~~~~~
BC30467: 'Intfc2' for the Imports 'Intfc2(Of String)' does not refer to a Namespace, Class, Structure, Enum or Module.
Imports ns1.Intfc2(Of String)
~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30468ERR_TypecharNotallowed()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="TypecharNotallowed">
<file name="a.vb"><![CDATA[
Module M1
Function scen1() as System.Datetime@
End Function
End Module
Structure S1
Function scen1() as System.sTRING#
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30468: Type declaration characters are not valid in this context.
Function scen1() as System.Datetime@
~~~~~~~~~
BC30468: Type declaration characters are not valid in this context.
Function scen1() as System.sTRING#
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30476ERR_EventSourceIsArray()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventSourceIsArray">
<file name="a.vb"><![CDATA[
Public Class Class1
Class Class2
Event Goo()
End Class
'COMPILEERROR: BC30591, "h(3)",BC30476, "Class2"
Dim WithEvents h(3) As Class2
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30476: 'WithEvents' variables cannot be typed as arrays.
Dim WithEvents h(3) As Class2
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30479ERR_SharedConstructorWithParams()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedConstructorWithParams">
<file name="a.vb"><![CDATA[
Structure Struct1
Shared Sub new(ByVal x As Integer)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30479: Shared 'Sub New' cannot have any parameters.
Shared Sub new(ByVal x As Integer)
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30480ERR_SharedConstructorIllegalSpec1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedConstructorIllegalSpec1">
<file name="a.vb"><![CDATA[
Structure Struct1
Shared public Sub new()
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30480: Shared 'Sub New' cannot be declared 'public'.
Shared public Sub new()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30490ERR_BadFlagsWithDefault1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadFlagsWithDefault1">
<file name="a.vb"><![CDATA[
Class A
Default Private Property P(o)
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
Class B
Private ReadOnly Default Property Q(x, y)
Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30490: 'Default' cannot be combined with 'Private'.
Default Private Property P(o)
~~~~~~~
BC30490: 'Default' cannot be combined with 'Private'.
Private ReadOnly Default Property Q(x, y)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30497ERR_NewCannotHandleEvents()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NewCannotHandleEvents">
<file name="a.vb"><![CDATA[
Class Cla30497
'COMPILEERROR: BC30497, "New"
Sub New() Handles var1.event1
End Sub
End Class
Class Cla30497_1
'COMPILEERROR: BC30497, "New"
Shared Sub New() Handles var1.event1
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30497: 'Sub New' cannot handle events.
Sub New() Handles var1.event1
~~~
BC30497: 'Sub New' cannot handle events.
Shared Sub New() Handles var1.event1
~~~
]]></errors>
CompilationUtils.AssertTheseParseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30501ERR_BadFlagsOnSharedMeth1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class C
Shared NotOverridable Function F()
Return Nothing
End Function
Shared Overrides Function G()
Return Nothing
End Function
Overridable Shared Sub M()
End Sub
MustOverride Shared Sub N()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30501: 'Shared' cannot be combined with 'NotOverridable' on a method declaration.
Shared NotOverridable Function F()
~~~~~~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'Overrides' on a method declaration.
Shared Overrides Function G()
~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'Overridable' on a method declaration.
Overridable Shared Sub M()
~~~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'MustOverride' on a method declaration.
MustOverride Shared Sub N()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528324")>
<Fact>
Public Sub BC30501ERR_BadFlagsOnSharedMeth2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class A
Public Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
MustInherit Class B
Inherits A
Public Overrides Shared Sub G()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30501: 'Shared' cannot be combined with 'Overrides' on a method declaration.
Public Overrides Shared Sub G()
~~~~~~~~~
BC40005: sub 'G' shadows an overridable method in the base class 'A'. To override the base method, this method must be declared 'Overrides'.
Public Overrides Shared Sub G()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30502ERR_BadFlagsOnSharedProperty1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class C
NotOverridable Shared Property P
Overrides Shared Property Q
Overridable Shared Property R
Shared MustOverride Property S
Default Shared Property T(ByVal v)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30502: 'Shared' cannot be combined with 'NotOverridable' on a property declaration.
NotOverridable Shared Property P
~~~~~~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'Overrides' on a property declaration.
Overrides Shared Property Q
~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'Overridable' on a property declaration.
Overridable Shared Property R
~~~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'MustOverride' on a property declaration.
Shared MustOverride Property S
~~~~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'Default' on a property declaration.
Default Shared Property T(ByVal v)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30503ERR_BadFlagsOnStdModuleProperty1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadFlagsOnStdModuleProperty1">
<file name="a.vb"><![CDATA[
Module M
Protected Property P
Shared Property Q
MustOverride Property R
Overridable Property S
Overrides Property T
Shadows Property U
Default Property V(o)
Get
Return Nothing
End Get
Set
End Set
End Property
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30503: Properties in a Module cannot be declared 'Protected'.
Protected Property P
~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Shared'.
Shared Property Q
~~~~~~
BC30503: Properties in a Module cannot be declared 'MustOverride'.
MustOverride Property R
~~~~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Overridable'.
Overridable Property S
~~~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Overrides'.
Overrides Property T
~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Shadows'.
Shadows Property U
~~~~~~~
BC30503: Properties in a Module cannot be declared 'Default'.
Default Property V(o)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30505ERR_SharedOnProcThatImpl()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedOnProcThatImpl">
<file name="a.vb"><![CDATA[
Delegate Sub D()
Interface I
Sub M()
Property P As Object
Event E As D
End Interface
Class C
Implements I
Shared Sub M() Implements I.M
End Sub
Shared Property P As Object Implements I.P
Shared Event E() Implements I.E
End Class
]]></file>
</compilation>)
compilation1.AssertTheseDiagnostics(<errors><![CDATA[
BC30149: Class 'C' must implement 'Event E As D' for interface 'I'.
Implements I
~
BC30149: Class 'C' must implement 'Property P As Object' for interface 'I'.
Implements I
~
BC30149: Class 'C' must implement 'Sub M()' for interface 'I'.
Implements I
~
BC30505: Methods or events that implement interface members cannot be declared 'Shared'.
Shared Sub M() Implements I.M
~~~~~~
BC30505: Methods or events that implement interface members cannot be declared 'Shared'.
Shared Property P As Object Implements I.P
~~~~~~
BC30505: Methods or events that implement interface members cannot be declared 'Shared'.
Shared Event E() Implements I.E
~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30506ERR_NoWithEventsVarOnHandlesList()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoWithEventsVarOnHandlesList">
<file name="a.vb"><![CDATA[
Module mod30506
'COMPILEERROR: BC30506, "clsEventError1"
Sub scenario1() Handles clsEventError1.Event1
End Sub
'COMPILEERROR: BC30506, "I1"
Sub scenario2() Handles I1.goo
End Sub
'COMPILEERROR: BC30506, "button1"
Sub scenario3() Handles button1.click
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub scenario1() Handles clsEventError1.Event1
~~~~~~~~~~~~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub scenario2() Handles I1.goo
~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub scenario3() Handles button1.click
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub HandlesHiddenEvent()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoWithEventsVarOnHandlesList">
<file name="a.vb"><![CDATA[
Imports System
Class HasEvents
Event E1()
End Class
Class HasWithEvents
Public WithEvents WE0 As HasEvents
Public WithEvents WE1 As HasEvents
Public WithEvents WE2 As HasEvents
Public WithEvents _WE3 As HasEvents
End Class
Class HasWithEventsDerived
Inherits HasWithEvents
Overrides Property WE0() As HasEvents
Get
Return Nothing
End Get
Set(value As HasEvents)
End Set
End Property
Overloads Property WE1(x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Property WE2(x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Property WE3 As Integer
Shared Sub goo0() Handles WE0.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo1() Handles WE1.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo2() Handles WE2.E2
Console.WriteLine("handled2")
End Sub
Shared Sub goo3() Handles WE3.E3
Console.WriteLine("handled2")
End Sub
End Class
Class Program
Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30284: property 'WE0' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides Property WE0() As HasEvents
~~~
BC40004: property 'WE0' conflicts with WithEvents variable 'WE0' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Overrides Property WE0() As HasEvents
~~~
BC40004: property 'WE1' conflicts with WithEvents variable 'WE1' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Overloads Property WE1(x As Integer) As Integer
~~~
BC40004: property 'WE2' conflicts with WithEvents variable 'WE2' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Property WE2(x As Integer) As Integer
~~~
BC40012: property 'WE3' implicitly declares '_WE3', which conflicts with a member in the base class 'HasWithEvents', and so the property should be declared 'Shadows'.
Property WE3 As Integer
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo0() Handles WE0.E1
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo1() Handles WE1.E1
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo2() Handles WE2.E2
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo3() Handles WE3.E3
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub HandlesProperty001()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="HandlesProperty001">
<file name="a.vb"><![CDATA[
Imports System
Imports System.ComponentModel
Namespace Project1
Module m1
Public Sub main()
Dim c = New Sink
Dim s = New OuterClass
c.x = s
s.Test()
End Sub
End Module
Class EventSource
Public Event MyEvent()
Sub test()
RaiseEvent MyEvent()
End Sub
End Class
Class SomeBase
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Public Property SomePropertyInBase() As EventSource
Get
Console.Write("#Get#")
Return Nothing
End Get
Set(value As EventSource)
End Set
End Property
End Class
Class OuterClass
Inherits SomeBase
Private Shared SubObject As New EventSource
<DesignOnly(True)>
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Public Shared Property SomePropertyWrongValue() As EventSource
Get
Console.Write("#Get#")
Return SubObject
End Get
Set(value As EventSource)
End Set
End Property
Public Property SomePropertyNoAttribute() As EventSource
Get
Console.Write("#Get#")
Return SubObject
End Get
Set(value As EventSource)
End Set
End Property
Public Shared Property SomePropertyWriteOnly() As EventSource
Get
Console.Write("#Get#")
Return SubObject
End Get
Set(value As EventSource)
End Set
End Property
Sub Test()
SubObject.test()
End Sub
End Class
Class Sink
Public WithEvents x As OuterClass
Sub goo1() Handles x.SomePropertyWrongValue.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub goo2() Handles x.SomePropertyNoAttribute.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub goo3() Handles x.SomePropertyWriteonly.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub goo4() Handles x.SomePropertyInBase.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub test()
x.Test()
End Sub
Sub New()
x = New OuterClass
End Sub
End Class
'.....
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo1() Handles x.SomePropertyWrongValue.MyEvent
~~~~~~~~~~~~~~~~~~~~~~~~
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo2() Handles x.SomePropertyNoAttribute.MyEvent
~~~~~~~~~~~~~~~~~~~~~~~~~
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo3() Handles x.SomePropertyWriteonly.MyEvent
~~~~~~~~~~~~~~~~~~~~~~~
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo4() Handles x.SomePropertyInBase.MyEvent
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub WithEventsHides()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="WithEventsHides">
<file name="a.vb"><![CDATA[
Imports System
Class HasEvents
Event E1()
End Class
Class HasWithEvents
Public WithEvents WE0 As HasEvents
Public WithEvents WE1 As HasEvents
Public Property WE2 As HasEvents
Public Property WE3 As HasEvents
End Class
Class HasWithEventsDerived
Inherits HasWithEvents
Public WithEvents WE0 As HasEvents
' no warnings
Public Shadows WithEvents WE1 As HasEvents
Public WithEvents WE2 As HasEvents
' no warnings
Public Shadows WithEvents WE3 As HasEvents
Shared Sub goo0() Handles WE0.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo1() Handles WE1.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo2() Handles WE2.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo3() Handles WE3.E1
Console.WriteLine("handled2")
End Sub
End Class
Class Program
Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40004: WithEvents variable 'WE0' conflicts with WithEvents variable 'WE0' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Public WithEvents WE0 As HasEvents
~~~
BC40004: WithEvents variable 'WE2' conflicts with property 'WE2' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Public WithEvents WE2 As HasEvents
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub WithEventsOverloads()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="WithEventsOverloads">
<file name="a.vb"><![CDATA[
Imports System
Class HasEvents
Event E1()
End Class
Class HasWithEventsDerived
Public WithEvents _WE1 As HasEvents
Public Property WE0(x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Public Overloads Property WE2(x As Integer, y As Long) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Public WithEvents WE0 As HasEvents
Public Property WE1
Public WithEvents WE2 As HasEvents
End Class
Class Program
Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: WithEvents variable '_WE1' conflicts with a member implicitly declared for property 'WE1' in class 'HasWithEventsDerived'.
Public WithEvents _WE1 As HasEvents
~~~~
BC30260: 'WE0' is already declared as 'Public Property WE0(x As Integer) As Integer' in this class.
Public WithEvents WE0 As HasEvents
~~~
BC30260: 'WE2' is already declared as 'Public Overloads Property WE2(x As Integer, y As Long) As Integer' in this class.
Public WithEvents WE2 As HasEvents
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30508ERR_AccessMismatch6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Class A
Protected Class C
End Class
Protected Structure S
End Structure
Private Interface I
End Interface
Public F As I
Friend Function M() As C
Return Nothing
End Function
End Class
Public Class B
Inherits A
Public G As C
Friend ReadOnly H As S
Public Function N(x As C) As S
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'F' cannot expose type 'A.I' in namespace 'N' through class 'A'.
Public F As I
~
BC30508: 'M' cannot expose type 'A.C' in namespace 'N' through class 'A'.
Friend Function M() As C
~
BC30508: 'G' cannot expose type 'A.C' in namespace 'N' through class 'B'.
Public G As C
~
BC30508: 'H' cannot expose type 'A.S' in namespace 'N' through class 'B'.
Friend ReadOnly H As S
~
BC30508: 'x' cannot expose type 'A.C' in namespace 'N' through class 'B'.
Public Function N(x As C) As S
~
BC30508: 'N' cannot expose type 'A.S' in namespace 'N' through class 'B'.
Public Function N(x As C) As S
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30508ERR_AccessMismatch6_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace NS30508
Interface i1
End Interface
Interface i2
End Interface
Class C1(Of v)
Implements i1
End Class
Class c2
Implements i1
Implements i2
'COMPILEERROR: BC30508, "ProtectedClass"
Function fiveB(Of t As ProtectedClass)() As String
Return "In fiveB"
End Function
'COMPILEERROR: BC30508, "Privateclass"
Function fiveC(Of t As Privateclass)() As String
Return "In fiveC"
End Function
Protected Function fiveD(Of t As ProtectedClass)() As String
Return "In fiveB"
End Function
Private Function fiveE(Of t As Privateclass)() As String
Return "In fiveC"
End Function
Protected Class ProtectedClass
End Class
Private Class Privateclass
End Class
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'fiveB' cannot expose type 'c2.ProtectedClass' in namespace 'NS30508' through class 'c2'.
Function fiveB(Of t As ProtectedClass)() As String
~~~~~~~~~~~~~~
BC30508: 'fiveC' cannot expose type 'c2.Privateclass' in namespace 'NS30508' through class 'c2'.
Function fiveC(Of t As Privateclass)() As String
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30508ERR_AccessMismatch6_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Class A
Protected Class C
End Class
Protected Structure S
End Structure
Private Interface I
End Interface
Protected Enum E
A
End Enum
Property P As I
End Class
Public Class B
Inherits A
Property Q As C
Friend ReadOnly Property R(x As E) As S
Get
Return Nothing
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'P' cannot expose type 'A.I' in namespace 'N' through class 'A'.
Property P As I
~
BC30508: 'Q' cannot expose type 'A.C' in namespace 'N' through class 'B'.
Property Q As C
~
BC30508: 'x' cannot expose type 'A.E' in namespace 'N' through class 'B'.
Friend ReadOnly Property R(x As E) As S
~
BC30508: 'R' cannot expose type 'A.S' in namespace 'N' through class 'B'.
Friend ReadOnly Property R(x As E) As S
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528153")>
<Fact()>
Public Sub BC30508ERR_AccessMismatch6_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Class A
Protected Class B
End Class
Public Class C
Function F() As B
Return Nothing
End Function
Public Class D
Sub M(o As B)
End Sub
End Class
End Class
End Class
Public Class E
Inherits A
Function F() As B
Return Nothing
End Function
End Class
End Namespace
Public Class F
Inherits N.A
Sub M(o As B)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'F' cannot expose type 'A.B' in namespace 'N' through class 'C'.
Function F() As B
~
BC30508: 'o' cannot expose type 'A.B' in namespace 'N' through class 'D'.
Sub M(o As B)
~
BC30508: 'F' cannot expose type 'A.B' in namespace 'N' through class 'E'.
Function F() As B
~
BC30508: 'o' cannot expose type 'A.B' in namespace '<Default>' through class 'F'.
Sub M(o As B)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30509ERR_InheritanceAccessMismatch5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InheritanceAccessMismatch5">
<file name="a.vb"><![CDATA[
Module Module1
Private Class C1
End Class
Class C2
Inherits C1
End Class
Class C3
Protected Class C4
End Class
Class C5
Inherits C4
End Class
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30509: 'C2' cannot inherit from class 'Module1.C1' because it expands the access of the base class to namespace '<Default>'.
Inherits C1
~~
BC30509: 'C5' cannot inherit from class 'Module1.C3.C4' because it expands the access of the base class to namespace '<Default>'.
Inherits C4
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30529ERR_ParamTypingInconsistency()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamTypingInconsistency">
<file name="a.vb"><![CDATA[
class M1
Sub Goo(ByVal [a], ByRef [continue], ByVal c As Single)
End Sub
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Sub Goo(ByVal [a], ByRef [continue], ByVal c As Single)
~~~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Sub Goo(ByVal [a], ByRef [continue], ByVal c As Single)
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30530ERR_ParamNameFunctionNameCollision_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
class M1
Function Goo(Of Goo)(ByVal Goo As Goo)
End Function
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32090: Type parameter cannot have the same name as its defining function.
Function Goo(Of Goo)(ByVal Goo As Goo)
~~~
BC30530: Parameter cannot have the same name as its defining function.
Function Goo(Of Goo)(ByVal Goo As Goo)
~~~
BC32089: 'Goo' is already declared as a type parameter of this method.
Function Goo(Of Goo)(ByVal Goo As Goo)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30530ERR_ParamNameFunctionNameCollision_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P(p, q)
Set(value)
End Set
End Property
Private _q
WriteOnly Property Q
Set(Q) ' No error
_q = Q
End Set
End Property
Property R
Get
Return Nothing
End Get
Set(get_R) ' No error
End Set
End Property
WriteOnly Property S
Set(set_S) ' No error
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30530: Parameter cannot have the same name as its defining function.
WriteOnly Property P(p, q)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540629")>
<Fact>
Public Sub BC30548ERR_InvalidAssemblyAttribute1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidAssemblyAttribute1">
<file name="a.vb"><![CDATA[
Imports System
'COMPILEERROR: BC30548, "Assembly: c1()"
<Assembly: c1()>
'COMPILEERROR: BC30549, "Module: c1()"
<Module: c1()>
<AttributeUsageAttribute(AttributeTargets.Class, Inherited:=False)>
NotInheritable Class c1Attribute
Inherits Attribute
End Class
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InvalidAssemblyAttribute1, "c1").WithArguments("c1Attribute"),
Diagnostic(ERRID.ERR_InvalidModuleAttribute1, "c1").WithArguments("c1Attribute"))
End Sub
<WorkItem(540629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540629")>
<Fact>
Public Sub BC30549ERR_InvalidModuleAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidModuleAttribute1">
<file name="a.vb"><![CDATA[
Imports System
<Module: InternalsVisibleTo()>
<AttributeUsageAttribute(AttributeTargets.Delegate)>
Class InternalsVisibleTo
Inherits Attribute
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidModuleAttribute1, "InternalsVisibleTo").WithArguments("InternalsVisibleTo"))
End Sub
<Fact>
Public Sub BC30561ERR_AmbiguousInImports2()
Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"N1", "N2"}))
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInImports2">
<file name="a.vb"><![CDATA[
Public Class Cls2
Implements i1
End Class
]]></file>
<file name="b.vb"><![CDATA[
Namespace N1
Interface I1
End Interface
End Namespace
Namespace N2
Interface I1
End Interface
End Namespace
]]></file>
</compilation>, options:=options)
Dim expectedErrors1 = <errors><![CDATA[
BC30561: 'I1' is ambiguous, imported from the namespaces or types 'N1, N2'.
Implements i1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30562ERR_AmbiguousInModules2()
Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"N1", "N2"}))
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AmbiguousInModules2">
<file name="a.vb"><![CDATA[
Public Class Cls2
Implements i1
End Class
]]></file>
<file name="b.vb"><![CDATA[
Module N1
Interface I1
End Interface
End Module
Module N2
Interface I1
End Interface
End Module
]]></file>
</compilation>, options)
Dim expectedErrors1 = <errors><![CDATA[
BC30562: 'I1' is ambiguous between declarations in Modules 'N1, N2'.
Implements i1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30572ERR_DuplicateNamedImportAlias1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BC30572ERR_DuplicateNamedImportAlias1">
<file name="a.vb"><![CDATA[
Imports Alias1 = N1.C1(of String)
Imports Alias1 = N1.C1(of String)
]]></file>
<file name="b.vb"><![CDATA[
Module N1
Class C1(of T)
End class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30572: Alias 'Alias1' is already declared.
Imports Alias1 = N1.C1(of String)
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30573ERR_DuplicatePrefix()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Xml.Linq
Imports <xmlns="default1">
Imports <xmlns="default2">
Imports <xmlns:p="p1">
Imports <xmlns:q="q">
Imports <xmlns:p="p2">
Class C
Private F As XElement = <p:a xmlns:p="p3" xmlns:q="q"/>
End Class
]]></file>
</compilation>, references:=XmlReferences)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30573: XML namespace prefix '' is already declared.
Imports <xmlns="default2">
~~~~~~~~~~~~~~~~~~
BC30573: XML namespace prefix 'p' is already declared.
Imports <xmlns:p="p2">
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30573ERR_DuplicatePrefix_1()
Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns=""default1"">", "<xmlns=""default2"">", "<xmlns:p=""p1"">", "<xmlns:q=""q"">", "<xmlns:p=""p2"">"}))
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Imports <xmlns="default">
Imports <xmlns:p="p">
Imports <xmlns:q="q">
Class C
End Class
]]></file>
</compilation>, references:=XmlReferences, options:=options)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30573: Error in project-level import '<xmlns:p="p2">' at '<xmlns:p="p2">' : XML namespace prefix 'p' is already declared.
BC30573: Error in project-level import '<xmlns="default2">' at '<xmlns="default2">' : XML namespace prefix '' is already declared.
]]></errors>)
Dim embedded = compilation.GetTypeByMetadataName("Microsoft.VisualBasic.Embedded")
Assert.IsType(Of EmbeddedSymbolManager.EmbeddedNamedTypeSymbol)(embedded)
Assert.False(DirectCast(embedded, INamedTypeSymbol).IsSerializable)
End Sub
<Fact>
Public Sub BC30583ERR_MethodAlreadyImplemented2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MethodAlreadyImplemented2">
<file name="a.vb"><![CDATA[
Namespace NS1
Interface i1
Sub goo()
End Interface
Interface i2
Inherits i1
End Interface
Interface i3
Inherits i1
End Interface
Class cls1
Implements i2, i3
Sub i2goo() Implements i2.goo
Console.WriteLine("in i1, goo")
End Sub
'COMPILEERROR: BC30583, "i3.goo"
Sub i3goo() Implements i3.goo
Console.WriteLine("in i3, goo")
End Sub
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30583: 'i1.goo' cannot be implemented more than once.
Sub i3goo() Implements i3.goo
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30584ERR_DuplicateInInherits1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateInInherits1">
<file name="a.vb"><![CDATA[
Interface sce(Of T)
End Interface
Interface sce1
Inherits sce(Of Integer)
Inherits sce(Of Integer)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30584: 'sce(Of Integer)' cannot be inherited more than once.
Inherits sce(Of Integer)
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30584ERR_DuplicateInInherits1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateInInherits1">
<file name="a.vb"><![CDATA[
interface I1
End interface
Structure s1
Interface sce1
Inherits I1
Inherits I1
End Interface
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30584: 'I1' cannot be inherited more than once.
Inherits I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30590ERR_EventNotFound1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="EventNotFound1">
<file name="a.vb"><![CDATA[
Friend Module mod30590
Class cls1
Event Ev2()
End Class
Class cls2 : Inherits cls1
Public WithEvents o As cls2
Private Shadows Sub Ev2()
End Sub
'COMPILEERROR: BC30590, "Ev2"
Private Sub o_Ev2() Handles o.Ev2
End Sub
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30590: Event 'Ev2' cannot be found.
Private Sub o_Ev2() Handles o.Ev2
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30593ERR_ModuleCantUseVariableSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseVariableSpecifier1">
<file name="a.vb"><![CDATA[
Class class1
End Class
Structure struct1
End Structure
Friend Module ObjInit14mod
'COMPILEERROR: BC30593, "Shared"
Shared cls As New class1()
'COMPILEERROR: BC30593, "Shared"
Shared xint As New Integer()
'COMPILEERROR: BC30593, "Shared"
Shared xdec As New Decimal(40@)
'COMPILEERROR: BC30593, "Shared"
Shared xstrct As New struct1()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared cls As New class1()
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared xint As New Integer()
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared xdec As New Decimal(40@)
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared xstrct As New struct1()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30594ERR_SharedEventNeedsSharedHandler()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SharedEventNeedsSharedHandler">
<file name="a.vb"><![CDATA[
Module M1
Class myCls
Event Event1()
End Class
Class myClass1
Shared WithEvents x As myCls
Public Sub EventHandler() Handles x.Event1
End Sub
Private Sub EventHandler1() Handles x.Event1
End Sub
Protected Sub EventHandler2() Handles x.Event1
End Sub
Friend Sub EventHandler3() Handles x.Event1
End Sub
End Class
Class myClass2
Shared WithEvents x As myCls
Overridable Sub EventHandler() Handles x.Event1
End Sub
End Class
MustInherit Class myClass3
Shared WithEvents x As myCls
MustOverride Sub EventHandler() Handles x.Event1
End Class
Class myClass4
Overridable Sub EventHandler()
End Sub
End Class
Class myClass7
Inherits myClass4
Shared WithEvents x As myCls
NotOverridable Overrides Sub EventHandler() Handles x.Event1
End Sub
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Public Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
Public Sub EventHandler() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Private Sub EventHandler1() Handles x.Event1
~
BC31029: Method 'EventHandler1' cannot handle event 'Event1' because they do not have a compatible signature.
Private Sub EventHandler1() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Protected Sub EventHandler2() Handles x.Event1
~
BC31029: Method 'EventHandler2' cannot handle event 'Event1' because they do not have a compatible signature.
Protected Sub EventHandler2() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Friend Sub EventHandler3() Handles x.Event1
~
BC31029: Method 'EventHandler3' cannot handle event 'Event1' because they do not have a compatible signature.
Friend Sub EventHandler3() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Overridable Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
Overridable Sub EventHandler() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
MustOverride Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
MustOverride Sub EventHandler() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
NotOverridable Overrides Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
NotOverridable Overrides Sub EventHandler() Handles x.Event1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
CompilationUtils.AssertTheseEmitDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30927ERR_MustOverOnNotInheritPartClsMem1_1()
CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class Test
NotInheritable Class C
End Class
Partial Class C
'COMPILEERROR: BC30927, "goo"
MustOverride Function goo() As Integer
End Class
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MustOverOnNotInheritPartClsMem1, "MustOverride").WithArguments("MustOverride"))
End Sub
<Fact>
Public Sub NotInheritableInOtherPartial()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class B
Overridable Sub f()
End Sub
Overridable Property p As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
NotInheritable Class C
Inherits B
End Class
Partial Class C
MustOverride Sub f1()
MustOverride Property p1 As Integer
Overridable Sub f2()
End Sub
Overridable Property p2 As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
NotOverridable Overrides Sub f()
End Sub
NotOverridable Overrides Property p As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30927: 'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.
MustOverride Sub f1()
~~~~~~~~~~~~
BC30927: 'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.
MustOverride Property p1 As Integer
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30607ERR_BadFlagsInNotInheritableClass1_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
MustOverride Sub O()
MustOverride Property R
End Class
NotInheritable Class B
Inherits A
Overridable Sub M()
End Sub
MustOverride Sub N()
NotOverridable Overrides Sub O()
End Sub
Overridable Property P
MustOverride Property Q
NotOverridable Overrides Property R
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Sub M()
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Sub N()
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Overrides Sub O()
~~~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Property P
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Property Q
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Overrides Property R
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<WorkItem(540594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540594")>
<Fact>
Public Sub BC30610ERR_BaseOnlyClassesMustBeExplicit2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseOnlyClassesMustBeExplicit2">
<file name="a.vb"><![CDATA[
MustInherit Class Cls1
MustOverride Sub Goo(ByVal Arg As Integer)
MustOverride Sub Goo(ByVal Arg As Double)
End Class
'COMPILEERROR: BC30610, "cls2"
Class cls2
Inherits Cls1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30610: Class 'cls2' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
Cls1: Public MustOverride Sub Goo(Arg As Integer)
Cls1: Public MustOverride Sub Goo(Arg As Double).
Class cls2
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(541026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541026")>
<Fact()>
Public Sub BC30610ERR_BaseOnlyClassesMustBeExplicit2WithBC31411()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseOnlyClassesMustBeExplicit2">
<file name="a.vb"><![CDATA[
MustInherit Class Cls1
MustOverride Sub Goo(ByVal Arg As Integer)
MustOverride Sub Goo(ByVal Arg As Double)
End Class
'COMPILEERROR: BC30610, "cls2"
Class cls2
Inherits Cls1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30610: Class 'cls2' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
Cls1: Public MustOverride Sub Goo(Arg As Integer)
Cls1: Public MustOverride Sub Goo(Arg As Double).
Class cls2
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30628ERR_StructCantInherit()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructCantInherit">
<file name="a.vb"><![CDATA[
Structure S1
Structure S2
Inherits s1
End Structure
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30628: Structures cannot have 'Inherits' statements.
Inherits s1
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30629ERR_NewInStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NewInStruct">
<file name="a.vb"><![CDATA[
Module mod30629
Structure Struct1
'COMPILEERROR:BC30629,"new"
Public Sub New()
End Sub
End Structure
End Module
]]></file>
</compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic12))
Dim expectedErrors1 = <errors><![CDATA[
BC30629: Structures cannot declare a non-shared 'Sub New' with no parameters.
Public Sub New()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC37240ERR_StructParameterlessInstanceCtorMustBePublic()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NewInStruct">
<file name="a.vb"><![CDATA[
Module mod37240
Structure Struct1
'COMPILEERROR:BC37240,"new"
Private Sub New()
End Sub
End Structure
sub Main
end sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30629: Structures cannot declare a non-shared 'Sub New' with no parameters.
Private Sub New()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30639ERR_BadPropertyFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyFlags1">
<file name="a.vb"><![CDATA[
Interface I
NotInheritable Property P
MustInherit ReadOnly Property Q
WriteOnly Const Property R(o)
Partial Property S
End Interface
Class C
NotInheritable Property T
MustInherit ReadOnly Property U
Get
Return Nothing
End Get
End Property
WriteOnly Const Property V(o)
Set(value)
End Set
End Property
Partial Property W
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30639: Properties cannot be declared 'NotInheritable'.
NotInheritable Property P
~~~~~~~~~~~~~~
BC30639: Properties cannot be declared 'MustInherit'.
MustInherit ReadOnly Property Q
~~~~~~~~~~~
BC30639: Properties cannot be declared 'Const'.
WriteOnly Const Property R(o)
~~~~~
BC30639: Properties cannot be declared 'Partial'.
Partial Property S
~~~~~~~
BC30639: Properties cannot be declared 'NotInheritable'.
NotInheritable Property T
~~~~~~~~~~~~~~
BC30639: Properties cannot be declared 'MustInherit'.
MustInherit ReadOnly Property U
~~~~~~~~~~~
BC30639: Properties cannot be declared 'Const'.
WriteOnly Const Property V(o)
~~~~~
BC30639: Properties cannot be declared 'Partial'.
Partial Property W
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30645ERR_InvalidOptionalParameterUsage1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidOptionalParameterUsage1">
<file name="a.vb"><![CDATA[
Module M1
<System.Web.Services.WebMethod(True)>
Public Function HelloWorld(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(Net451.SystemWebServices)
Dim expectedErrors1 = <errors><![CDATA[
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld(Optional ByVal n As String = "e") As String
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30645ERR_InvalidOptionalParameterUsage1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidOptionalParameterUsage1a">
<file name="a.vb"><![CDATA[
Module M1
<System.Web.Services.WebMethod(True)>
<System.Web.Services.WebMethod(False)>
Public Function HelloWorld(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(Net451.SystemWebServices)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30663: Attribute 'WebMethodAttribute' cannot be applied multiple times.
<System.Web.Services.WebMethod(False)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld(Optional ByVal n As String = "e") As String
~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30645ERR_InvalidOptionalParameterUsage1b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidOptionalParameterUsage1b">
<file name="a.vb"><![CDATA[
Module M1
<System.Web.Services.WebMethod()>
Public Function HelloWorld1(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled)>
Public Function HelloWorld2(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1)>
Public Function HelloWorld3(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1, True)>
Public Function HelloWorld4(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1, True, 123)>
Public Function HelloWorld5(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(Net451.SystemWebServices,
Net451.SystemEnterpriseServices)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<errors><![CDATA[
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld1(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld2(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld3(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld4(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30516: Overload resolution failed because no accessible 'New' accepts this number of arguments.
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1, True, 123)>
~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30650ERR_InvalidEnumBase()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidEnumBase">
<file name="a.vb"><![CDATA[
Module ICase1mod
Enum color1 As Double
blue
End Enum
Enum color2 As String
blue
End Enum
Enum color3 As Single
blue
End Enum
Enum color4 As Date
blue
End Enum
Enum color5 As Object
blue
End Enum
Enum color6 As Boolean
blue
End Enum
Enum color7 As Decimal
blue
End Enum
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30650: Enums must be declared as an integral type.
Enum color1 As Double
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color2 As String
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color3 As Single
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color4 As Date
~~~~
BC30650: Enums must be declared as an integral type.
Enum color5 As Object
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color6 As Boolean
~~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color7 As Decimal
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30651ERR_ByRefIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ByRefIllegal1">
<file name="a.vb"><![CDATA[
Class C
Property P(ByVal x, ByRef y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
ReadOnly Property Q(ParamArray p())
Get
Return Nothing
End Get
End Property
WriteOnly Property R(Optional x = Nothing)
Set(value)
End Set
End Property
End Class
Interface I
ReadOnly Property P(ByRef x, Optional ByVal y = Nothing)
WriteOnly Property Q(ParamArray p())
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30651: property parameters cannot be declared 'ByRef'.
Property P(ByVal x, ByRef y)
~~~~~
BC30651: property parameters cannot be declared 'ByRef'.
ReadOnly Property P(ByRef x, Optional ByVal y = Nothing)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30652ERR_UnreferencedAssembly3()
Dim Lib1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Lib1">
<file name="a.vb"><![CDATA[
Public Class C1
End Class
]]></file>
</compilation>)
Dim Lib2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Lib2">
<file name="a.vb"><![CDATA[
Public Class C2
Dim s as C1
End Class
]]></file>
</compilation>)
Dim ref1 = New VisualBasicCompilationReference(Lib1)
Lib2 = Lib2.AddReferences(ref1)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnreferencedAssembly3">
<file name="a.vb"><![CDATA[
Public Class C
Dim s as C1
End Class
]]></file>
</compilation>)
Dim ref2 = New VisualBasicCompilationReference(Lib2)
compilation1 = compilation1.AddReferences(ref2)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'C1' is not defined.
Dim s as C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538153")>
<Fact>
Public Sub BC30656ERR_UnsupportedField1()
Dim csharpComp = CSharp.CSharpCompilation.Create("Test", options:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim text = "public class A { public static volatile int X; }"
Dim ref = Net40.mscorlib
csharpComp = csharpComp.AddSyntaxTrees(CSharp.SyntaxFactory.ParseSyntaxTree(text))
csharpComp = csharpComp.AddReferences(ref)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnsupportedField1">
<file name="a.vb"><![CDATA[
Module M
Dim X = A.X
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(MetadataReference.CreateFromImage(csharpComp.EmitToArray()))
Dim expectedErrors1 = <errors><![CDATA[
BC30656: Field 'X' is of an unsupported type.
Dim X = A.X
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30660ERR_LocalsCannotHaveAttributes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="LocalsCannotHaveAttributes">
<file name="at30660.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(p As ULong)
End Sub
End Class
Public Class Goo
Public Function SSS() As Byte
<My(12345)> Dim x As Byte = 1
Return x
End Function
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_LocalsCannotHaveAttributes, "<My(12345)>"))
End Sub
<Fact>
Public Sub BC30662ERR_InvalidAttributeUsage2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidAttributeUsage2">
<file name="a.vb"><![CDATA[
Imports System
Namespace DecAttr
<AttributeUsageAttribute(AttributeTargets.Property)> Class attr1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Event)> Class attr2
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Delegate)> Class attr3
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Constructor)> Class attr4
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Field)> Class attr5
Inherits Attribute
End Class
Class scen1
<attr1()> Public Declare Function Beep1 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr2()> Public Declare Function Beep2 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr3()> Public Declare Function Beep3 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr4()> Public Declare Function Beep4 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr5()> Public Declare Function Beep5 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
End Class
End Namespace
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr1").WithArguments("attr1", "Beep1"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr2").WithArguments("attr2", "Beep2"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr3").WithArguments("attr3", "Beep3"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr4").WithArguments("attr4", "Beep4"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr5").WithArguments("attr5", "Beep5"))
End Sub
<WorkItem(538370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538370")>
<Fact>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly:clscompliant(true), Assembly:clscompliant(true), Assembly:clscompliant(true)>
<Module:clscompliant(true), Module:clscompliant(true), Module:clscompliant(true)>
Namespace DecAttr
<AttributeUsageAttribute(AttributeTargets.Property)>
Class attrProperty
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Parameter)>
Class attrParameter
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.ReturnValue)>
Class attrReturnType
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Class)>
Class attrClass
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Struct)>
Class attrStruct
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Method)>
Class attrMethod
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Field)>
Class attrField
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Enum)>
Class attrEnum
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Constructor)>
Class attrCtor
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Delegate)>
Class attrDelegate
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Interface)>
Class attrInterface
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Assembly)>
Class attrAssembly
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Module)>
Class attrModule
Inherits Attribute
End Class
<attrClass(), attrClass(), attrClass()>
Module M1
End Module
<attrInterface(), attrInterface(), attrInterface()>
Interface I
End Interface
<attrEnum(), attrEnum(), attrEnum()>
Enum E
member
End Enum
<attrDelegate(), attrDelegate(), attrDelegate()>
Delegate Sub Del()
<attrClass(), attrClass()>
<attrClass()>
Class scen1(Of T1)
<attrCtor(), attrCtor(), attrCtor()>
Public Sub New()
End Sub
<attrField(), attrField(), attrField()>
Public field as Integer
Private newPropertyValue As String
<attrProperty()> ' first ok
<attrProperty()> ' first error
<attrProperty()> ' second error
Public Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
<attrMethod(), attrMethod(), attrMethod()>
Public function Sub1(Of T)(
<attrParameter(), attrParameter(), attrParameter()> a as Integer,
b as T) as <attrReturnType(), attrReturnType(), attrReturnType()> Integer
return 23
End function
End Class
<attrStruct()>
<attrStruct(), attrStruct()>
Structure S1
End Structure
End Namespace
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Assembly:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Assembly:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Module:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Module:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrDelegate()").WithArguments("attrDelegate"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrDelegate()").WithArguments("attrDelegate"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrEnum()").WithArguments("attrEnum"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrEnum()").WithArguments("attrEnum"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrInterface()").WithArguments("attrInterface"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrInterface()").WithArguments("attrInterface"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrStruct()").WithArguments("attrStruct"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrStruct()").WithArguments("attrStruct"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrParameter()").WithArguments("attrParameter"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrParameter()").WithArguments("attrParameter"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrCtor()").WithArguments("attrCtor"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrCtor()").WithArguments("attrCtor"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrField()").WithArguments("attrField"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrField()").WithArguments("attrField"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrProperty()").WithArguments("attrProperty"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrProperty()").WithArguments("attrProperty"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrReturnType()").WithArguments("attrReturnType"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrReturnType()").WithArguments("attrReturnType"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrMethod()").WithArguments("attrMethod"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrMethod()").WithArguments("attrMethod"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1a">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
<A1(), A2()>
Partial Private Sub M(i As Integer)
End Sub
End Class
Partial Class C1
<A1(), A2()>
Private Sub M(i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1b">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
<A2(), A1(), A2()>
Partial Private Sub M(i As Integer)
End Sub
End Class
Partial Class C1
<A1(), A1(), A2()>
Private Sub M(i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1c()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1c">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
Partial Private Sub M(<A1(), A2()>i As Integer)
End Sub
End Class
Partial Class C1
Private Sub M(<A1(), A2()>i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1d()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1d">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
Partial Private Sub M(<A2(), A1(), A2()>i As Integer)
End Sub
End Class
Partial Class C1
Private Sub M(<A1(), A1(), A2()>i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact>
Public Sub BC30668ERR_UseOfObsoleteSymbol2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UseOfObsoleteSymbol2">
<file name="a.vb"><![CDATA[
Imports System
Namespace NS
Class clstest
<Obsolete("Scenario6 Message", True)> Protected Friend WriteOnly Property scenario6()
Set(ByVal Value)
End Set
End Property
<Obsolete("", True)> Public Shared WriteOnly Property scenario7()
Set(ByVal Value)
End Set
End Property
<Obsolete()> Default Property scenario8(ByVal i As Integer) As Integer
Get
Return 1
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Class clsTest1
<Obsolete("", True)> Default Public ReadOnly Property scenario9(ByVal i As Long) As Long
Get
Return 1
End Get
End Property
End Class
Friend Module OBS022mod
<Obsolete("Scenario1 Message", True)> WriteOnly Property Scenario1a()
Set(ByVal Value)
End Set
End Property
<Obsolete("Scenario2 Message", True)> ReadOnly Property scenario2()
Get
Return 1
End Get
End Property
Sub OBS022()
Dim obj As Object = 23%
Dim cls1 As New clstest()
'COMPILEERROR: BC30668, "Scenario1a"
Scenario1a = obj
'COMPILEERROR: BC30668, "scenario2"
obj = scenario2
'COMPILEERROR: BC30668, "cls1.scenario6"
cls1.scenario6 = obj
'COMPILEERROR: BC30668, "clstest.scenario7"
clstest.scenario7 = obj
Dim cls2 As New clsTest1()
'COMPILEERROR: BC30668, "cls2"
obj = cls2(4)
End Sub
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30668: 'Public WriteOnly Property Scenario1a As Object' is obsolete: 'Scenario1 Message'.
Scenario1a = obj
~~~~~~~~~~
BC30668: 'Public ReadOnly Property scenario2 As Object' is obsolete: 'Scenario2 Message'.
obj = scenario2
~~~~~~~~~
BC30668: 'Protected Friend WriteOnly Property scenario6 As Object' is obsolete: 'Scenario6 Message'.
cls1.scenario6 = obj
~~~~~~~~~~~~~~
BC31075: 'Public Shared WriteOnly Property scenario7 As Object' is obsolete.
clstest.scenario7 = obj
~~~~~~~~~~~~~~~~~
BC31075: 'Public ReadOnly Default Property scenario9(i As Long) As Long' is obsolete.
obj = cls2(4)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538173")>
<Fact>
Public Sub BC30683ERR_InheritsStmtWrongOrder()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsStmtWrongOrder">
<file name="a.vb"><![CDATA[
Class cn1
Public ss As Long
'COMPILEERROR: BC30683, "Inherits c2"
Inherits c2
End Class
Class c2
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30683: 'Inherits' statement must precede all declarations in a class.
Inherits c2
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseParseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30688ERR_InterfaceEventCantUse1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceEventCantUse1">
<file name="a.vb"><![CDATA[
Interface I
Event Goo() Implements I.Goo
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30688: Events in interfaces cannot be declared 'Implements'.
Event Goo() Implements I.Goo
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30695ERR_MustShadow2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustShadow2">
<file name="a.vb"><![CDATA[
Class c1
'COMPILEERROR: BC30695, "goo",
Sub goo()
End Sub
Shadows Function goo(ByVal i As Integer) As Integer
End Function
End Class
Class c2_1
Public goo As Integer
End Class
Class c2_2
Inherits c2_1
Shadows Sub goo()
End Sub
'COMPILEERROR: BC30695,"goo"
Sub goo(ByVal c As Char)
End Sub
'COMPILEERROR: BC30695,"goo"
Sub goo(ByVal d As Double)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30695: sub 'goo' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Sub goo()
~~~
BC30695: sub 'goo' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Sub goo(ByVal c As Char)
~~~
BC40004: sub 'goo' conflicts with variable 'goo' in the base class 'c2_1' and should be declared 'Shadows'.
Sub goo(ByVal c As Char)
~~~
BC30695: sub 'goo' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Sub goo(ByVal d As Double)
~~~
BC40004: sub 'goo' conflicts with variable 'goo' in the base class 'c2_1' and should be declared 'Shadows'.
Sub goo(ByVal d As Double)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30695ERR_MustShadow2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class Base
Sub Method(x As Integer)
End Sub
Overloads Sub Method(x As String)
End Sub
End Class
Partial Class Derived1
Inherits Base
Shadows Sub Method(x As String)
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Class Derived1
Inherits Base
Overrides Sub Method(x As Integer)
End Sub
End Class
Class Derived2
Inherits Base
Function Method(x As String, y As Integer) As String
End Function
Overrides Sub Method(x As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: sub 'Method' must be declared 'Overloads' because another 'Method' is declared 'Overloads' or 'Overrides'.
Sub Method(x As Integer)
~~~~~~
BC30695: sub 'Method' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Overrides Sub Method(x As Integer)
~~~~~~
BC31086: 'Public Overrides Sub Method(x As Integer)' cannot override 'Public Sub Method(x As Integer)' because it is not declared 'Overridable'.
Overrides Sub Method(x As Integer)
~~~~~~
BC31409: function 'Method' must be declared 'Overloads' because another 'Method' is declared 'Overloads' or 'Overrides'.
Function Method(x As String, y As Integer) As String
~~~~~~
BC40003: function 'Method' shadows an overloadable member declared in the base class 'Base'. If you want to overload the base method, this method must be declared 'Overloads'.
Function Method(x As String, y As Integer) As String
~~~~~~
BC31086: 'Public Overrides Sub Method(x As Integer)' cannot override 'Public Sub Method(x As Integer)' because it is not declared 'Overridable'.
Overrides Sub Method(x As Integer)
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30696ERR_OverloadWithOptionalTypes2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithOptionalTypes2">
<file name="a.vb"><![CDATA[
Class Cla30696
'COMPILEERROR: BC30696, "goo"
Public Function goo(Optional ByVal arg As ULong = 1)
Return "BC30696"
End Function
Public Function goo(Optional ByVal arg As Integer = 1)
Return "BC30696"
End Function
'COMPILEERROR: BC30696, "goo3"
Public Function goo1(ByVal arg As Integer, Optional ByVal arg1 As String = "")
Return "BC30696"
End Function
Public Function goo1(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
Return "BC30696"
End Function
End Class
Interface Scen2_1
'COMPILEERROR: BC30696, "goo"
Function goo(Optional ByVal arg As Object = Nothing)
Function goo(Optional ByVal arg As ULong = 1)
'COMPILEERROR: BC30696, "goo3"
Function goo1(ByVal arg As Integer, Optional ByVal arg1 As Object = Nothing)
Function goo1(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
End Interface
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors><![CDATA[]]></errors>)
End Sub
<WorkItem(529018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529018")>
<Fact()>
Public Sub BC30697ERR_OverrideWithOptionalTypes2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideWithOptionalTypes2">
<file name="a.vb"><![CDATA[
Class Base
Public Overridable Sub goo(ByVal x As String, Optional ByVal y As String = "hello")
End Sub
End Class
Class C1
Inherits Base
Public Overrides Sub goo(ByVal x As String, Optional ByVal y As Integer = 1)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30697: 'Public Overrides Sub goo(x As String, [y As Integer = 1])' cannot override 'Public Overridable Sub goo(x As String, [y As String = "hello"])' because they differ by the types of optional parameters.
Public Overrides Sub goo(ByVal x As String, Optional ByVal y As Integer = 1)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30728ERR_StructsCannotHandleEvents()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructsCannotHandleEvents">
<file name="a.vb"><![CDATA[
Public Structure S1
Event e()
Sub goo() Handles c.e
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30728: Methods declared in structures cannot have 'Handles' clauses.
Sub goo() Handles c.e
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub goo() Handles c.e
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30730ERR_OverridesImpliesOverridable()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverridesImpliesOverridable">
<file name="a.vb"><![CDATA[
Class CBase
overridable function goo
End function
End Class
Class C1
Inherits CBase
Overrides public Overridable function goo
End function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30730: Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.
Overrides public Overridable function goo
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for ERRID_ModuleCantUseMemberSpecifier1
' Old name="ModifierErrorsInsideModules"
<Fact>
Public Sub BC30735ERR_ModuleCantUseTypeSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module m1
protected Class c
Protected Enum e1
a
End Enum
End Class
Protected Enum e5
a
End Enum
Shadows Enum e6
a
End Enum
protected structure struct1
end structure
protected delegate Sub d1(i as integer)
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30735: Type in a Module cannot be declared 'protected'.
protected Class c
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'Protected'.
Protected Enum e5
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'Shadows'.
Shadows Enum e6
~~~~~~~
BC30735: Type in a Module cannot be declared 'protected'.
protected structure struct1
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'protected'.
protected delegate Sub d1(i as integer)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC30770ERR_DefaultEventNotFound1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="DefaultEventNotFound1">
<file name="a.vb"><![CDATA[
Imports System.ComponentModel
<DefaultEvent("LogonCompleted")> Public Class EventSource1
Private Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource2
Public Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource22
Friend Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource23
Protected Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource24
Protected Friend Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent(Nothing)> Public Class EventSource3
End Class
<DefaultEvent("")> Public Class EventSource4
End Class
<DefaultEvent(" ")> Public Class EventSource5
End Class
Class Base
Public Event LogonCompleted()
End Class
<DefaultEvent("LogonCompleted")> Class EventSource6
Inherits Base
Private Shadows Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleted")> Interface EventSource7
End Interface
<DefaultEvent("LogonCompleted")> Structure EventSource8
End Structure
]]></file>
</compilation>, {SystemRef}, TestOptions.ReleaseDll)
Dim expectedErrors = <errors><![CDATA[
BC30770: Event 'LogonCompleted' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent("LogonCompleted")> Public Class EventSource1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30770: Event 'LogonCompleteD' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent("LogonCompleteD")> Public Class EventSource23
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30770: Event 'LogonCompleteD' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent("LogonCompleteD")> Public Class EventSource24
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30770: Event ' ' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent(" ")> Public Class EventSource5
~~~~~~~~~~~~~~~~~~
BC30662: Attribute 'DefaultEventAttribute' cannot be applied to 'EventSource7' because the attribute is not valid on this declaration type.
<DefaultEvent("LogonCompleted")> Interface EventSource7
~~~~~~~~~~~~
BC30662: Attribute 'DefaultEventAttribute' cannot be applied to 'EventSource8' because the attribute is not valid on this declaration type.
<DefaultEvent("LogonCompleted")> Structure EventSource8
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact, WorkItem(545966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545966")>
Public Sub BC30772ERR_InvalidNonSerializedUsage()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidNonSerializedUsage">
<file name="a.vb"><![CDATA[
Imports System
Module M1
<NonSerialized>
Dim x = 1
<NonSerialized>
Event E As System.Action
End Module
]]></file>
</compilation>)
Dim expectedErrors =
<errors><![CDATA[
BC30772: 'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.
<NonSerialized>
~~~~~~~~~~~~~
BC30772: 'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.
<NonSerialized>
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30786ERR_ModuleCantUseDLLDeclareSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseDLLDeclareSpecifier1">
<file name="a.vb"><![CDATA[
Module M
Protected Declare Sub Goo Lib "My" ()
End Module
]]></file>
</compilation>)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_ModuleCantUseDLLDeclareSpecifier1, "Protected").WithArguments("Protected"))
End Sub
<Fact>
Public Sub BC30791ERR_StructCantUseDLLDeclareSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructCantUseDLLDeclareSpecifier1">
<file name="a.vb"><![CDATA[
Structure M
Protected Declare Sub Goo Lib "My" ()
End Structure
]]></file>
</compilation>)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StructCantUseDLLDeclareSpecifier1, "Protected").WithArguments("Protected"))
End Sub
<Fact>
Public Sub BC30795ERR_SharedStructMemberCannotSpecifyNew()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedStructMemberCannotSpecifyNew">
<file name="a.vb"><![CDATA[
Structure S1
' does not work
Dim structVar1 As New System.ApplicationException
' works
Shared structVar2 As New System.ApplicationException
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30795: Non-shared members in a Structure cannot be declared 'New'.
Dim structVar1 As New System.ApplicationException
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC31049ERR_SharedStructMemberCannotSpecifyInitializers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC30795ERR_SharedStructMemberCannotSpecifyInitializers">
<file name="a.vb"><![CDATA[
Structure S1
' does not work
Dim structVar1 As System.ApplicationException = New System.ApplicationException()
' works
Shared structVar2 As System.ApplicationException = New System.ApplicationException()
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31049: Initializers on structure members are valid only for 'Shared' members and constants.
Dim structVar1 As System.ApplicationException = New System.ApplicationException()
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30798ERR_InvalidTypeForAliasesImport2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidTypeForAliasesImport2">
<file name="a.vb"><![CDATA[
Imports aa = System.Action 'BC30798
Imports bb = ns1.Intfc2.intfc2goo 'BC40056
Namespace ns1
Public Class Intfc2
Public intfc2goo As Integer
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30798: 'Action' for the Imports alias to 'Action' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.
Imports aa = System.Action 'BC30798
~~~~~~~~~~~~~~~~~~
BC40056: Namespace or type specified in the Imports 'ns1.Intfc2.intfc2goo' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports bb = ns1.Intfc2.intfc2goo 'BC40056
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
<WorkItem(13926, "https://github.com/dotnet/roslyn/issues/13926")>
Public Sub BadAliasTarget()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports BadAlias = unknown
Public Class Class1
Public Shared Sub Main()
End Sub
Function Test() As BadAlias
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'unknown' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports BadAlias = unknown
~~~~~~~
BC31208: Type or namespace 'unknown' is not defined.
Function Test() As BadAlias
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
Dim test = compilation1.GetTypeByMetadataName("Class1").GetMember(Of MethodSymbol)("Test")
Assert.True(test.ReturnType.IsErrorType())
Assert.Equal(DiagnosticSeverity.Error, DirectCast(test.ReturnType, ErrorTypeSymbol).ErrorInfo.Severity)
End Sub
<Fact>
Public Sub BC30828ERR_ObsoleteAsAny()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ObsoleteAsAny">
<file name="a.vb"><![CDATA[
Class C1
Declare Sub goo Lib "a.dll" (ByRef bit As Any)
End Class
]]></file>
</compilation>)
compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_ObsoleteAsAny, "Any").WithArguments("Any"))
End Sub
<Fact>
Public Sub BC30906ERR_OverrideWithArrayVsParamArray2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideWithArrayVsParamArray2">
<file name="a.vb"><![CDATA[
Class C1
Overridable Sub goo(ByVal a As Integer())
End Sub
End Class
Class C2
Inherits C1
Overrides Sub goo(ByVal ParamArray a As Integer())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30906: 'Public Overrides Sub goo(ParamArray a As Integer())' cannot override 'Public Overridable Sub goo(a As Integer())' because they differ by parameters declared 'ParamArray'.
Overrides Sub goo(ByVal ParamArray a As Integer())
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30907ERR_CircularBaseDependencies4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CircularBaseDependencies4">
<file name="a.vb"><![CDATA[
Class A
Inherits B
End Class
Class B
Inherits C
End Class
Class C
Inherits A.D
End Class
Partial Class A
Class D
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type '
'A' inherits from 'B'.
'B' inherits from 'C'.
'C' inherits from 'A.D'.
'A.D' is nested in 'A'.'.
Inherits B
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30908ERR_NestedBase2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NestedBase2">
<file name="a.vb"><![CDATA[
NotInheritable Class cls1b
Inherits cls1a
MustInherit Class cls1a
Sub subScen1()
gstrexpectedresult = "Scen1"
End Sub
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31446: Class 'cls1b' cannot reference its nested type 'cls1b.cls1a' in Inherits clause.
Inherits cls1a
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class PublicClass
Protected Friend Structure ProtectedFriendStructure
End Structure
End Class
Friend Class FriendClass
End Class
Friend Structure FriendStructure
End Structure
Friend Interface FriendInterface
End Interface
Friend Enum FriendEnum
A
End Enum
Public Class A
Inherits PublicClass
Public F As ProtectedFriendStructure
Public G As FriendClass
Public H As FriendStructure
End Class
Public Structure B
Public F As FriendInterface
Public G As FriendEnum
End Structure
Public Class C
Inherits PublicClass
Public Function F() As ProtectedFriendStructure
End Function
Public Sub M(x As FriendClass)
End Sub
End Class
Public Interface I
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'F' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'A'.
Public F As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'G' cannot expose type 'FriendClass' outside the project through class 'A'.
Public G As FriendClass
~~~~~~~~~~~
BC30909: 'H' cannot expose type 'FriendStructure' outside the project through class 'A'.
Public H As FriendStructure
~~~~~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendInterface' outside the project through structure 'B'.
Public F As FriendInterface
~~~~~~~~~~~~~~~
BC30909: 'G' cannot expose type 'FriendEnum' outside the project through structure 'B'.
Public G As FriendEnum
~~~~~~~~~~
BC30909: 'F' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'C'.
Public Function F() As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendClass' outside the project through class 'C'.
Public Sub M(x As FriendClass)
~~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendStructure' outside the project through interface 'I'.
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'y' cannot expose type 'FriendInterface' outside the project through interface 'I'.
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendEnum' outside the project through interface 'I'.
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class PublicClass
Protected Friend Structure ProtectedFriendStructure
End Structure
End Class
Friend Class FriendClass
End Class
Friend Structure FriendStructure
End Structure
Friend Interface FriendInterface
End Interface
Friend Enum FriendEnum
A
End Enum
Public Class A
Inherits PublicClass
Property P As ProtectedFriendStructure
Property Q As FriendClass
Property R As FriendStructure
End Class
Public Structure B
Property P As FriendInterface
Property Q As FriendEnum
End Structure
Public Class C
Inherits PublicClass
ReadOnly Property P(x As FriendClass) As ProtectedFriendStructure
Get
Return Nothing
End Get
End Property
End Class
Public Interface I
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'P' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'A'.
Property P As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'Q' cannot expose type 'FriendClass' outside the project through class 'A'.
Property Q As FriendClass
~~~~~~~~~~~
BC30909: 'R' cannot expose type 'FriendStructure' outside the project through class 'A'.
Property R As FriendStructure
~~~~~~~~~~~~~~~
BC30909: 'P' cannot expose type 'FriendInterface' outside the project through structure 'B'.
Property P As FriendInterface
~~~~~~~~~~~~~~~
BC30909: 'Q' cannot expose type 'FriendEnum' outside the project through structure 'B'.
Property Q As FriendEnum
~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendClass' outside the project through class 'C'.
ReadOnly Property P(x As FriendClass) As ProtectedFriendStructure
~~~~~~~~~~~
BC30909: 'P' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'C'.
ReadOnly Property P(x As FriendClass) As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendStructure' outside the project through interface 'I'.
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'y' cannot expose type 'FriendInterface' outside the project through interface 'I'.
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'P' cannot expose type 'FriendEnum' outside the project through interface 'I'.
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528153")>
<Fact()>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class PublicClass
Protected Friend Interface ProtectedFriendInterface
End Interface
Protected Friend Class ProtectedFriendClass
End Class
End Class
Friend Interface FriendInterface
End Interface
Friend Class FriendClass
End Class
Public Class A
Inherits PublicClass
Public Sub M(Of T As ProtectedFriendInterface, U As ProtectedFriendClass)()
End Sub
End Class
Public Structure B
Public Sub M(Of T As FriendInterface, U As FriendClass)()
End Sub
End Structure
Public Interface I
Function F(Of T As FriendInterface, U As FriendClass)() As Object
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'M' cannot expose type 'PublicClass.ProtectedFriendInterface' outside the project through class 'A'.
Public Sub M(Of T As ProtectedFriendInterface, U As ProtectedFriendClass)()
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'M' cannot expose type 'PublicClass.ProtectedFriendClass' outside the project through class 'A'.
Public Sub M(Of T As ProtectedFriendInterface, U As ProtectedFriendClass)()
~~~~~~~~~~~~~~~~~~~~
BC30909: 'M' cannot expose type 'FriendInterface' outside the project through structure 'B'.
Public Sub M(Of T As FriendInterface, U As FriendClass)()
~~~~~~~~~~~~~~~
BC30909: 'M' cannot expose type 'FriendClass' outside the project through structure 'B'.
Public Sub M(Of T As FriendInterface, U As FriendClass)()
~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendInterface' outside the project through interface 'I'.
Function F(Of T As FriendInterface, U As FriendClass)() As Object
~~~~~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendClass' outside the project through interface 'I'.
Function F(Of T As FriendInterface, U As FriendClass)() As Object
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528153")>
<Fact()>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Interface A
Friend Interface B
End Interface
Public Interface C
Function F() As B
Public Interface D
Sub M(o As B)
End Interface
End Interface
End Interface
Public Interface E
Inherits A
Function F() As B
End Interface
Public Interface F
Sub M(o As A.B)
End Interface
End Namespace
Public Interface G
Function F() As N.A.B
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'F' cannot expose type 'A.B' outside the project through interface 'C'.
Function F() As B
~
BC30909: 'o' cannot expose type 'A.B' outside the project through interface 'D'.
Sub M(o As B)
~
BC30909: 'F' cannot expose type 'A.B' outside the project through interface 'E'.
Function F() As B
~
BC30909: 'o' cannot expose type 'A.B' outside the project through interface 'F'.
Sub M(o As A.B)
~~~
BC30909: 'F' cannot expose type 'A.B' outside the project through interface 'G'.
Function F() As N.A.B
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Friend Enum E
A
End Enum
Public Class C
Public Const F As E = E.A
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'F' cannot expose type 'E' outside the project through class 'C'.
Public Const F As E = E.A
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30910ERR_InheritanceAccessMismatchOutside3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritanceAccessMismatchOutside3">
<file name="a.vb"><![CDATA[
Friend Interface I1
End Interface
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30910: 'I2' cannot inherit from interface 'I1' because it expands the access of the base interface outside the assembly.
Inherits I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30911ERR_UseOfObsoletePropertyAccessor3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoletePropertyAccessor3">
<file name="a.vb"><![CDATA[
Imports System
Class C1
ReadOnly Property p As String
<Obsolete("hello", True)>
Get
Return "hello"
End Get
End Property
End Class
Class C2
Sub goo()
Dim s As New C1
Dim a = s.p
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30911: 'Get' accessor of 'Public ReadOnly Property p As String' is obsolete: 'hello'.
Dim a = s.p
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30912ERR_UseOfObsoletePropertyAccessor2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoletePropertyAccessor2">
<file name="a.vb"><![CDATA[
Imports System
Class C1
ReadOnly Property p As String
<Obsolete(nothing,True)>
Get
Return "hello"
End Get
End Property
End Class
Class C2
Sub goo()
Dim s As New C1
Dim a = s.p
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30912: 'Get' accessor of 'Public ReadOnly Property p As String' is obsolete.
Dim a = s.p
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543640")>
Public Sub BC30914ERR_AccessMismatchImplementedEvent6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AccessMismatchImplementedEvent6">
<file name="a.vb"><![CDATA[
Public Class C
Protected Interface i1
Event goo()
End Interface
Friend Class c1
Implements i1
Public Event goo() Implements i1.goo
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30914: 'goo' cannot expose the underlying delegate type 'C.i1.gooEventHandler' of the event it is implementing to namespace '<Default>' through class 'c1'.
Public Event goo() Implements i1.goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543641")>
Public Sub BC30915ERR_AccessMismatchImplementedEvent4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AccessMismatchImplementedEvent4">
<file name="a.vb"><![CDATA[
Interface i1
Event goo()
End Interface
Public Class c1
Implements i1
Public Event goo() Implements i1.goo
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30915: 'goo' cannot expose the underlying delegate type 'i1.gooEventHandler' of the event it is implementing outside the project through class 'c1'.
Public Event goo() Implements i1.goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30916ERR_InheritanceCycleInImportedType1()
Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1
Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2
Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Class C
Class C
Inherits C1
implements I1
End Class
End Class
]]></file>
</compilation>,
{Net451.mscorlib, C1, C2})
Dim expectedErrors = <errors><![CDATA[
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
Inherits C1
~~
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30916ERR_InheritanceCycleInImportedType1_2()
Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1
Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2
Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Class C
Inherits C2
implements I1
End Class
]]></file>
</compilation>,
{Net451.mscorlib, C1, C2})
Dim expectedErrors = <errors><![CDATA[
BC30916: Type 'C2' is not supported because it either directly or indirectly inherits from itself.
Inherits C2
~~
BC30916: Type 'C2' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30916ERR_InheritanceCycleInImportedType1_3()
Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1
Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2
Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Class C
Inherits C1
implements I1
End Class
]]></file>
</compilation>,
{Net451.mscorlib, C1, C2})
Dim expectedErrors = <errors><![CDATA[
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
Inherits C1
~~
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30921ERR_InheritsTypeArgAccessMismatch7()
Dim Comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsTypeArgAccessMismatch7">
<file name="a.vb"><![CDATA[
Public Class containingClass
Public Class baseClass(Of t)
End Class
Friend Class derivedClass
Inherits baseClass(Of internalStructure)
End Class
Private Structure internalStructure
Dim firstMember As Integer
End Structure
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30921: 'derivedClass' cannot inherit from class 'containingClass.baseClass(Of containingClass.internalStructure)' because it expands the access of type 'containingClass.internalStructure' to namespace '<Default>'.
Inherits baseClass(Of internalStructure)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30922ERR_InheritsTypeArgAccessMismatchOutside5()
Dim Comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsTypeArgAccessMismatchOutside5">
<file name="a.vb"><![CDATA[
Public Class baseClass(Of t)
End Class
Public Class derivedClass
Inherits baseClass(Of restrictedStructure)
End Class
Friend Structure restrictedStructure
Dim firstMember As Integer
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30922: 'derivedClass' cannot inherit from class 'baseClass(Of restrictedStructure)' because it expands the access of type 'restrictedStructure' outside the assembly.
Inherits baseClass(Of restrictedStructure)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30925ERR_PartialTypeAccessMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialTypeAccessMismatch3">
<file name="a.vb"><![CDATA[
Class s1
Partial Protected Class c1
End Class
Partial Private Class c1
End Class
Partial Friend Class c1
End Class
Partial Protected Interface I1
End Interface
Partial Private Interface I1
End Interface
Partial Friend Interface I1
End Interface
End Class
Partial Public Module m1
End Module
Partial Friend Module m1
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30925: Specified access 'Private' for 'c1' does not match the access 'Protected' specified on one of its other partial types.
Partial Private Class c1
~~
BC30925: Specified access 'Friend' for 'c1' does not match the access 'Protected' specified on one of its other partial types.
Partial Friend Class c1
~~
BC30925: Specified access 'Private' for 'I1' does not match the access 'Protected' specified on one of its other partial types.
Partial Private Interface I1
~~
BC30925: Specified access 'Friend' for 'I1' does not match the access 'Protected' specified on one of its other partial types.
Partial Friend Interface I1
~~
BC30925: Specified access 'Friend' for 'm1' does not match the access 'Public' specified on one of its other partial types.
Partial Friend Module m1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30926ERR_PartialTypeBadMustInherit1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialTypeBadMustInherit1">
<file name="a.vb"><![CDATA[
Partial Class C1
Partial MustInherit Class C2
End Class
End Class
Partial Class C1
Partial NotInheritable Class C2
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30926: 'MustInherit' cannot be specified for partial type 'C2' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.
Partial MustInherit Class C2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' dup of 30607?
<Fact>
Public Sub BC30927ERR_MustOverOnNotInheritPartClsMem1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustOverOnNotInheritPartClsMem1">
<file name="a.vb"><![CDATA[
Public Class C1
MustOverride Sub goo()
End Class
Partial Public NotInheritable Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30927: 'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.
MustOverride Sub goo()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30928ERR_BaseMismatchForPartialClass3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseMismatchForPartialClass3">
<file name="a.vb"><![CDATA[
Option Strict On
Interface I1
End Interface
Interface I2
End Interface
Partial Interface I3
Inherits I1
End Interface
Partial Interface I3
Inherits I2
End Interface
Class TestModule
Sub Test(x As I3)
Dim y As I1 = x
Dim z As I2 = x
End Sub
End Class
Partial Class Cls2(Of T, U)
Inherits Class1(Of U, T)
End Class
Partial Class Cls2(Of T, U)
Inherits Class1(Of T, T)
End Class
Class Class1(Of X, Y)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30928: Base class 'Class1(Of T, T)' specified for class 'Cls2' cannot be different from the base class 'Class1(Of U, T)' of one of its other partial types.
Inherits Class1(Of T, T)
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30931ERR_PartialTypeTypeParamNameMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A(Of T)
Partial Class B(Of U As A(Of T), V As A(Of V))
End Class
Partial Class B(Of X As A(Of T), Y As A(Of Y))
End Class
Partial Interface I(Of U As A(Of T), V As A(Of V))
End Interface
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
End Interface
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30931: Type parameter name 'X' does not match the name 'U' of the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30931: Type parameter name 'Y' does not match the name 'V' of the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30002: Type 'Y' is not defined.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30931: Type parameter name 'X' does not match the name 'U' of the corresponding type parameter defined on one of the other partial types of 'I'.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
BC30931: Type parameter name 'Y' does not match the name 'V' of the corresponding type parameter defined on one of the other partial types of 'I'.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'I'.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
BC30002: Type 'Y' is not defined.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30932ERR_PartialTypeConstraintMismatch1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
End Interface
Interface IB
End Interface
' Different constraints.
Partial Class A1(Of T As Structure)
End Class
Partial Class A1(Of T As Class)
End Class
Partial Class A2(Of T As Structure, U As IA(Of T))
End Class
Partial Class A2(Of T As Class, U As IB)
End Class
Partial Class A3(Of T As IA(Of T))
End Class
Partial Class A3(Of T As IA(Of IA(Of T)))
End Class
Partial Class A4(Of T As {Structure, IB})
End Class
Partial Class A4(Of T As {Class, IB})
End Class
Partial Structure A5(Of T As {IA(Of T), New})
End Structure
Partial Structure A5(Of T As {IA(Of T), New})
End Structure
Partial Structure A5(Of T As {IB, New})
End Structure
' Additional constraints.
Partial Class B1(Of T As New)
End Class
Partial Class B1(Of T As {Class, New})
End Class
Partial Class B2(Of T, U As {IA(Of T)})
End Class
Partial Class B2(Of T, U As {IB, IA(Of T)})
End Class
' Missing constraints.
Partial Class C1(Of T As {Class, New})
End Class
Partial Class C1(Of T As {New})
End Class
Partial Structure C2(Of T, U As {IB, IA(Of T)})
End Structure
Partial Structure C2(Of T, U As {IA(Of T)})
End Structure
' Same constraints, different order.
Partial Class D1(Of T As {Structure, IA(Of T), IB})
End Class
Partial Class D1(Of T As {IB, IA(Of T), Structure})
End Class
Partial Class D1(Of T As {Structure, IB, IA(Of T)})
End Class
Partial Class D2(Of T, U, V As {T, U})
End Class
Partial Class D2(Of T, U, V As {U, T})
End Class
' Different constraint clauses.
Partial Class E1(Of T, U As T)
End Class
Partial Class E1(Of T As Class, U)
End Class
Partial Class E1(Of T, U As T)
End Class
Partial Class E2(Of T, U As IB)
End Class
Partial Class E2(Of T As IA(Of U), U)
End Class
Partial Class E2(Of T As IB, U)
End Class
' Additional constraint clause.
Partial Class F1(Of T)
End Class
Partial Class F1(Of T)
End Class
Partial Class F1(Of T As Class)
End Class
Partial Class F2(Of T As Class, U)
End Class
Partial Class F2(Of T As Class, U As T)
End Class
' Missing constraint clause.
Partial Class G1(Of T As {Class})
End Class
Partial Class G1(Of T)
End Class
Partial Structure G2(Of T As {Class}, U As {T})
End Structure
Partial Structure G2(Of T As {Class}, U)
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A1'.
Partial Class A1(Of T As Class)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A2'.
Partial Class A2(Of T As Class, U As IB)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A2'.
Partial Class A2(Of T As Class, U As IB)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A3'.
Partial Class A3(Of T As IA(Of IA(Of T)))
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A4'.
Partial Class A4(Of T As {Class, IB})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A5'.
Partial Structure A5(Of T As {IB, New})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B1'.
Partial Class B1(Of T As {Class, New})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B2'.
Partial Class B2(Of T, U As {IB, IA(Of T)})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'C1'.
Partial Class C1(Of T As {New})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'C2'.
Partial Structure C2(Of T, U As {IA(Of T)})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E1'.
Partial Class E1(Of T As Class, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E1'.
Partial Class E1(Of T As Class, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IA(Of U), U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IA(Of U), U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IB, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IB, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'F1'.
Partial Class F1(Of T As Class)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'F2'.
Partial Class F2(Of T As Class, U As T)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'G1'.
Partial Class G1(Of T)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'G2'.
Partial Structure G2(Of T As {Class}, U)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Unrecognized constraint types should not result
' in constraint mismatch errors in partial types.
<Fact()>
Public Sub BC30932ERR_PartialTypeConstraintMismatch1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Partial Class C(Of T As {Class, Unknown})
End Class
Partial Class C(Of T As {Unknown, Class})
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'Unknown' is not defined.
Partial Class C(Of T As {Class, Unknown})
~~~~~~~
BC30002: Type 'Unknown' is not defined.
Partial Class C(Of T As {Unknown, Class})
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Duplicate constraints in partial types.
<Fact()>
Public Sub BC30932ERR_PartialTypeConstraintMismatch1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Partial Class A(Of T As {New, New, I, I})
End Class
Partial Class A(Of T As {New, I})
End Class
Partial Class B(Of T, U As T)
End Class
Partial Class B(Of T, U As {T, T})
End Class
]]></file>
</compilation>)
' Note: Dev10 simply reports the duplicate constraint in each case, even
' in subsequent partial declarations. Arguably the Dev10 behavior is better.
Dim expectedErrors1 = <errors><![CDATA[
BC32081: 'New' constraint cannot be specified multiple times for the same type parameter.
Partial Class A(Of T As {New, New, I, I})
~~~
BC32071: Constraint type 'I' already specified for this type parameter.
Partial Class A(Of T As {New, New, I, I})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A'.
Partial Class A(Of T As {New, I})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of T, U As {T, T})
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30935ERR_AmbiguousOverrides3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousOverrides3">
<file name="a.vb"><![CDATA[
Public Class baseClass(Of t)
Public Overridable Sub goo(ByVal inputValue As String)
End Sub
Public Overridable Sub goo(ByVal inputValue As t)
End Sub
End Class
Public Class derivedClass
Inherits baseClass(Of String)
Overrides Sub goo(ByVal inputValue As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30935: Member 'Public Overridable Sub goo(inputValue As String)' that matches this signature cannot be overridden because the class 'baseClass' contains multiple members with this same name and signature:
'Public Overridable Sub goo(inputValue As String)'
'Public Overridable Sub goo(inputValue As t)'
Overrides Sub goo(ByVal inputValue As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30937ERR_AmbiguousImplements3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousImplements3">
<file name="a.vb"><![CDATA[
Public Interface baseInterface(Of t)
Sub doSomething(ByVal inputValue As String)
Sub doSomething(ByVal inputValue As t)
End Interface
Public Class implementingClass
Implements baseInterface(Of String)
Sub doSomething(ByVal inputValue As String) _
Implements baseInterface(Of String).doSomething
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'implementingClass' must implement 'Sub doSomething(inputValue As String)' for interface 'baseInterface(Of String)'.
Implements baseInterface(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~
BC30937: Member 'baseInterface(Of String).doSomething' that matches this signature cannot be implemented because the interface 'baseInterface(Of String)' contains multiple members with this same name and signature:
'Sub doSomething(inputValue As String)'
'Sub doSomething(inputValue As String)'
Implements baseInterface(Of String).doSomething
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30972ERR_StructLayoutAttributeNotAllowed()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructLayoutAttributeNotAllowed">
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Runtime.InteropServices
<StructLayout(1)>
Structure C1(Of T)
Sub goo(ByVal a As T)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30972: Attribute 'StructLayout' cannot be applied to a generic type.
<StructLayout(1)>
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31029ERR_EventHandlerSignatureIncompatible2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventHandlerSignatureIncompatible2">
<file name="a.vb"><![CDATA[
option strict on
Class clsTest1
Event ev1(ByVal ArgC As Char)
End Class
Class clsTest2
Inherits clsTest1
Shadows Event ev1(ByVal ArgI As Integer)
End Class
Class clsTest3
Dim WithEvents clsTest As clsTest2
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31029: Method 'subTest' cannot handle event 'ev1' because they do not have a compatible signature.
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31029ERR_EventHandlerSignatureIncompatible2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventHandlerSignatureIncompatible2a">
<file name="a.vb"><![CDATA[
option strict off
Class clsTest1
Event ev1(ByVal ArgC As Char)
End Class
Class clsTest2
Inherits clsTest1
Shadows Event ev1(ByVal ArgI As Integer)
End Class
Class clsTest3
Dim WithEvents clsTest As clsTest2
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31029: Method 'subTest' cannot handle event 'ev1' because they do not have a compatible signature.
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(542143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542143")>
<Fact>
Public Sub BC31033ERR_InterfaceImplementedTwice1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceImplementedTwice1">
<file name="a.vb"><![CDATA[
Class C1
Implements I1(Of Integer), I1(Of Double), I1(Of Integer)
End Class
Interface I1(Of T)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31033: Interface 'I1(Of Integer)' can be implemented only once by this type.
Implements I1(Of Integer), I1(Of Double), I1(Of Integer)
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31033ERR_InterfaceImplementedTwice1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceImplementedTwice1">
<file name="a.vb"><![CDATA[
Class c3_1
Implements i3_1
End Class
Class c3_2
Inherits c3_1
Implements i3_1, i3_1, i3_1
End Class
Interface i3_1
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31033: Interface 'i3_1' can be implemented only once by this type.
Implements i3_1, i3_1, i3_1
~~~~
BC31033: Interface 'i3_1' can be implemented only once by this type.
Implements i3_1, i3_1, i3_1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31035ERR_InterfaceNotImplemented1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceNotImplemented1">
<file name="a.vb"><![CDATA[
Interface I
Sub S()
End Interface
Class C1
Implements I
Public Sub S() Implements I.S
End Sub
End Class
Class C2
Inherits C1
Public Sub F() Implements I.S
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31035: Interface 'I' is not implemented by this class.
Public Sub F() Implements I.S
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31041ERR_BadInterfaceMember()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadInterfaceMember">
<file name="a.vb"><![CDATA[
Interface Interface1
Module Module1
End Module
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30603: Statement cannot appear within an interface body.
Module Module1
~~~~~~~~~~~~~~
BC30603: Statement cannot appear within an interface body.
End Module
~~~~~~~~~~
BC30622: 'End Module' must be preceded by a matching 'Module'.
End Module
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseParseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31043ERR_ArrayInitInStruct_1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public j(10) As Integer
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public j(10) As Integer
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31043ERR_ArrayInitInStruct_2">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared j(10) As Integer
End Structure
]]></file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31043ERR_ArrayInitInStruct_3">
<file name="a.vb"><![CDATA[
Public Structure S1
Public k(10) As Integer = {1}
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public k(10) As Integer = {1}
~~~~~
BC31049: Initializers on structure members are valid only for 'Shared' members and constants.
Public k(10) As Integer = {1}
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ArrayInitInStruct_4">
<file name="a.vb"><![CDATA[
Public Structure S1
Public l(10), m(1), n As Integer
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public l(10), m(1), n As Integer
~~~~~
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public l(10), m(1), n As Integer
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31044ERR_EventTypeNotDelegate()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventTypeNotDelegate">
<file name="a.vb"><![CDATA[
Public Class C1
Public Event E As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31044: Events declared with an 'As' clause must have a delegate type.
Public Event E As String
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31047ERR_ProtectedTypeOutsideClass()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ProtectedTypeOutsideClass">
<file name="a.vb"><![CDATA[
Protected Enum Enum11
Apple
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31047: Protected types can only be declared inside of a class.
Protected Enum Enum11
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for ERRID_StructCantUseVarSpecifier1
' Oldname"ModifierErrorsInsideStructures"
<Fact>
Public Sub BC31047ERR_ProtectedTypeOutsideClass_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure s
Protected Enum e3
a
End Enum
Private Enum e4
x
End Enum
protected delegate Sub d1(i as integer)
Protected Structure s_s1
end structure
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31047: Protected types can only be declared inside of a class.
Protected Enum e3
~~
BC31047: Protected types can only be declared inside of a class.
protected delegate Sub d1(i as integer)
~~
BC31047: Protected types can only be declared inside of a class.
Protected Structure s_s1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC31048ERR_DefaultPropertyWithNoParams()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Default Property P()
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
Class B
Default ReadOnly Property Q(ParamArray x As Object())
Get
Return Nothing
End Get
End Property
End Class
Interface IA
Default WriteOnly Property P()
End Interface
Interface IB
Default Property Q(ParamArray x As Object())
End Interface
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property P()
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default ReadOnly Property Q(ParamArray x As Object())
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default WriteOnly Property P()
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property Q(ParamArray x As Object())
~
]]></errors>)
End Sub
<Fact>
Public Sub BC31048ERR_DefaultPropertyWithNoParams_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA
Default Property P(Optional o As Object = Nothing)
Property Q(Optional o As Object = Nothing)
End Interface
Interface IB
Default Property P(x As Object, Optional y As Integer = 1)
Default Property P(Optional x As Integer = 0, Optional y As Integer = 1)
Property Q(Optional x As Integer = 0, Optional y As Integer = 1)
End Interface
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property P(Optional o As Object = Nothing)
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property P(Optional x As Integer = 0, Optional y As Integer = 1)
~
]]></errors>)
End Sub
<Fact>
Public Sub BC31049ERR_InitializerInStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InitializerInStruct">
<file name="a.vb"><![CDATA[
Structure S1
' does not work
Dim i As Integer = 10
' works
const j as Integer = 10
shared k as integer = 10
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31049: Initializers on structure members are valid only for 'Shared' members and constants.
Dim i As Integer = 10
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31051ERR_DuplicateImport1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateImport1">
<file name="a.vb"><![CDATA[
Imports ns1.genclass(Of String)
Imports ns1.genclass(Of String)
Namespace ns1
Class genclass(Of T)
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31051: Namespace or type 'genclass(Of String)' has already been imported.
Imports ns1.genclass(Of String)
~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31051ERR_DuplicateImport1_GlobalImports()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateImport1_GlobalImports">
<file name="a.vb"><![CDATA[
Imports System.Collections
Imports System.Collections
Class C
End Class
]]></file>
</compilation>, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithGlobalImports(
GlobalImport.Parse(
{"System.Collections", "System.Collections"}
)
))
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31051: Namespace or type 'System.Collections' has already been imported.
Imports System.Collections
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31051ERR_DuplicateImport1_GlobalImports_NoErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31051ERR_DuplicateImport1_GlobalImports_NoErrors">
<file name="a.vb"><![CDATA[
Imports System.Collections
Class C
End Class
]]></file>
</compilation>, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithGlobalImports(
GlobalImport.Parse(
{"System.Collections", "System.Collections"}
)
))
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors><![CDATA[]]></errors>)
End Sub
<Fact()>
Public Sub BC31052ERR_BadModuleFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BC31052ERR_BadModuleFlags1">
<file name="a.vb"><![CDATA[
NotInheritable Module M1
End Module
shared Module M2
End Module
readonly Module M3
End Module
overridable Module M5
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31052: Modules cannot be declared 'NotInheritable'.
NotInheritable Module M1
~~~~~~~~~~~~~~
BC31052: Modules cannot be declared 'shared'.
shared Module M2
~~~~~~
BC31052: Modules cannot be declared 'readonly'.
readonly Module M3
~~~~~~~~
BC31052: Modules cannot be declared 'overridable'.
overridable Module M5
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_1()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Class Cls1
Event e()
End Class
Event obj1()
Dim obj1event As [Delegate]
End Module
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_SynthMemberClashesWithMember5, "obj1").WithArguments("event", "obj1", "obj1Event", "module", "M1"))
End Sub
<Fact>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property u
Function get_p()
Return Nothing
End Function
Shared Function set_p()
Return Nothing
End Function
Shared Sub GET_Q()
End Sub
Sub SET_Q()
End Sub
Dim get_R
Shared set_R
Shared Property get_s
Property set_s
Class get_T
End Class
Structure set_T
End Structure
Enum get_U
X
End Enum
End Class
]]></file>
</compilation>)
' Since nested types are bound before members, we report 31061 for
' cases where nested types conflict with implicit property members.
' This differs from Dev10 which reports 31060 in all these cases.
Dim expectedErrors1 = <errors><![CDATA[
BC31060: property 'P' implicitly defines 'get_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'P' implicitly defines 'set_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'Q' implicitly defines 'get_Q', which conflicts with a member of the same name in class 'C'.
Shared Property Q
~
BC31060: property 'Q' implicitly defines 'set_Q', which conflicts with a member of the same name in class 'C'.
Shared Property Q
~
BC31060: property 'r' implicitly defines 'get_r', which conflicts with a member of the same name in class 'C'.
Property r
~
BC31060: property 'r' implicitly defines 'set_r', which conflicts with a member of the same name in class 'C'.
Property r
~
BC31060: property 's' implicitly defines 'get_s', which conflicts with a member of the same name in class 'C'.
Shared Property s
~
BC31060: property 's' implicitly defines 'set_s', which conflicts with a member of the same name in class 'C'.
Shared Property s
~
BC31061: class 'get_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Class get_T
~~~~~
BC31061: structure 'set_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Structure set_T
~~~~~
BC31061: enum 'get_U' conflicts with a member implicitly declared for property 'u' in class 'C'.
Enum get_U
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
Get
Return Nothing
End Get
Set
End Set
End Property
ReadOnly Property Q
Get
Return Nothing
End Get
End Property
WriteOnly Property R
Set
End Set
End Property
Private get_P
Private set_P
Private get_Q
Private set_Q
Private get_R
Private set_R
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31060: property 'P' implicitly defines 'get_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'P' implicitly defines 'set_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'Q' implicitly defines 'get_Q', which conflicts with a member of the same name in class 'C'.
ReadOnly Property Q
~
BC31060: property 'R' implicitly defines 'set_R', which conflicts with a member of the same name in class 'C'.
WriteOnly Property R
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property U
Property v
Shared Property w
Property X
Function _p()
Return Nothing
End Function
Shared Sub _Q()
End Sub
Dim _r
Shared _S
Shared Property _t
Property _U
Class _v
End Class
Structure _W
End Structure
Enum _x
X
End Enum
End Class
]]></file>
</compilation>)
' Since nested types are bound before members, we report 31061 for
' cases where nested types conflict with implicit property members.
' This differs from Dev10 which reports 31060 in all these cases.
Dim expectedErrors1 = <errors><![CDATA[
BC31060: property 'P' implicitly defines '_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'Q' implicitly defines '_Q', which conflicts with a member of the same name in class 'C'.
Shared Property Q
~
BC31060: property 'r' implicitly defines '_r', which conflicts with a member of the same name in class 'C'.
Property r
~
BC31060: property 's' implicitly defines '_s', which conflicts with a member of the same name in class 'C'.
Shared Property s
~
BC31060: property 'T' implicitly defines '_T', which conflicts with a member of the same name in class 'C'.
Property T
~
BC31060: property 'U' implicitly defines '_U', which conflicts with a member of the same name in class 'C'.
Shared Property U
~
BC31061: class '_v' conflicts with a member implicitly declared for property 'v' in class 'C'.
Class _v
~~
BC31061: structure '_W' conflicts with a member implicitly declared for property 'w' in class 'C'.
Structure _W
~~
BC31061: enum '_x' conflicts with a member implicitly declared for property 'X' in class 'C'.
Enum _x
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31061ERR_MemberClashesWithSynth6_1()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
Class Cls1
Event e()
End Class
Dim WithEvents ObjEvent As Cls1
Event Obj()
End Module
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MemberClashesWithSynth6, "ObjEvent").WithArguments("WithEvents variable", "ObjEvent", "event", "Obj", "module", "M1"))
End Sub
<Fact>
Public Sub BC31061ERR_MemberClashesWithSynth6_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Function get_p()
Return Nothing
End Function
Shared Function set_p()
Return Nothing
End Function
Shared Sub GET_Q()
End Sub
Sub SET_Q()
End Sub
Dim get_R
Shared set_R
Shared Property get_s
Property set_s
Class get_T
End Class
Structure set_T
End Structure
Enum get_U
X
End Enum
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property u
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: function 'get_p' conflicts with a member implicitly declared for property 'P' in class 'C'.
Function get_p()
~~~~~
BC31061: function 'set_p' conflicts with a member implicitly declared for property 'P' in class 'C'.
Shared Function set_p()
~~~~~
BC31061: sub 'GET_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Shared Sub GET_Q()
~~~~~
BC31061: sub 'SET_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Sub SET_Q()
~~~~~
BC31061: variable 'get_R' conflicts with a member implicitly declared for property 'r' in class 'C'.
Dim get_R
~~~~~
BC31061: variable 'set_R' conflicts with a member implicitly declared for property 'r' in class 'C'.
Shared set_R
~~~~~
BC31061: property 'get_s' conflicts with a member implicitly declared for property 's' in class 'C'.
Shared Property get_s
~~~~~
BC31061: property 'set_s' conflicts with a member implicitly declared for property 's' in class 'C'.
Property set_s
~~~~~
BC31061: class 'get_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Class get_T
~~~~~
BC31061: structure 'set_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Structure set_T
~~~~~
BC31061: enum 'get_U' conflicts with a member implicitly declared for property 'u' in class 'C'.
Enum get_U
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31061ERR_MemberClashesWithSynth6_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Private get_P
Private set_P
Private get_Q
Private set_Q
Private get_R
Private set_R
Property P
Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
ReadOnly Property Q
Get
Return Nothing
End Get
End Property
WriteOnly Property R
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: variable 'get_P' conflicts with a member implicitly declared for property 'P' in class 'C'.
Private get_P
~~~~~
BC31061: variable 'set_P' conflicts with a member implicitly declared for property 'P' in class 'C'.
Private set_P
~~~~~
BC31061: variable 'get_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Private get_Q
~~~~~
BC31061: variable 'set_R' conflicts with a member implicitly declared for property 'R' in class 'C'.
Private set_R
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31061ERR_MemberClashesWithSynth6_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Function _p()
Return Nothing
End Function
Shared Sub _Q()
End Sub
Dim _r
Shared _S
Shared Property _t
Property _U
Class _v
End Class
Structure _W
End Structure
Enum _x
X
End Enum
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property U
Property v
Shared Property w
Property X
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: function '_p' conflicts with a member implicitly declared for property 'P' in class 'C'.
Function _p()
~~
BC31061: sub '_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Shared Sub _Q()
~~
BC31061: variable '_r' conflicts with a member implicitly declared for property 'r' in class 'C'.
Dim _r
~~
BC31061: variable '_S' conflicts with a member implicitly declared for property 's' in class 'C'.
Shared _S
~~
BC31061: property '_t' conflicts with a member implicitly declared for property 'T' in class 'C'.
Shared Property _t
~~
BC31061: property '_U' conflicts with a member implicitly declared for property 'U' in class 'C'.
Property _U
~~
BC31061: class '_v' conflicts with a member implicitly declared for property 'v' in class 'C'.
Class _v
~~
BC31061: structure '_W' conflicts with a member implicitly declared for property 'w' in class 'C'.
Structure _W
~~
BC31061: enum '_x' conflicts with a member implicitly declared for property 'X' in class 'C'.
Enum _x
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31063ERR_SetHasOnlyOneParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SetHasOnlyOneParam">
<file name="a.vb"><![CDATA[
Module M
WriteOnly Property P(ByVal i As Integer) As Integer
Set(x As Integer, ByVal Value As Integer)
End Set
End Property
WriteOnly Property Q()
Set() ' No error
If value Is Nothing Then
End If
End Set
End Property
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31063: 'Set' method cannot have more than one parameter.
Set(x As Integer, ByVal Value As Integer)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31064ERR_SetValueNotPropertyType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SetValueNotPropertyType">
<file name="a.vb"><![CDATA[
' Implicit property type and implicit set argument type (same)
Structure A
WriteOnly Property P%
Set(ap%) ' no error
End Set
End Property
WriteOnly Property Q&
Set(aq&) ' no error
End Set
End Property
WriteOnly Property R@
Set(ar@) ' no error
End Set
End Property
WriteOnly Property S!
Set(as!) ' no error
End Set
End Property
WriteOnly Property T#
Set(at#) ' no error
End Set
End Property
WriteOnly Property U$
Set(au$) ' no error
End Set
End Property
End Structure
' Implicit property type and explicit set argument type (same)
Class B
WriteOnly Property P%
Set(bp As Integer) ' no error
End Set
End Property
WriteOnly Property Q&
Set(bq As Long) ' no error
End Set
End Property
WriteOnly Property R@
Set(br As Decimal) ' no error
End Set
End Property
WriteOnly Property S!
Set(ba As Single) ' no error
End Set
End Property
WriteOnly Property T#
Set(bt As Double) ' no error
End Set
End Property
WriteOnly Property U$
Set(bu As String) ' no error
End Set
End Property
End Class
' Explicit property type and explicit set argument type (same)
Structure C
WriteOnly Property P As Integer
Set(cp As Integer) ' no error
End Set
End Property
WriteOnly Property Q As Long
Set(cq As Long) ' no error
End Set
End Property
WriteOnly Property R As Decimal
Set(cr As Decimal) ' no error
End Set
End Property
WriteOnly Property S As Single
Set(cs As Single) ' no error
End Set
End Property
WriteOnly Property T As Double
Set(ct As Double) ' no error
End Set
End Property
WriteOnly Property U As String
Set(cu As String) ' no error
End Set
End Property
End Structure
' Implicit property type and implicit set argument type (different)
Class D
WriteOnly Property P%
Set(ap&) ' BC31064
End Set
End Property
WriteOnly Property Q&
Set(aq@) ' BC31064
End Set
End Property
WriteOnly Property R@
Set(ar!) ' BC31064
End Set
End Property
WriteOnly Property S!
Set(as#) ' BC31064
End Set
End Property
WriteOnly Property T#
Set(at$) ' BC31064
End Set
End Property
WriteOnly Property U$
Set(au%) ' BC31064
End Set
End Property
End Class
' Implicit property type and explicit set argument type (different)
Structure E
WriteOnly Property P%
Set(bp As Decimal) ' BC31064
End Set
End Property
WriteOnly Property Q&
Set(bq As Single) ' BC31064
End Set
End Property
WriteOnly Property R@
Set(br As Double) ' BC31064
End Set
End Property
WriteOnly Property S!
Set(ba As String) ' BC31064
End Set
End Property
WriteOnly Property T#
Set(bt As Integer) ' BC31064
End Set
End Property
WriteOnly Property U$
Set(bu As Long) ' BC31064
End Set
End Property
End Structure
' Explicit property type and explicit set argument type (different)
Class F
WriteOnly Property P As Integer
Set(cp As Single) ' BC31064
End Set
End Property
WriteOnly Property Q As Long
Set(cq As Double) ' BC31064
End Set
End Property
WriteOnly Property R As Decimal
Set(cr As String) ' BC31064
End Set
End Property
WriteOnly Property S As Single
Set(cs As Integer) ' BC31064
End Set
End Property
WriteOnly Property T As Double
Set(ct As Long) ' BC31064
End Set
End Property
WriteOnly Property U As String
Set(cu As Decimal) ' BC31064
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ap&) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(aq@) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ar!) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(as#) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(at$) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(au%) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bp As Decimal) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bq As Single) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(br As Double) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ba As String) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bt As Integer) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bu As Long) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cp As Single) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cq As Double) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cr As String) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cs As Integer) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ct As Long) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cu As Decimal) ' BC31064
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31065ERR_SetHasToBeByVal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SetHasToBeByVal1">
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P
Set(ByRef value)
End Set
End Property
WriteOnly Property Q
Set(ByVal ParamArray value())
End Set
End Property
WriteOnly Property R As Integer()
Set(ParamArray value As Integer())
End Set
End Property
WriteOnly Property S
Set(Optional value = Nothing)
End Set
End Property
WriteOnly Property T
Set(ByVal value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31065: 'Set' parameter cannot be declared 'ByRef'.
Set(ByRef value)
~~~~~
BC31065: 'Set' parameter cannot be declared 'ParamArray'.
Set(ByVal ParamArray value())
~~~~~~~~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ByVal ParamArray value())
~~~~~
BC31065: 'Set' parameter cannot be declared 'ParamArray'.
Set(ParamArray value As Integer())
~~~~~~~~~~
BC31065: 'Set' parameter cannot be declared 'Optional'.
Set(Optional value = Nothing)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31067ERR_StructureCantUseProtected()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructureCantUseProtected">
<file name="a.vb"><![CDATA[
Structure S
Protected Sub New(o)
End Sub
Protected Friend Sub New(x, y)
End Sub
Protected Sub M()
End Sub
Protected Friend Function F()
Return Nothing
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Sub New(o)
~~~~~~~~~
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Friend Sub New(x, y)
~~~~~~~~~~~~~~~~
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Sub M()
~~~~~~~~~
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Friend Function F()
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31068ERR_BadInterfaceDelegateSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceDelegateSpecifier1">
<file name="a.vb"><![CDATA[
Interface i1
private Delegate Sub goo
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31068: Delegate in an interface cannot be declared 'private'.
private Delegate Sub goo
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31069ERR_BadInterfaceEnumSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceEnumSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
Public Enum E
ONE
End Enum
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31069: Enum in an interface cannot be declared 'Public'.
Public Enum E
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31070ERR_BadInterfaceClassSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceClassSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
Interface I2
Protected Class C1
End Class
Friend Class C2
End Class
End Interface
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31070: Class in an interface cannot be declared 'Protected'.
Protected Class C1
~~~~~~~~~
BC31070: Class in an interface cannot be declared 'Friend'.
Friend Class C2
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31071ERR_BadInterfaceStructSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceStructSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
Public Structure S1
End Structure
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31071: Structure in an interface cannot be declared 'Public'.
Public Structure S1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31075ERR_UseOfObsoleteSymbolNoMessage1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoleteSymbolNoMessage1">
<file name="a.vb"><![CDATA[
Imports System
<Obsolete(Nothing, True)> Interface I1
End Interface
Class class1
Implements I1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31075: 'I1' is obsolete.
Implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31083ERR_ModuleMemberCantImplement()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleMemberCantImplement">
<file name="a.vb"><![CDATA[
Module class1
Interface I1
Sub goo()
End Interface
'COMPILEERROR: BC31083, "Implements"
Public Sub goo() Implements I1.goo
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31083: Members in a Module cannot implement interface members.
Public Sub goo() Implements I1.goo
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31084ERR_EventDelegatesCantBeFunctions()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventDelegatesCantBeFunctions">
<file name="a.vb"><![CDATA[
Imports System
Class A
Event X As Func(Of String)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31084: Events cannot be declared with a delegate type that has a return type.
Event X As Func(Of String)
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31086ERR_CantOverride4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverride4">
<file name="a.vb"><![CDATA[
Class C1
Public Sub F1()
End Sub
End Class
Class B
Inherits C1
Public Overrides Sub F1()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31086: 'Public Overrides Sub F1()' cannot override 'Public Sub F1()' because it is not declared 'Overridable'.
Public Overrides Sub F1()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
Private Shared ReadOnly s_typeWithMixedProperty As String = <![CDATA[
.class public auto ansi beforefieldinit Base_VirtGet_Set
extends [mscorlib]System.Object
{
.method public hidebysig specialname newslot virtual
instance int32 get_Prop() cil managed
{
// Code size 2 (0x2)
.maxstack 8
ldstr "Base_VirtGet_Set.Get"
call void [mscorlib]System.Console::WriteLine(string)
IL_0000: ldc.i4.1
IL_0001: ret
}
.method public hidebysig specialname
instance void set_Prop(int32 'value') cil managed
{
// Code size 1 (0x1)
ldstr "Base_VirtGet_Set.Set"
call void [mscorlib]System.Console::WriteLine(string)
.maxstack 8
IL_0000: ret
}
.property instance int32 Prop()
{
.get instance int32 Base_VirtGet_Set::get_Prop()
.set instance void Base_VirtGet_Set::set_Prop(int32)
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
.class public auto ansi beforefieldinit Base_Get_VirtSet
extends [mscorlib]System.Object
{
.method public hidebysig specialname
instance int32 get_Prop() cil managed
{
// Code size 2 (0x2)
.maxstack 8
ldstr "Base_Get_VirtSet.Get"
call void [mscorlib]System.Console::WriteLine(string)
IL_0000: ldc.i4.1
IL_0001: ret
}
.method public hidebysig specialname newslot virtual
instance void set_Prop(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
ldstr "Base_Get_VirtSet.Set"
call void [mscorlib]System.Console::WriteLine(string)
IL_0000: ret
}
.property instance int32 Prop()
{
.get instance int32 Base_Get_VirtSet::get_Prop()
.set instance void Base_Get_VirtSet::set_Prop(int32)
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
]]>.Value.Replace(vbLf, vbCrLf)
<WorkItem(528982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528982")>
<Fact()>
Public Sub BC31086ERR_CantOverride5a()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="CantOverride5a">
<file name="a.vb"><![CDATA[
Class VBDerived
Inherits Base_Get_VirtSet
Public Overrides Property Prop As Integer
Get
System.Console.WriteLine("VBDerived.Get")
Return MyBase.Prop
End Get
Set(value As Integer)
System.Console.WriteLine("VBDerived.Set")
MyBase.Prop = value
End Set
End Property
Shared Sub Main()
Dim o As Base_Get_VirtSet
o = New Base_Get_VirtSet()
o.Prop = o.Prop
o = New VBDerived()
o.Prop = o.Prop
End Sub
End Class
]]></file>
</compilation>, s_typeWithMixedProperty, options:=TestOptions.DebugExe)
' There are no Errors, but getter is actually not overridden!!!
Dim validator = Sub(m As ModuleSymbol)
Dim p1 = m.GlobalNamespace.GetMember(Of PropertySymbol)("VBDerived.Prop")
Assert.True(p1.IsOverrides)
Dim baseP1 As PropertySymbol = p1.OverriddenProperty
Assert.True(baseP1.IsOverridable)
Assert.False(baseP1.GetMethod.IsOverridable)
Assert.True(baseP1.SetMethod.IsOverridable)
Dim p1Get = p1.GetMethod
Dim p1Set = p1.SetMethod
Assert.True(p1Get.IsOverrides)
Assert.Same(baseP1.GetMethod, p1Get.OverriddenMethod)
Assert.True(p1Set.IsOverrides)
Assert.Same(baseP1.SetMethod, p1Set.OverriddenMethod)
End Sub
CompileAndVerify(compilation1, expectedOutput:=
"Base_Get_VirtSet.Get
Base_Get_VirtSet.Set
Base_Get_VirtSet.Get
VBDerived.Set
Base_Get_VirtSet.Set", sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
<WorkItem(528982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528982")>
<Fact()>
Public Sub BC31086ERR_CantOverride5b()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="CantOverride5b">
<file name="a.vb"><![CDATA[
Class VBDerived
Inherits Base_VirtGet_Set
Public Overrides Property Prop As Integer
Get
System.Console.WriteLine("VBDerived.Get")
Return MyBase.Prop
End Get
Set(value As Integer)
System.Console.WriteLine("VBDerived.Set")
MyBase.Prop = value
End Set
End Property
Shared Sub Main()
Dim o As Base_VirtGet_Set
o = New Base_VirtGet_Set()
o.Prop = o.Prop
o = New VBDerived()
o.Prop = o.Prop
End Sub
End Class
]]></file>
</compilation>, s_typeWithMixedProperty, options:=TestOptions.DebugExe)
' There are no Errors, but setter is actually not overridden!!!
Dim validator = Sub(m As ModuleSymbol)
Dim p1 = m.GlobalNamespace.GetMember(Of PropertySymbol)("VBDerived.Prop")
Assert.True(p1.IsOverrides)
Dim baseP1 As PropertySymbol = p1.OverriddenProperty
Assert.True(baseP1.IsOverridable)
Assert.True(baseP1.GetMethod.IsOverridable)
Assert.False(baseP1.SetMethod.IsOverridable)
Dim p1Get = p1.GetMethod
Dim p1Set = p1.SetMethod
Assert.True(p1Get.IsOverrides)
Assert.Same(baseP1.GetMethod, p1Get.OverriddenMethod)
Assert.True(p1Set.IsOverrides)
Assert.Same(baseP1.SetMethod, p1Set.OverriddenMethod)
End Sub
CompileAndVerify(compilation1, expectedOutput:=
"Base_VirtGet_Set.Get
Base_VirtGet_Set.Set
VBDerived.Get
Base_VirtGet_Set.Get
Base_VirtGet_Set.Set", sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
<Fact()>
Public Sub BC31087ERR_CantSpecifyArraysOnBoth()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CantSpecifyArraysOnBoth">
<file name="a.vb"><![CDATA[
Module M
Sub Goo(ByVal x() As String())
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31087: Array modifiers cannot be specified on both a variable and its type.
Sub Goo(ByVal x() As String())
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31087ERR_CantSpecifyArraysOnBoth_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantSpecifyArraysOnBoth">
<file name="a.vb"><![CDATA[
Class C
Public Shared Sub Main()
Dim a()() As Integer = nothing
For Each x() As Integer() In a
Next
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected><![CDATA[
BC31087: Array modifiers cannot be specified on both a variable and its type.
For Each x() As Integer() In a
~~~~~~~~~
BC30332: Value of type 'Integer()' cannot be converted to 'Integer()()' because 'Integer' is not derived from 'Integer()'.
For Each x() As Integer() In a
~
]]></expected>)
End Sub
<WorkItem(540876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540876")>
<Fact>
Public Sub BC31088ERR_NotOverridableRequiresOverrides()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NotOverridableRequiresOverrides">
<file name="a.vb"><![CDATA[
Class C1
NotOverridable Sub Goo()
End Sub
Public NotOverridable Property F As Integer
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
NotOverridable Sub Goo()
~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Public NotOverridable Property F As Integer
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31089ERR_PrivateTypeOutsideType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PrivateTypeOutsideType">
<file name="a.vb"><![CDATA[
Namespace ns1
Private Module Mod1
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31089: Types declared 'Private' must be inside another type.
Private Module Mod1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31099ERR_BadPropertyAccessorFlags()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags">
<file name="a.vb"><![CDATA[
Class C
Property P
Static Get
Return Nothing
End Get
Shared Set
End Set
End Property
Property Q
Partial Get
Return Nothing
End Get
Default Set
End Set
End Property
Property R
MustInherit Get
Return Nothing
End Get
NotInheritable Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31099: Property accessors cannot be declared 'Static'.
Static Get
~~~~~~
BC31099: Property accessors cannot be declared 'Shared'.
Shared Set
~~~~~~
BC31099: Property accessors cannot be declared 'Partial'.
Partial Get
~~~~~~~
BC31099: Property accessors cannot be declared 'Default'.
Default Set
~~~~~~~
BC31099: Property accessors cannot be declared 'MustInherit'.
MustInherit Get
~~~~~~~~~~~
BC31099: Property accessors cannot be declared 'NotInheritable'.
NotInheritable Set
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31100ERR_BadPropertyAccessorFlagsRestrict()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlagsRestrict">
<file name="a.vb"><![CDATA[
Class C
Public Property P1
Get
Return Nothing
End Get
Public Set(ByVal value) ' P1 BC31100
End Set
End Property
Public Property P2
Get
Return Nothing
End Get
Friend Set(ByVal value)
End Set
End Property
Public Property P3
Get
Return Nothing
End Get
Protected Set(ByVal value)
End Set
End Property
Public Property P4
Get
Return Nothing
End Get
Protected Friend Set(ByVal value)
End Set
End Property
Public Property P5
Get
Return Nothing
End Get
Private Set(ByVal value)
End Set
End Property
Friend Property Q1
Public Get ' Q1 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q2
Friend Get ' Q2 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q3
Protected Get ' Q3 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q4
Protected Friend Get ' Q4 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q5
Private Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Protected Property R1
Get
Return Nothing
End Get
Public Set(ByVal value) ' R1 BC31100
End Set
End Property
Protected Property R2
Get
Return Nothing
End Get
Friend Set(ByVal value) ' R2 BC31100
End Set
End Property
Protected Property R3
Get
Return Nothing
End Get
Protected Set(ByVal value) ' R3 BC31100
End Set
End Property
Protected Property R4
Get
Return Nothing
End Get
Protected Friend Set(ByVal value) ' R4 BC31100
End Set
End Property
Protected Property R5
Get
Return Nothing
End Get
Private Set(ByVal value)
End Set
End Property
Protected Friend Property S1
Get
Return Nothing
End Get
Public Set(ByVal value) ' S1 BC31100
End Set
End Property
Protected Friend Property S2
Get
Return Nothing
End Get
Friend Set(ByVal value)
End Set
End Property
Protected Friend Property S3
Get
Return Nothing
End Get
Protected Set(ByVal value)
End Set
End Property
Protected Friend Property S4
Get
Return Nothing
End Get
Protected Friend Set(ByVal value) ' S4 BC31100
End Set
End Property
Protected Friend Property S5
Get
Return Nothing
End Get
Private Set(ByVal value)
End Set
End Property
Private Property T1
Public Get ' T1 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T2
Friend Get ' T2 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T3
Protected Get ' T3 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T4
Protected Friend Get ' T4 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T5
Private Get ' T5 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U1
Public Get ' U1 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U2
Friend Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U3
Protected Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U4
Protected Friend Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U5
Private Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Set(ByVal value) ' P1 BC31100
~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Get ' Q1 BC31100
~~~~~~
BC31100: Access modifier 'Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Friend Get ' Q2 BC31100
~~~~~~
BC31100: Access modifier 'Protected' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Get ' Q3 BC31100
~~~~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Get ' Q4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Set(ByVal value) ' R1 BC31100
~~~~~~
BC31100: Access modifier 'Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Friend Set(ByVal value) ' R2 BC31100
~~~~~~
BC31100: Access modifier 'Protected' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Set(ByVal value) ' R3 BC31100
~~~~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Set(ByVal value) ' R4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Set(ByVal value) ' S1 BC31100
~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Set(ByVal value) ' S4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Get ' T1 BC31100
~~~~~~
BC31100: Access modifier 'Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Friend Get ' T2 BC31100
~~~~~~
BC31100: Access modifier 'Protected' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Get ' T3 BC31100
~~~~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Get ' T4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Private' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Private Get ' T5 BC31100
~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Get ' U1 BC31100
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31101ERR_OnlyOneAccessorForGetSet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOneAccessorForGetSet">
<file name="a.vb"><![CDATA[
Class C
Property P
Private Get
Return Nothing
End Get
Protected Set(value)
End Set
End Property
Property Q
Friend Set
End Set
Friend Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31101: Access modifier can only be applied to either 'Get' or 'Set', but not both.
Protected Set(value)
~~~~~~~~~~~~~~~~~~~~
BC31101: Access modifier can only be applied to either 'Get' or 'Set', but not both.
Friend Get
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31104ERR_WriteOnlyNoAccessorFlag()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
WriteOnly Property Goo(ByVal x As Integer) As Integer
Private Set(ByVal value As Integer)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31104: 'WriteOnly' properties cannot have an access modifier on 'Set'.
Private Set(ByVal value As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31105ERR_ReadOnlyNoAccessorFlag()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
ReadOnly Property Goo(ByVal x As Integer) As Integer
Protected Get
Return 1
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31105: 'ReadOnly' properties cannot have an access modifier on 'Get'.
Protected Get
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31106ERR_BadPropertyAccessorFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags1">
<file name="a.vb"><![CDATA[
Class A
Overridable Property P
Overridable Property Q
Get
Return Nothing
End Get
Protected Set
End Set
End Property
End Class
Class B
Inherits A
NotOverridable Overrides Property P
Get
Return Nothing
End Get
Private Set
End Set
End Property
Public Overrides Property Q
Get
Return Nothing
End Get
Protected Set
End Set
End Property
End Class
MustInherit Class C
MustOverride Property P
End Class
Class D
Inherits C
NotOverridable Overrides Property P
Private Get
Return Nothing
End Get
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31106: Property accessors cannot be declared 'Private' in a 'NotOverridable' property.
Private Set
~~~~~~~
BC30266: 'Private NotOverridable Overrides Property Set P(Value As Object)' cannot override 'Public Overridable Property Set P(AutoPropertyValue As Object)' because they have different access levels.
Private Set
~~~
BC31106: Property accessors cannot be declared 'Private' in a 'NotOverridable' property.
Private Get
~~~~~~~
BC30266: 'Private NotOverridable Overrides Property Get P() As Object' cannot override 'Public MustOverride Property Get P() As Object' because they have different access levels.
Private Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31107ERR_BadPropertyAccessorFlags2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags2">
<file name="a.vb"><![CDATA[
Class C
Default Property P(o)
Private Get
Return Nothing
End Get
Set
End Set
End Property
End Class
Structure S
Default Property P(x, y)
Get
Return Nothing
End Get
Private Set
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31107: Property accessors cannot be declared 'Private' in a 'Default' property.
Private Get
~~~~~~~
BC31107: Property accessors cannot be declared 'Private' in a 'Default' property.
Private Set
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31108ERR_BadPropertyAccessorFlags3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags3">
<file name="a.vb"><![CDATA[
Class C
Overridable Property P
Private Get
Return Nothing
End Get
Set
End Set
End Property
Overridable Property Q
Get
Return Nothing
End Get
Private Set
End Set
End Property
Overridable Property R
Protected Get
Return Nothing
End Get
Set
End Set
End Property
Overridable Property S
Get
Return Nothing
End Get
Friend Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31108: Property cannot be declared 'Overridable' because it contains a 'Private' accessor.
Overridable Property P
~~~~~~~~~~~
BC31108: Property cannot be declared 'Overridable' because it contains a 'Private' accessor.
Overridable Property Q
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31127ERR_DuplicateAddHandlerDef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateAddHandlerDef">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31127: 'AddHandler' is already declared.
AddHandler(ByVal value As EventHandler)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31128ERR_DuplicateRemoveHandlerDef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateRemoveHandlerDef">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31128: 'RemoveHandler' is already declared.
RemoveHandler(ByVal value As EventHandler)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31129ERR_DuplicateRaiseEventDef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateRaiseEventDef">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31129: 'RaiseEvent' is already declared.
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31130ERR_MissingAddHandlerDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MissingAddHandlerDef1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31130: 'AddHandler' definition missing for event 'Public Event Click As EventHandler'.
Public Custom Event Click As EventHandler
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31131ERR_MissingRemoveHandlerDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MissingRemoveHandlerDef1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31131: 'RemoveHandler' definition missing for event 'Public Event Click As EventHandler'.
Public Custom Event Click As EventHandler
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31132ERR_MissingRaiseEventDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MissingRaiseEventDef1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31132: 'RaiseEvent' definition missing for event 'Public Event Click As EventHandler'.
Public Custom Event Click As EventHandler
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31133ERR_EventAddRemoveHasOnlyOneParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventAddRemoveHasOnlyOneParam">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler()
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31133: 'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.
AddHandler()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31134ERR_EventAddRemoveByrefParamIllegal()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventAddRemoveByrefParamIllegal">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByRef value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31134: 'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.
RemoveHandler(ByRef value As EventHandler)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31136ERR_AddRemoveParamNotEventType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AddRemoveParamNotEventType">
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Public Class M
Custom Event x As Action
AddHandler(ByVal value As Action(Of Integer))
End AddHandler
RemoveHandler(ByVal value)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.
AddHandler(ByVal value As Action(Of Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.
RemoveHandler(ByVal value)
~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31137ERR_RaiseEventShapeMismatch1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="RaiseEventShapeMismatch1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByRef sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'EventHandler'.
RaiseEvent(ByRef sender As Object, ByVal e As EventArgs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31138ERR_EventMethodOptionalParamIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventMethodOptionalParamIllegal1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(Optional ByVal value As EventHandler = Nothing)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'Optional'.
AddHandler(Optional ByVal value As EventHandler = Nothing)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31142ERR_ObsoleteInvalidOnEventMember()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ObsoleteInvalidOnEventMember">
<file name="a.vb"><![CDATA[
Imports System
Public Class C1
Custom Event x As Action
AddHandler(ByVal value As Action)
End AddHandler
RemoveHandler(ByVal value As Action)
End RemoveHandler
<Obsolete()>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.
<Obsolete()>
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31400ERR_BadStaticLocalInStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadStaticLocalInStruct">
<file name="a.vb"><![CDATA[
Structure S
Sub Goo()
Static x As Integer = 1
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31400: Local variables within methods of structures cannot be declared 'Static'.
Static x As Integer = 1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31400ERR_BadStaticLocalInStruct2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadStaticLocalInStruct2">
<file name="a.vb"><![CDATA[
Structure S
Sub Goo()
Static Static x As Integer
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31400: Local variables within methods of structures cannot be declared 'Static'.
Static Static x As Integer
~~~~~~
BC30178: Specifier is duplicated.
Static Static x As Integer
~~~~~~
BC42024: Unused local variable: 'x'.
Static Static x As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BadLocalspecifiers()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31400ERR_BadLocalspecifiers">
<file name="a.vb"><![CDATA[
Class S
Sub Goo()
Static Static a As Integer
Static Dim Dim b As Integer
Static Const Dim c As Integer
Private d As Integer
Private Private e As Integer
Private Const f As Integer
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30178: Specifier is duplicated.
Static Static a As Integer
~~~~~~
BC42024: Unused local variable: 'a'.
Static Static a As Integer
~
BC30178: Specifier is duplicated.
Static Dim Dim b As Integer
~~~
BC42024: Unused local variable: 'b'.
Static Dim Dim b As Integer
~
BC30246: 'Dim' is not valid on a local constant declaration.
Static Const Dim c As Integer
~~~
BC30438: Constants must have a value.
Static Const Dim c As Integer
~
BC30247: 'Private' is not valid on a local variable declaration.
Private d As Integer
~~~~~~~
BC42024: Unused local variable: 'd'.
Private d As Integer
~
BC30247: 'Private' is not valid on a local variable declaration.
Private Private e As Integer
~~~~~~~
BC30247: 'Private' is not valid on a local variable declaration.
Private Private e As Integer
~~~~~~~
BC42024: Unused local variable: 'e'.
Private Private e As Integer
~
BC30247: 'Private' is not valid on a local variable declaration.
Private Const f As Integer
~~~~~~~
BC30438: Constants must have a value.
Private Const f As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31401ERR_DuplicateLocalStatic1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalStatic1">
<file name="a.vb"><![CDATA[
Module M
Sub Main()
If True Then
Static x = 1
End If
If True Then
Static x = 1
End If
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31401: Static local variable 'x' is already declared.
Static x = 1
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31403ERR_ImportAliasConflictsWithType2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ImportAliasConflictsWithType2">
<file name="a.vb"><![CDATA[
Imports System = System
Module M
Sub Main()
System.Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31403: Imports alias 'System' conflicts with 'System' declared in the root namespace.
Imports System = System
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31404ERR_CantShadowAMustOverride1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantShadowAMustOverride1">
<file name="a.vb"><![CDATA[
MustInherit Class A
MustOverride Sub Goo(ByVal x As Integer)
End Class
MustInherit Class B
Inherits A
Shadows Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31404: 'Public Sub Goo()' cannot shadow a method declared 'MustOverride'.
Shadows Sub Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31407ERR_MultipleEventImplMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleEventImplMismatch3">
<file name="a.vb"><![CDATA[
Interface I1
Event evtTest1()
Event evtTest2()
End Interface
Class C1
Implements I1
Event evtTest3() Implements I1.evtTest1, I1.evtTest2
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31407: Event 'Public Event evtTest3 As I1.evtTest1EventHandler' cannot implement event 'I1.Event evtTest2()' because its delegate type does not match the delegate type of another event implemented by 'Public Event evtTest3 As I1.evtTest1EventHandler'.
Event evtTest3() Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
CompilationUtils.AssertTheseEmitDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_0()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Partial NotInheritable Class C1
End Class
Partial MustInherit Class C1
End Class
Partial MustInherit NotInheritable Class C1
End Class
Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30926: 'MustInherit' cannot be specified for partial type 'C1' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.
Partial MustInherit Class C1
~~
BC31408: 'MustInherit' and 'NotInheritable' cannot be combined.
Partial MustInherit NotInheritable Class C1
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538931")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit NotInheritable Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'MustInherit' and 'NotInheritable' cannot be combined.
MustInherit NotInheritable Class C1
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538931")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A1
Private Overridable Sub scen1()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Private' and 'Overridable' cannot be combined.
Private Overridable Sub scen1()
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Class C
ReadOnly WriteOnly Property P
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
Structure S
WriteOnly ReadOnly Property Q
Get
Return Nothing
End Get
Set
End Set
End Property
End Structure
Interface I
ReadOnly WriteOnly Property R
End Interface
Class D
Private Overridable Property S
Overridable Private Property T
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30635: 'ReadOnly' and 'WriteOnly' cannot be combined.
ReadOnly WriteOnly Property P
~~~~~~~~~
BC30022: Properties declared 'ReadOnly' cannot have a 'Set'.
Set
~~~
BC30635: 'ReadOnly' and 'WriteOnly' cannot be combined.
WriteOnly ReadOnly Property Q
~~~~~~~~
BC30023: Properties declared 'WriteOnly' cannot have a 'Get'.
Get
~~~
BC30635: 'ReadOnly' and 'WriteOnly' cannot be combined.
ReadOnly WriteOnly Property R
~~~~~~~~~
BC31408: 'Private' and 'Overridable' cannot be combined.
Private Overridable Property S
~~~~~~~~~~~
BC31408: 'Private' and 'Overridable' cannot be combined.
Overridable Private Property T
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(541025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541025")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A1
Private MustOverride Sub scen1()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Private' and 'MustOverride' cannot be combined.
Private MustOverride Sub scen1()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(542159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542159")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Infer On
Module M1
Sub Goo()
End Sub
End Module
MustInherit Class C1
MustOverride Sub goo()
Dim s = (New C2)
End Class
Class C2
Inherits C1
Overrides Shadows Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Overrides' and 'Shadows' cannot be combined.
Overrides Shadows Sub goo()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(837983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837983")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Module Module1
Sub main()
End Sub
End Module
Public Class Cls
Public ValueOfProperty1 As IEnumerable(Of String)
'COMPILEERROR: BC31408, "Iterator"
Public WriteOnly Iterator Property WriteOnlyPro1() As IEnumerable(Of String)
Set(value As IEnumerable(Of String))
ValueOfProperty1 = value
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Iterator' and 'WriteOnly' cannot be combined.
Public WriteOnly Iterator Property WriteOnlyPro1() As IEnumerable(Of String)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(837993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837993")>
<Fact>
Public Sub BC36938ERR_BadIteratorReturn_Property()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
' Bug51817: Incorrect Iterator Modifier in Source Code Causes VBC to exit incorrectly when Msbuild Project
Public Class Scenario2
Implements IEnumerator(Of Integer)
Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
Return True
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
End Sub
Public ReadOnly Iterator Property Current As Integer Implements IEnumerator(Of Integer).Current
'COMPILEERROR: BC36938 ,"Get"
Get
End Get
End Property
Public ReadOnly Iterator Property Current1 As Object Implements IEnumerator.Current
'COMPILEERROR: BC36938 ,"Get"
Get
End Get
End Property
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
End If
End If
Me.disposedValue = True
End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public ReadOnly Iterator Property Current As Integer Implements IEnumerator(Of Integer).Current
~~~~~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public ReadOnly Iterator Property Current1 As Object Implements IEnumerator.Current
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31409ERR_MustBeOverloads2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class C1
Overloads Sub goo(ByVal i As Integer)
End Sub
Sub goo(ByVal s As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: sub 'goo' must be declared 'Overloads' because another 'goo' is declared 'Overloads' or 'Overrides'.
Sub goo(ByVal s As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31409ERR_MustBeOverloads2_Mixed_Properties_And_Methods()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class OverloadedPropertiesBase
Overridable Overloads ReadOnly Property Prop(x As Integer) As String
Get
Return Nothing
End Get
End Property
Overridable ReadOnly Property Prop(x As String) As String
Get
Return Nothing
End Get
End Property
Overridable Overloads Function Prop(x As String) As String
Return Nothing
End Function
Shadows Function Prop(x As Integer) As Integer
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: property 'Prop' must be declared 'Overloads' because another 'Prop' is declared 'Overloads' or 'Overrides'.
Overridable ReadOnly Property Prop(x As String) As String
~~~~
BC30260: 'Prop' is already declared as 'Public Overridable Overloads ReadOnly Property Prop(x As Integer) As String' in this class.
Overridable Overloads Function Prop(x As String) As String
~~~~
BC30260: 'Prop' is already declared as 'Public Overridable Overloads ReadOnly Property Prop(x As Integer) As String' in this class.
Shadows Function Prop(x As Integer) As Integer
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31409ERR_MustBeOverloads2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class Base
Sub Method(x As Integer)
End Sub
Overloads Sub Method(x As String)
End Sub
End Class
Partial Class Derived1
Inherits Base
Shadows Sub Method(x As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: sub 'Method' must be declared 'Overloads' because another 'Method' is declared 'Overloads' or 'Overrides'.
Sub Method(x As Integer)
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' spec changed in Roslyn
<WorkItem(527642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527642")>
<Fact>
Public Sub BC31410ERR_CantOverloadOnMultipleInheritance()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverloadOnMultipleInheritance">
<file name="a.vb"><![CDATA[
Interface IA
Overloads Sub Goo(ByVal x As Integer)
End Interface
Interface IB
Overloads Sub Goo(ByVal x As String)
End Interface
Interface IC
Inherits IA, IB
Overloads Sub Goo()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31411ERR_MustOverridesInClass1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class C1
MustOverride Sub goo()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31411: 'C1' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Public Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31411ERR_MustOverridesInClass1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
MustOverride Property P
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31411: 'C' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Class C
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31413ERR_SynthMemberShadowsMustOverride5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SynthMemberShadowsMustOverride5">
<file name="a.vb"><![CDATA[
MustInherit Class clsTest1
MustOverride Sub add_e(ByVal ArgX As clsTest2.eEventHandler)
End Class
MustInherit Class clsTest2
Inherits clsTest1
Shadows Event e()
End Class
]]></file>
</compilation>)
' CONSIDER: Dev11 prints "Sub add_E", rather than "AddHandler Event e", but roslyn's behavior seems friendlier
' and more consistent with the way property accessors are displayed (in both dev11 and roslyn).
Dim expectedErrors1 = <errors><![CDATA[
BC31413: 'Public AddHandler Event e(obj As clsTest2.eEventHandler)', implicitly declared for event 'e', cannot shadow a 'MustOverride' method in the base class 'clsTest1'.
Shadows Event e()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540613")>
<Fact>
Public Sub BC31417ERR_CannotOverrideInAccessibleMember()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CannotOverrideInAccessibleMember">
<file name="a.vb"><![CDATA[
Class Cls1
Private Overridable Sub goo()
End Sub
End Class
Class Cls2
Inherits Cls1
Private Overrides Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Private' and 'Overridable' cannot be combined.
Private Overridable Sub goo()
~~~~~~~~~~~
BC31417: 'Private Overrides Sub goo()' cannot override 'Private Sub goo()' because it is not accessible in this context.
Private Overrides Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31418ERR_HandlesSyntaxInModule()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="HandlesSyntaxInModule">
<file name="a.vb"><![CDATA[
Option Strict Off
Module M
Sub Bar() Handles Me.Goo
End Sub
Event Goo()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31418: 'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.
Sub Bar() Handles Me.Goo
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31420ERR_ClashWithReservedEnumMember1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClashWithReservedEnumMember1">
<file name="a.vb"><![CDATA[
Structure S
Public Enum InterfaceColors
value__
End Enum
End Structure
Class c1
Public Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31420: 'value__' conflicts with the reserved member by this name that is implicitly declared in all enums.
value__
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539947")>
<Fact>
Public Sub BC31420ERR_ClashWithReservedEnumMember2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ClashWithReservedEnumMember1">
<file name="a.vb"><![CDATA[
Module M
Public Enum InterfaceColors
Value__
End Enum
End Module
Class c1
Public Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31420: 'Value__' conflicts with the reserved member by this name that is implicitly declared in all enums.
Value__
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31422ERR_BadUseOfVoid_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C1
Function scen1() As Void
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31422: 'System.Void' can only be used in a GetType expression.
Function scen1() As Void
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC31422ERR_BadUseOfVoid_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P As System.Void
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31422: 'System.Void' can only be used in a GetType expression.
Property P As System.Void
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
CompilationUtils.AssertTheseEmitDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC31423ERR_EventImplMismatch5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventImplMismatch5">
<file name="a.vb"><![CDATA[
Imports System
Public Interface IA
Event E()
End Interface
Public Class A
Implements IA
Public Event E As Action Implements IA.E
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31423: Event 'Public Event E As Action' cannot implement event 'Event E()' on interface 'IA' because their delegate types 'Action' and 'IA.EEventHandler' do not match.
Public Event E As Action Implements IA.E
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539760")>
<Fact>
Public Sub BC31429ERR_MetadataMembersAmbiguous3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MetadataMembersAmbiguous3">
<file name="a.vb"><![CDATA[
Class Base
Public Shared Sub Main
Dim a As Integer = 5
Dim b As Base = New Derived(a)
End Sub
Private Class Derived
Inherits Base
Private a As Integer
Public Sub New(a As Integer)
Me.a = a
End Sub
Public Sub New()
End Sub
End Class
End Class
Class Base
Public Shared Sub Main
Dim a As Integer = 5
Dim b As Base = New Derived(a)
End Sub
Private Class Derived
Inherits Base
Private a As Integer
Public Sub New(a As Integer)
Me.a = a
End Sub
Public Sub New()
End Sub
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30521: Overload resolution failed because no accessible 'New' is most specific for these arguments:
'Public Sub New(a As Integer)': Not most specific.
'Public Sub New(a As Integer)': Not most specific.
Dim b As Base = New Derived(a)
~~~~~~~
BC31429: 'a' is ambiguous because multiple kinds of members with this name exist in class 'Base.Derived'.
Me.a = a
~~~~
BC30179: class 'Base' and class 'Base' conflict in namespace '<Default>'.
Class Base
~~~~
BC30521: Overload resolution failed because no accessible 'New' is most specific for these arguments:
'Public Sub New(a As Integer)': Not most specific.
'Public Sub New(a As Integer)': Not most specific.
Dim b As Base = New Derived(a)
~~~~~~~
BC30179: class 'Derived' and class 'Derived' conflict in class 'Base'.
Private Class Derived
~~~~~~~
BC31429: 'a' is ambiguous because multiple kinds of members with this name exist in class 'Base.Derived'.
Me.a = a
~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1">
<file name="a.vb"><![CDATA[
Class C1
Partial Public Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Public'.
Partial Public Sub goo()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1a">
<file name="a.vb"><![CDATA[
Class C1
Partial Protected Overridable Sub goo()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Protected'.
Partial Protected Overridable Sub goo()
~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Overridable'.
Partial Protected Overridable Sub goo()
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1b">
<file name="a.vb"><![CDATA[
Class C1
Partial Protected Friend Sub M1()
End Sub
Partial Friend Protected Overridable Sub M2()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Protected Friend'.
Partial Protected Friend Sub M1()
~~~~~~~~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Friend Protected'.
Partial Friend Protected Overridable Sub M2()
~~~~~~~~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Overridable'.
Partial Friend Protected Overridable Sub M2()
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1c()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1c">
<file name="a.vb"><![CDATA[
Class C1
Partial Protected Overridable Friend Sub M()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Protected'.
Partial Protected Overridable Friend Sub M()
~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Overridable'.
Partial Protected Overridable Friend Sub M()
~~~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Friend'.
Partial Protected Overridable Friend Sub M()
~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31432ERR_PartialMethodsMustBePrivate()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialMethodsMustBePrivate">
<file name="a.vb"><![CDATA[
Class C1
Partial Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31432: Partial methods must be declared 'Private'.
Partial Sub Goo()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2">
<file name="a.vb"><![CDATA[
Class C1
Partial Private Sub Goo()
End Sub
Partial Private Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31433: Method 'Goo' cannot be declared 'Partial' because only one method 'Goo' can be marked 'Partial'.
Partial Private Sub Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2a">
<file name="b.vb"><![CDATA[
Class C1
Partial Private Sub Goo()
End Sub
Partial Private Sub GoO()
End Sub
End Class
]]></file>
<file name="a.vb"><![CDATA[
Partial Class C1
Partial Private Sub goo()
End Sub
Partial Private Sub GOO()
End Sub
End Class
]]></file>
</compilation>)
' note the exact methods errors are reported on
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31433: Method 'goo' cannot be declared 'Partial' because only one method 'goo' can be marked 'Partial'.
Partial Private Sub goo()
~~~
BC31433: Method 'GOO' cannot be declared 'Partial' because only one method 'GOO' can be marked 'Partial'.
Partial Private Sub GOO()
~~~
BC31433: Method 'GoO' cannot be declared 'Partial' because only one method 'GoO' can be marked 'Partial'.
Partial Private Sub GoO()
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2b">
<file name="a.vb"><![CDATA[
Class CLS
Partial Private Shared Sub PS(a As Integer)
End Sub
Partial Private Shared Sub Ps(a As Integer)
End Sub
Private Shared Sub pS(a As Integer)
End Sub
Private Shared Sub ps(a As Integer)
End Sub
Public Sub PS(a As Integer)
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30269: 'Private Shared Sub PS(a As Integer)' has multiple definitions with identical signatures.
Partial Private Shared Sub PS(a As Integer)
~~
BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'.
Partial Private Shared Sub Ps(a As Integer)
~~
BC31434: Method 'ps' cannot implement partial method 'ps' because 'ps' already implements it. Only one method can implement a partial method.
Private Shared Sub ps(a As Integer)
~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2c()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2c">
<file name="a.vb"><![CDATA[
Class CLS
Partial Private Shared Sub PS(a As Integer)
End Sub
Partial Private Overloads Shared Sub Ps(a As Integer)
End Sub
Private Overloads Shared Sub ps(a As Integer)
End Sub
Private Shared Sub pS(a As Integer)
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31409: sub 'PS' must be declared 'Overloads' because another 'PS' is declared 'Overloads' or 'Overrides'.
Partial Private Shared Sub PS(a As Integer)
~~
BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'.
Partial Private Overloads Shared Sub Ps(a As Integer)
~~
BC31409: sub 'pS' must be declared 'Overloads' because another 'pS' is declared 'Overloads' or 'Overrides'.
Private Shared Sub pS(a As Integer)
~~
BC31434: Method 'pS' cannot implement partial method 'pS' because 'pS' already implements it. Only one method can implement a partial method.
Private Shared Sub pS(a As Integer)
~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31434ERR_OnlyOneImplementingMethodAllowed3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOneImplementingMethodAllowed3">
<file name="a.vb"><![CDATA[
Public Class C1
Partial Private Sub GoO2()
End Sub
End Class
Partial Public Class C1
Private Sub GOo2()
End Sub
End Class
Partial Public Class C1
Private Sub Goo2()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31434: Method 'Goo2' cannot implement partial method 'Goo2' because 'Goo2' already implements it. Only one method can implement a partial method.
Private Sub Goo2()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31434ERR_OnlyOneImplementingMethodAllowed3a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOneImplementingMethodAllowed3a">
<file name="b.vb"><![CDATA[
Public Class C1
Partial Private Sub GoO2()
End Sub
End Class
Partial Public Class C1
Private Sub GOo2()
End Sub
End Class
Partial Public Class C1
Private Sub Goo2()
End Sub
End Class
]]></file>
<file name="a.vb"><![CDATA[
Partial Public Class C1
Private Sub GOO2()
End Sub
End Class
Partial Public Class C1
Private Sub GoO2()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31434: Method 'GOO2' cannot implement partial method 'GOO2' because 'GOO2' already implements it. Only one method can implement a partial method.
Private Sub GOO2()
~~~~
BC31434: Method 'GoO2' cannot implement partial method 'GoO2' because 'GoO2' already implements it. Only one method can implement a partial method.
Private Sub GoO2()
~~~~
BC31434: Method 'Goo2' cannot implement partial method 'Goo2' because 'Goo2' already implements it. Only one method can implement a partial method.
Private Sub Goo2()
~~~~
]]></errors>
' note the exact methods errors are reported on
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31437ERR_PartialMethodsMustBeSub1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialMethodsMustBeSub1">
<file name="a.vb"><![CDATA[
Class C1
Partial Function Goo() As Boolean
Return True
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC31437: 'Goo' cannot be declared 'Partial' because partial methods must be Subs.
Partial Function Goo() As Boolean
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31437ERR_PartialMethodsMustBeSub2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialMethodsMustBeSub2">
<file name="a.vb"><![CDATA[
Class C1
Partial Private Sub Goo()
End Sub
Partial Function Goo() As Boolean
Return True
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC30301: 'Private Sub Goo()' and 'Public Function Goo() As Boolean' cannot overload each other because they differ only by return types.
Partial Private Sub Goo()
~~~
BC31437: 'Goo' cannot be declared 'Partial' because partial methods must be Subs.
Partial Function Goo() As Boolean
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31438ERR_PartialMethodGenericConstraints2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
End Interface
Interface IB
End Interface
Class C(Of X)
' Different constraints.
Partial Private Sub A1(Of T As Structure)()
End Sub
Private Sub A1(Of T As Class)()
End Sub
Partial Private Sub A2(Of T As Structure, U As IA(Of T))()
End Sub
Private Sub A2(Of T As Structure, U As IB)()
End Sub
Partial Private Sub A3(Of T As IA(Of T))()
End Sub
Private Sub A3(Of T As IA(Of IA(Of T)))()
End Sub
Partial Private Sub A4(Of T As {Structure, IA(Of T)}, U)()
End Sub
Private Sub A4(Of T As {Structure, IA(Of U)}, U)()
End Sub
' Additional constraints.
Partial Private Sub B1(Of T)()
End Sub
Private Sub B1(Of T As New)()
End Sub
Partial Private Sub B2(Of T As {X, New})()
End Sub
Private Sub B2(Of T As {X, Class, New})()
End Sub
Partial Private Sub B3(Of T As IA(Of T), U)()
End Sub
Private Sub B3(Of T As {IB, IA(Of T)}, U)()
End Sub
' Missing constraints.
Partial Private Sub C1(Of T As Class)()
End Sub
Private Sub C1(Of T)()
End Sub
Partial Private Sub C2(Of T As {Class, New})()
End Sub
Private Sub C2(Of T As {Class})()
End Sub
Partial Private Sub C3(Of T, U As {IB, IA(Of T)})()
End Sub
Private Sub C3(Of T, U As IA(Of T))()
End Sub
' Same constraints, different order.
Private Sub D1(Of T As {IA(Of T), IB})()
End Sub
Partial Private Sub D1(Of T As {IB, IA(Of T)})()
End Sub
Private Sub D2(Of T, U, V As {T, U, X})()
End Sub
Partial Private Sub D2(Of T, U, V As {U, X, T})()
End Sub
' Different constraint clauses.
Private Sub E1(Of T, U As T)()
End Sub
Partial Private Sub E1(Of T As Class, U)()
End Sub
' Additional constraint clause.
Private Sub F1(Of T As Class, U)()
End Sub
Partial Private Sub F1(Of T As Class, U As T)()
End Sub
' Missing constraint clause.
Private Sub G1(Of T As Class, U As T)()
End Sub
Partial Private Sub G1(Of T As Class, U)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31438: Method 'A1' does not have the same generic constraints as the partial method 'A1'.
Private Sub A1(Of T As Class)()
~~
BC31438: Method 'A2' does not have the same generic constraints as the partial method 'A2'.
Private Sub A2(Of T As Structure, U As IB)()
~~
BC31438: Method 'A3' does not have the same generic constraints as the partial method 'A3'.
Private Sub A3(Of T As IA(Of IA(Of T)))()
~~
BC31438: Method 'A4' does not have the same generic constraints as the partial method 'A4'.
Private Sub A4(Of T As {Structure, IA(Of U)}, U)()
~~
BC31438: Method 'B1' does not have the same generic constraints as the partial method 'B1'.
Private Sub B1(Of T As New)()
~~
BC31438: Method 'B2' does not have the same generic constraints as the partial method 'B2'.
Private Sub B2(Of T As {X, Class, New})()
~~
BC31438: Method 'B3' does not have the same generic constraints as the partial method 'B3'.
Private Sub B3(Of T As {IB, IA(Of T)}, U)()
~~
BC31438: Method 'C1' does not have the same generic constraints as the partial method 'C1'.
Private Sub C1(Of T)()
~~
BC31438: Method 'C2' does not have the same generic constraints as the partial method 'C2'.
Private Sub C2(Of T As {Class})()
~~
BC31438: Method 'C3' does not have the same generic constraints as the partial method 'C3'.
Private Sub C3(Of T, U As IA(Of T))()
~~
BC31438: Method 'E1' does not have the same generic constraints as the partial method 'E1'.
Private Sub E1(Of T, U As T)()
~~
BC31438: Method 'F1' does not have the same generic constraints as the partial method 'F1'.
Private Sub F1(Of T As Class, U)()
~~
BC31438: Method 'G1' does not have the same generic constraints as the partial method 'G1'.
Private Sub G1(Of T As Class, U As T)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31438ERR_PartialMethodGenericConstraints2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Class Base(Of T As Class)
Class Derived
Inherits Base(Of Base(Of String))
Partial Private Sub Goo(Of S As {Base(Of String), IComparable})(i As Integer)
End Sub
Private Sub GOO(Of S As {IComparable, Base(Of IDisposable)})(i As Integer)
End Sub
Private Sub GoO(Of s As {IComparable, Base(Of IEnumerable)})(i As Integer)
End Sub
Private Sub gOo(Of s As {IComparable, Base(Of IComparable)})(i As Integer)
End Sub
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31438: Method 'GOO' does not have the same generic constraints as the partial method 'Goo'.
Private Sub GOO(Of S As {IComparable, Base(Of IDisposable)})(i As Integer)
~~~
BC31434: Method 'GoO' cannot implement partial method 'GoO' because 'GoO' already implements it. Only one method can implement a partial method.
Private Sub GoO(Of s As {IComparable, Base(Of IEnumerable)})(i As Integer)
~~~
BC31434: Method 'gOo' cannot implement partial method 'gOo' because 'gOo' already implements it. Only one method can implement a partial method.
Private Sub gOo(Of s As {IComparable, Base(Of IComparable)})(i As Integer)
~~~
]]></errors>)
' NOTE: Dev10 reports three BC31438 in this case
End Sub
<Fact()>
Public Sub BC31438ERR_PartialMethodGenericConstraints2b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Public Class Base(Of T As Class)
Public Class Derived
Inherits Base(Of Base(Of String))
Partial Private Sub Goo(Of S As {Base(Of String), IComparable})(i As Integer)
End Sub
Private Sub gOo(Of s As {IComparable, C.I})(i As Integer)
End Sub
Partial Private Sub Bar(Of S As {C.I})(i As Integer)
End Sub
Private Sub bar(Of s As {C.I})(i As Integer)
End Sub
Public Class C
Interface I
End Interface
End Class
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31438: Method 'gOo' does not have the same generic constraints as the partial method 'Goo'.
Private Sub gOo(Of s As {IComparable, C.I})(i As Integer)
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31439ERR_PartialDeclarationImplements1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialDeclarationImplements1">
<file name="a.vb"><![CDATA[
Imports System
Class A
Implements IDisposable
Partial Private Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Sub Dispose()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'A' must implement 'Sub Dispose()' for interface 'IDisposable'.
Implements IDisposable
~~~~~~~~~~~
BC31439: Partial method 'Dispose' cannot use the 'Implements' keyword.
Partial Private Sub Dispose() Implements IDisposable.Dispose
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31439ERR_PartialDeclarationImplements1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialDeclarationImplements1a">
<file name="a.vb"><![CDATA[
Imports System
Class A
Implements IDisposable
Partial Private Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30149: Class 'A' must implement 'Sub Dispose()' for interface 'IDisposable'.
Implements IDisposable
~~~~~~~~~~~
BC31439: Partial method 'Dispose' cannot use the 'Implements' keyword.
Partial Private Sub Dispose() Implements IDisposable.Dispose
~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31441ERR_ImplementationMustBePrivate2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementationMustBePrivate2">
<file name="a.vb"><![CDATA[
Partial Class C1
Partial Private Sub GOO()
End Sub
End Class
Partial Class C1
Sub GOO()
'HELLO
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31441: Method 'GOO' must be declared 'Private' in order to implement partial method 'GOO'.
Sub GOO()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31441ERR_ImplementationMustBePrivate2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementationMustBePrivate2a">
<file name="a.vb"><![CDATA[
Partial Class C1
Partial Private Sub GOO()
End Sub
End Class
Partial Class C1
Sub Goo()
End Sub
Private Sub gOO()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31441: Method 'Goo' must be declared 'Private' in order to implement partial method 'GOO'.
Sub Goo()
~~~
BC31434: Method 'gOO' cannot implement partial method 'gOO' because 'gOO' already implements it. Only one method can implement a partial method.
Private Sub gOO()
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31442ERR_PartialMethodParamNamesMustMatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialMethodParamNamesMustMatch3">
<file name="a.vb"><![CDATA[
Module M
Partial Private Sub Goo(ByVal x As Integer)
End Sub
Private Sub Goo(ByVal y As Integer)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31442: Parameter name 'y' does not match the name of the corresponding parameter, 'x', defined on the partial method declaration 'Goo'.
Private Sub Goo(ByVal y As Integer)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31442ERR_PartialMethodParamNamesMustMatch3a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialMethodParamNamesMustMatch3a">
<file name="a.vb"><![CDATA[
Module M
Partial Private Sub Goo(ByVal x As Integer, a As Integer)
End Sub
Private Sub Goo(ByVal x As Integer, b As Integer)
End Sub
Private Sub Goo(ByVal y As Integer, b As Integer)
End Sub
Private Sub Goo(ByVal y As Integer, b As Integer)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31442: Parameter name 'b' does not match the name of the corresponding parameter, 'a', defined on the partial method declaration 'Goo'.
Private Sub Goo(ByVal x As Integer, b As Integer)
~
BC31434: Method 'Goo' cannot implement partial method 'Goo' because 'Goo' already implements it. Only one method can implement a partial method.
Private Sub Goo(ByVal y As Integer, b As Integer)
~~~
BC31434: Method 'Goo' cannot implement partial method 'Goo' because 'Goo' already implements it. Only one method can implement a partial method.
Private Sub Goo(ByVal y As Integer, b As Integer)
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31443ERR_PartialMethodTypeParamNameMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialMethodTypeParamNameMismatch3">
<file name="a.vb"><![CDATA[
Module M
Partial Private Sub Goo(Of S)()
End Sub
Private Sub Goo(Of T)()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31443: Name of type parameter 'T' does not match 'S', the corresponding type parameter defined on the partial method declaration 'Goo'.
Private Sub Goo(Of T)()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31503ERR_AttributeMustBeClassNotStruct1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeMustBeClassNotStruct1">
<file name="a.vb"><![CDATA[
Structure s1
End Structure
<s1()>
Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31503: 's1' cannot be used as an attribute because it is not a class.
<s1()>
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540625")>
<Fact>
Public Sub BC31504ERR_AttributeMustInheritSysAttr()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeMustInheritSysAttr">
<file name="at31504.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public Class MyAttribute
'Inherits Attribute
End Class
<MyAttribute()>
Class Test
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttributeMustInheritSysAttr, "MyAttribute").WithArguments("MyAttribute"))
End Sub
<WorkItem(540628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540628")>
<Fact>
Public Sub BC31506ERR_AttributeCannotBeAbstract()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeCannotBeAbstract">
<file name="at31506.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public MustInherit Class MyAttribute
Inherits Attribute
Public Sub New()
End Sub
End Class
<My()>
Class Goo
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttributeCannotBeAbstract, "My").WithArguments("MyAttribute"))
End Sub
<WorkItem(540628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540628")>
<Fact>
Public Sub BC31507ERR_AttributeCannotHaveMustOverride()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeCannotHaveMustOverride">
<file name="at31500.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public MustInherit Class MyAttribute
Inherits Attribute
Public Sub New()
End Sub
'MustOverride Property AbsProp As Byte
Public MustOverride Sub AbsSub()
End Class
<My()>
Class Goo
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttributeCannotBeAbstract, "My").WithArguments("MyAttribute"))
End Sub
<Fact>
Public Sub BC31512ERR_STAThreadAndMTAThread0()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="STAThreadAndMTAThread0">
<file name="a.vb"><![CDATA[
Imports System
Class C1
<MTAThread>
<STAThread>
Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31512: 'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.
Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' BC31523ERR_DllImportNotLegalOnDeclare
' BC31524ERR_DllImportNotLegalOnGetOrSet
' BC31526ERR_DllImportOnGenericSubOrFunction
' see AttributeTests
<Fact()>
Public Sub BC31527ERR_ComClassOnGeneric()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassOnGeneric">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic
<ComClass()>
Class C1(Of T)
Sub GOO(ByVal s As T)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.
Class C1(Of T)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' BC31529ERR_DllImportOnInstanceMethod
' BC31530ERR_DllImportOnInterfaceMethod
' BC31531ERR_DllImportNotLegalOnEventMethod
' see AttributeTests
<Fact, WorkItem(1116455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116455")>
Public Sub BC31534ERR_FriendAssemblyBadArguments()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="FriendAssemblyBadArguments">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleTo("Test, Version=*")> ' ok
<Assembly: InternalsVisibleTo("Test, PublicKeyToken=*")> ' ok
<Assembly: InternalsVisibleTo("Test, Culture=*")> ' ok
<Assembly: InternalsVisibleTo("Test, Retargetable=*")> ' ok
<Assembly: InternalsVisibleTo("Test, ContentType=*")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=.")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=..")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=...")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=1")> ' error
<Assembly: InternalsVisibleTo("Test, Version=1.*")> ' error
<Assembly: InternalsVisibleTo("Test, Version=1.1.*")> ' error
<Assembly: InternalsVisibleTo("Test, Version=1.1.1.*")> ' error
<Assembly: InternalsVisibleTo("Test, ProcessorArchitecture=MSIL")> ' error
<Assembly: InternalsVisibleTo("Test, CuLTure=EN")> ' error
<Assembly: InternalsVisibleTo("Test, PublicKeyToken=null")> ' ok
]]></file>
</compilation>, {SystemCoreRef})
' Tested against Dev12
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1"")").WithArguments("Test, Version=1").WithLocation(11, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1.*"")").WithArguments("Test, Version=1.*").WithLocation(12, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1.1.*"")").WithArguments("Test, Version=1.1.*").WithLocation(13, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1.1.1.*"")").WithArguments("Test, Version=1.1.1.*").WithLocation(14, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")").WithArguments("Test, ProcessorArchitecture=MSIL").WithLocation(15, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, CuLTure=EN"")").WithArguments("Test, CuLTure=EN").WithLocation(16, 2))
End Sub
<Fact>
Public Sub BC31537ERR_FriendAssemblyNameInvalid()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="FriendAssemblyNameInvalid">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleTo("' '")> ' ok
<Assembly: InternalsVisibleTo("\t\r\n;a")> ' ok (whitespace escape)
<Assembly: InternalsVisibleTo("\u1234;a")> ' ok (assembly name Unicode escape)
<Assembly: InternalsVisibleTo("' a '")> ' ok
<Assembly: InternalsVisibleTo("\u1000000;a")> ' invalid escape
<Assembly: InternalsVisibleTo("a'b'c")> ' quotes in the middle
<Assembly: InternalsVisibleTo("Test, PublicKey=Null")>
<Assembly: InternalsVisibleTo("Test, Bar")>
<Assembly: InternalsVisibleTo("Test, Version")>
]]></file>
</compilation>, {SystemCoreRef})
' Tested against Dev12
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""\u1000000;a"")").WithArguments("\u1000000;a").WithLocation(6, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""a'b'c"")").WithArguments("a'b'c").WithLocation(7, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""Test, PublicKey=Null"")").WithArguments("Test, PublicKey=Null").WithLocation(8, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""Test, Bar"")").WithArguments("Test, Bar").WithLocation(9, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""Test, Version"")").WithArguments("Test, Version").WithLocation(10, 2))
End Sub
<Fact()>
Public Sub BC31549ERR_PIAHasNoAssemblyGuid1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"/>
</compilation>,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
compilation2.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC31549: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute.
]]></errors>)
End Sub
<Fact()>
Public Sub BC31553ERR_PIAHasNoTypeLibAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"><![CDATA[
<Assembly: System.Runtime.InteropServices.Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"/>
</compilation>,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
compilation2.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC31553: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute.
]]></errors>)
End Sub
<Fact()>
Public Sub BC31553ERR_PIAHasNoTypeLibAttribute1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"/>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"/>
</compilation>,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
compilation2.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC31549: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute.
BC31553: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute.
]]></errors>)
End Sub
<Fact>
Public Sub BC32040ERR_BadFlagsOnNewOverloads()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadFlagsOnNewOverloads">
<file name="a.vb"><![CDATA[
class C1
End class
Friend Class C2
Inherits C1
Public Overloads Sub New(ByVal x As Integer)
MyBase.New(CType (x, Short))
End Sub
Public Sub New(ByVal x As Date)
MyBase.New(1)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32040: The 'Overloads' keyword is used to overload inherited members; do not use the 'Overloads' keyword when overloading 'Sub New'.
Public Overloads Sub New(ByVal x As Integer)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32041ERR_TypeCharOnGenericParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeCharOnGenericParam">
<file name="a.vb"><![CDATA[
Structure S(Of T@)
Sub M(Of U@)()
End Sub
End Structure
Interface I(Of T#)
Sub M(Of U#)()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32041: Type character cannot be used in a type parameter declaration.
Structure S(Of T@)
~~
BC32041: Type character cannot be used in a type parameter declaration.
Sub M(Of U@)()
~~
BC32041: Type character cannot be used in a type parameter declaration.
Interface I(Of T#)
~~
BC32041: Type character cannot be used in a type parameter declaration.
Sub M(Of U#)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32042ERR_TooFewGenericArguments1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TooFewGenericArguments1">
<file name="a.vb"><![CDATA[
Structure S1(Of t)
End Structure
Class c1
Dim x3 As S1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32042: Too few type arguments to 'S1(Of t)'.
Dim x3 As S1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32043ERR_TooManyGenericArguments1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TooManyGenericArguments1">
<file name="a.vb"><![CDATA[
Structure S1(Of arg1)
End Structure
Class c1
Dim scen2 As New S1(Of String, Integer, Double, Decimal)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32043: Too many type arguments to 'S1(Of arg1)'.
Dim scen2 As New S1(Of String, Integer, Double, Decimal)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32044ERR_GenericConstraintNotSatisfied2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T1, T2)
Sub M(Of U As {T1, T2})()
M(Of T1)()
M(Of T2)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32044: Type argument 'T1' does not inherit from or implement the constraint type 'T2'.
M(Of T1)()
~~~~~~~~
BC32044: Type argument 'T2' does not inherit from or implement the constraint type 'T1'.
M(Of T2)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32044ERR_GenericConstraintNotSatisfied2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Module M
Sub Main()
Goo(Function(x As String) x, Function(x As Object) x)
End Sub
Sub Goo(Of T, S As T)(ByVal x As T, ByVal y As S)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32044: Type argument 'Function <generated method>(x As Object) As Object' does not inherit from or implement the constraint type 'Function <generated method>(x As String) As String'.
Goo(Function(x As String) x, Function(x As Object) x)
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32047ERR_MultipleClassConstraints1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleClassConstraints1">
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
Inherits A
End Class
Class C
Inherits B
End Class
Interface IA(Of T, U As {A, T, B})
End Interface
Interface IB
Sub M(Of T As {A, B, C, New})()
End Interface
MustInherit Class D(Of T, U)
MustOverride Sub M(Of V As {T, U, C, New})()
End Class
MustInherit Class E
Inherits D(Of A, B)
Public Overrides Sub M(Of V As {A, B, C, New})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32047: Type parameter 'U' can only have one constraint that is a class.
Interface IA(Of T, U As {A, T, B})
~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Sub M(Of T As {A, B, C, New})()
~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Sub M(Of T As {A, B, C, New})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32048ERR_ConstNotClassInterfaceOrTypeParam1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ConstNotClassInterfaceOrTypeParam1">
<file name="a.vb"><![CDATA[
Class A
End Class
Delegate Sub D()
Structure S
End Structure
Enum E
A
End Enum
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
End Class
MustInherit Class C2(Of T1, T2, T3, T4, T5)
MustOverride Sub M(Of U1 As T1, U2 As T2, U3 As T3, U4 As T4, U5 As T5)()
End Class
MustInherit Class C3
Inherits C2(Of A(), D, S, E, Unknown)
MustOverride Overrides Sub M(Of U1 As A(), U2 As D, U3 As S, U4 As E, U5 As Unknown)()
End Class
Class C3(Of T As {S(), E()})
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32048: Type constraint 'A()' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~~~
BC32048: Type constraint 'D' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~
BC32048: Type constraint 'S' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~
BC32048: Type constraint 'E' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~
BC30002: Type 'Unknown' is not defined.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~~~~~~~
BC30002: Type 'Unknown' is not defined.
Inherits C2(Of A(), D, S, E, Unknown)
~~~~~~~
BC30002: Type 'Unknown' is not defined.
MustOverride Overrides Sub M(Of U1 As A(), U2 As D, U3 As S, U4 As E, U5 As Unknown)()
~~~~~~~
BC32048: Type constraint 'S()' must be either a class, interface or type parameter.
Class C3(Of T As {S(), E()})
~~~
BC32048: Type constraint 'E()' must be either a class, interface or type parameter.
Class C3(Of T As {S(), E()})
~~~
BC32119: Constraint 'E()' conflicts with the constraint 'S()' already specified for type parameter 'T'.
Class C3(Of T As {S(), E()})
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for duplicate type parameters
<Fact>
Public Sub BC32049ERR_DuplicateTypeParamName1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
class c(of tT, TT, Tt)
end class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32049: Type parameter already declared with name 'TT'.
class c(of tT, TT, Tt)
~~
BC32049: Type parameter already declared with name 'Tt'.
class c(of tT, TT, Tt)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32054ERR_ShadowingGenericParamWithMember1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingGenericParamWithMember1">
<file name="a.vb"><![CDATA[
Partial Structure S1(Of membername)
Function membername() As String
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32054: 'membername' has the same name as a type parameter.
Function membername() As String
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32055ERR_GenericParamBase2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericParamBase2">
<file name="a.vb"><![CDATA[
Class C1(Of T)
Class cls3
Inherits T
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32055: Class 'cls3' cannot inherit from a type parameter.
Inherits T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32055ERR_GenericParamBase2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericParamBase2">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
Class c1
Inherits T
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32055: Class 'c1' cannot inherit from a type parameter.
Inherits T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32056ERR_ImplementsGenericParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeParamQualifierDisallowed">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
Class c1
Implements T
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32056: Type parameter not allowed in 'Implements' clause.
Implements T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32060ERR_ClassConstraintNotInheritable1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
NotInheritable Class A
End Class
Class B
End Class
Interface IA(Of T As {A, B})
End Interface
Interface IB(Of T)
Sub M(Of U As T)()
End Interface
Class C
Implements IB(Of A)
Private Sub M(Of U As A)() Implements IB(Of A).M
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32060: Type constraint cannot be a 'NotInheritable' class.
Interface IA(Of T As {A, B})
~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Interface IA(Of T As {A, B})
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32061ERR_ConstraintIsRestrictedType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Interface I(Of T As Object, U As System.ValueType)
End Interface
Structure S(Of T As System.Enum, U As System.Array)
End Structure
Delegate Sub D(Of T As System.Delegate, U As System.MulticastDelegate)()
Class C(Of T As {Object, A}, U As {A, Object})
End Class
Class A(Of T1, T2, T3, T4, T5, T6)
End Class
Class B
Inherits A(Of Object, System.ValueType, System.Enum, System.Array, System.Delegate, System.MulticastDelegate)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32061: 'Object' cannot be used as a type constraint.
Interface I(Of T As Object, U As System.ValueType)
~~~~~~
BC32061: 'ValueType' cannot be used as a type constraint.
Interface I(Of T As Object, U As System.ValueType)
~~~~~~~~~~~~~~~~
BC32061: '[Enum]' cannot be used as a type constraint.
Structure S(Of T As System.Enum, U As System.Array)
~~~~~~~~~~~
BC32061: 'Array' cannot be used as a type constraint.
Structure S(Of T As System.Enum, U As System.Array)
~~~~~~~~~~~~
BC32061: '[Delegate]' cannot be used as a type constraint.
Delegate Sub D(Of T As System.Delegate, U As System.MulticastDelegate)()
~~~~~~~~~~~~~~~
BC32061: 'MulticastDelegate' cannot be used as a type constraint.
Delegate Sub D(Of T As System.Delegate, U As System.MulticastDelegate)()
~~~~~~~~~~~~~~~~~~~~~~~~
BC32061: 'Object' cannot be used as a type constraint.
Class C(Of T As {Object, A}, U As {A, Object})
~~~~~~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Class C(Of T As {Object, A}, U As {A, Object})
~
BC32047: Type parameter 'U' can only have one constraint that is a class.
Class C(Of T As {Object, A}, U As {A, Object})
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540653")>
<Fact>
Public Sub BC32067ERR_AttrCannotBeGenerics()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttrCannotBeGenerics">
<file name="a.vb"><![CDATA[
Imports System
Class Test(Of attributeusageattribute)
'COMPILEERROR: BC32067,"attributeusageattribute"
<attributeusageattribute(AttributeTargets.All)> Class c1
End Class
Class myattr
'COMPILEERROR: BC32074,"Attribute"
Inherits Attribute
End Class
'COMPILEERROR: BC32067,"myattr"
<myattr()> Class test3
End Class
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttrCannotBeGenerics, "attributeusageattribute").WithArguments("attributeusageattribute"),
Diagnostic(ERRID.ERR_AttrCannotBeGenerics, "myattr").WithArguments("Test(Of attributeusageattribute).myattr"),
Diagnostic(ERRID.ERR_GenericClassCannotInheritAttr, "myattr"))
End Sub
<Fact()>
Public Sub BC32068ERR_BadStaticLocalInGenericMethod()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadStaticLocalInGenericMethod">
<file name="a.vb"><![CDATA[
Module M
Sub Goo(Of T)()
Static x = 1
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32068: Local variables within generic methods cannot be declared 'Static'.
Static x = 1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32070ERR_SyntMemberShadowsGenericParam3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SyntMemberShadowsGenericParam3">
<file name="a.vb"><![CDATA[
Class C(Of _P, get_P, set_P, _q, get_R, set_R, _R)
Property P
Property Q
Property R
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32070: property 'P' implicitly defines a member '_P' which has the same name as a type parameter.
Property P
~
BC32070: property 'Q' implicitly defines a member '_Q' which has the same name as a type parameter.
Property Q
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32071ERR_ConstraintAlreadyExists1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
MustInherit Class B(Of T, U)
MustOverride Sub M1(Of V As {T, U, I})()
End Class
MustInherit Class C
Inherits B(Of I, A)
MustOverride Overrides Sub M1(Of V As {I, A, I})()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32071: Constraint type 'I' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'T' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32047: Type parameter 'U' can only have one constraint that is a class.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'A' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'I' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'I' already specified for this type parameter.
MustOverride Overrides Sub M1(Of V As {I, A, I})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Duplicate undefined constraint types.
<Fact()>
Public Sub BC32071ERR_ConstraintAlreadyExists1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {A, B, A})
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'A' is not defined.
Class C(Of T As {A, B, A})
~
BC30002: Type 'B' is not defined.
Class C(Of T As {A, B, A})
~
BC30002: Type 'A' is not defined.
Class C(Of T As {A, B, A})
~
BC32071: Constraint type 'A' already specified for this type parameter.
Class C(Of T As {A, B, A})
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
Public Sub BC32072ERR_InterfacePossiblyImplTwice2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfacePossiblyImplTwice2">
<file name="a.vb"><![CDATA[
Class C1(Of T As IAsyncResult, u As IComparable)
Implements intf1(Of T)
Implements intf1(Of u)
End Class
Interface intf1(Of T)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32072: Cannot implement interface 'intf1(Of u)' because its implementation could conflict with the implementation of another implemented interface 'intf1(Of T)' for some type arguments.
Implements intf1(Of u)
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540652")>
<Fact()>
Public Sub BC32074ERR_GenericClassCannotInheritAttr()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Reflection
Friend Module RegressVSW108431mod
<AttributeUsage(AttributeTargets.All)>
Class Attr1(Of A)
'COMPILEERROR: BC32074, "Attribute"
Inherits Attribute
End Class
Class G(Of T)
Class Attr2
'COMPILEERROR: BC32074,"Attribute"
Inherits Attribute
End Class
End Class
End Module
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class Attr1(Of A)
~~~~~
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class Attr2
~~~~~
]]></errors>)
End Sub
<WorkItem(543672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543672")>
<Fact()>
Public Sub BC32074ERR_GenericClassCannotInheritAttr_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Inherits System.Attribute
End Class
Class B(Of T)
Inherits A
End Class
Class C(Of T)
Class B
Inherits A
End Class
End Class
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class B(Of T)
~
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class B
~
]]></errors>)
End Sub
<Fact>
Public Sub BC32075ERR_DeclaresCantBeInGeneric()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericClassCannotInheritAttr">
<file name="a.vb"><![CDATA[
Public Class C1(Of t)
Declare Sub goo Lib "a.dll" ()
End Class
]]></file>
</compilation>)
compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_DeclaresCantBeInGeneric, "goo"))
End Sub
<Fact()>
Public Sub BC32077ERR_OverrideWithConstraintMismatch2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
End Interface
Interface IB
End Interface
MustInherit Class A
' Different constraints.
Friend MustOverride Sub A1(Of T As Structure)()
Friend MustOverride Sub A2(Of T As Structure, U As IA(Of T))()
Friend MustOverride Sub A3(Of T As IA(Of T))()
Friend MustOverride Sub A4(Of T As {Structure, IA(Of T)}, U)()
' Additional constraints.
Friend MustOverride Sub B1(Of T)()
Friend MustOverride Sub B2(Of T As New)()
Friend MustOverride Sub B3(Of T As IA(Of T), U)()
' Missing constraints.
Friend MustOverride Sub C1(Of T As Class)()
Friend MustOverride Sub C2(Of T As {Class, New})()
Friend MustOverride Sub C3(Of T, U As {IB, IA(Of T)})()
' Same constraints, different order.
Friend MustOverride Sub D1(Of T As {IA(Of T), IB})()
Friend MustOverride Sub D2(Of T, U, V As {T, U})()
' Different constraint clauses.
Friend MustOverride Sub E1(Of T, U As T)()
' Different type parameter names.
Friend MustOverride Sub F1(Of T As Class, U As T)()
Friend MustOverride Sub F2(Of T As Class, U As T)()
End Class
MustInherit Class B
Inherits A
' Different constraints.
Friend MustOverride Overrides Sub A1(Of T As Class)()
Friend MustOverride Overrides Sub A2(Of T As Structure, U As IB)()
Friend MustOverride Overrides Sub A3(Of T As IA(Of IA(Of T)))()
Friend MustOverride Overrides Sub A4(Of T As {Structure, IA(Of U)}, U)()
' Additional constraints.
Friend MustOverride Overrides Sub B1(Of T As New)()
Friend MustOverride Overrides Sub B2(Of T As {Class, New})()
Friend MustOverride Overrides Sub B3(Of T As {IB, IA(Of T)}, U)()
' Missing constraints.
Friend MustOverride Overrides Sub C1(Of T)()
Friend MustOverride Overrides Sub C2(Of T As Class)()
Friend MustOverride Overrides Sub C3(Of T, U As IA(Of T))()
' Same constraints, different order.
Friend MustOverride Overrides Sub D1(Of T As {IB, IA(Of T)})()
Friend MustOverride Overrides Sub D2(Of T, U, V As {U, T})()
' Different constraint clauses.
Friend MustOverride Overrides Sub E1(Of T As Class, U)()
' Different type parameter names.
Friend MustOverride Overrides Sub F1(Of U As Class, T As U)()
Friend MustOverride Overrides Sub F2(Of T1 As Class, T2 As T1)()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32077: 'Friend MustOverride Overrides Sub A1(Of T As Class)()' cannot override 'Friend MustOverride Sub A1(Of T As Structure)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A1(Of T As Class)()
~~
BC32077: 'Friend MustOverride Overrides Sub A2(Of T As Structure, U As IB)()' cannot override 'Friend MustOverride Sub A2(Of T As Structure, U As IA(Of T))()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A2(Of T As Structure, U As IB)()
~~
BC32077: 'Friend MustOverride Overrides Sub A3(Of T As IA(Of IA(Of T)))()' cannot override 'Friend MustOverride Sub A3(Of T As IA(Of T))()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A3(Of T As IA(Of IA(Of T)))()
~~
BC32077: 'Friend MustOverride Overrides Sub A4(Of T As {Structure, IA(Of U)}, U)()' cannot override 'Friend MustOverride Sub A4(Of T As {Structure, IA(Of T)}, U)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A4(Of T As {Structure, IA(Of U)}, U)()
~~
BC32077: 'Friend MustOverride Overrides Sub B1(Of T As New)()' cannot override 'Friend MustOverride Sub B1(Of T)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub B1(Of T As New)()
~~
BC32077: 'Friend MustOverride Overrides Sub B2(Of T As {Class, New})()' cannot override 'Friend MustOverride Sub B2(Of T As New)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub B2(Of T As {Class, New})()
~~
BC32077: 'Friend MustOverride Overrides Sub B3(Of T As {IB, IA(Of T)}, U)()' cannot override 'Friend MustOverride Sub B3(Of T As IA(Of T), U)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub B3(Of T As {IB, IA(Of T)}, U)()
~~
BC32077: 'Friend MustOverride Overrides Sub C1(Of T)()' cannot override 'Friend MustOverride Sub C1(Of T As Class)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub C1(Of T)()
~~
BC32077: 'Friend MustOverride Overrides Sub C2(Of T As Class)()' cannot override 'Friend MustOverride Sub C2(Of T As {Class, New})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub C2(Of T As Class)()
~~
BC32077: 'Friend MustOverride Overrides Sub C3(Of T, U As IA(Of T))()' cannot override 'Friend MustOverride Sub C3(Of T, U As {IB, IA(Of T)})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub C3(Of T, U As IA(Of T))()
~~
BC32077: 'Friend MustOverride Overrides Sub E1(Of T As Class, U)()' cannot override 'Friend MustOverride Sub E1(Of T, U As T)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub E1(Of T As Class, U)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32077ERR_OverrideWithConstraintMismatch2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
End Interface
Class A
Implements I
End Class
Structure S
End Structure
MustInherit Class A0(Of T)
Friend MustOverride Sub AM(Of U As {T, Structure})()
End Class
MustInherit Class A1
Inherits A0(Of S)
Friend MustOverride Overrides Sub AM(Of U As {Structure, S})()
End Class
MustInherit Class A2
Inherits A0(Of S)
Friend MustOverride Overrides Sub AM(Of U As S)()
End Class
MustInherit Class B0(Of T)
Friend MustOverride Sub BX(Of U As {T, Class})()
End Class
MustInherit Class B1
Inherits B0(Of A)
Friend MustOverride Overrides Sub BX(Of U As {Class, A})()
End Class
MustInherit Class B2
Inherits B0(Of A)
Friend MustOverride Overrides Sub BX(Of U As A)()
End Class
MustInherit Class C0(Of T, U)
Friend MustOverride Sub CM(Of V As {T, U})()
End Class
MustInherit Class C1(Of T)
Inherits C0(Of T, T)
Friend MustOverride Overrides Sub CM(Of V As T)()
End Class
MustInherit Class C2(Of T)
Inherits C0(Of T, T)
Friend MustOverride Overrides Sub CM(Of V As {T, T})()
End Class
MustInherit Class D0(Of T, U)
Friend MustOverride Sub DM(Of V As {T, U, A, I})()
End Class
MustInherit Class D1
Inherits D0(Of I, A)
Friend MustOverride Overrides Sub DM(Of V As A)()
End Class
MustInherit Class D2
Inherits D0(Of I, A)
Friend MustOverride Overrides Sub DM(Of V As {A, I})()
End Class
MustInherit Class D3
Inherits D0(Of A, I)
Friend MustOverride Overrides Sub DM(Of V As {A, I, A, I})()
End Class
MustInherit Class E0(Of T, U)
Friend MustOverride Sub EM(Of V As {T, U, Structure})()
End Class
MustInherit Class E1
Inherits E0(Of Object, ValueType)
Friend MustOverride Overrides Sub EM(Of U As Structure)()
End Class
MustInherit Class E2
Inherits E0(Of Object, ValueType)
Friend MustOverride Overrides Sub EM(Of U As {Structure, Object, ValueType})()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32077: 'Friend MustOverride Overrides Sub AM(Of U As S)()' cannot override 'Friend MustOverride Sub AM(Of U As {Structure, S})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub AM(Of U As S)()
~~
BC32077: 'Friend MustOverride Overrides Sub BX(Of U As A)()' cannot override 'Friend MustOverride Sub BX(Of U As {Class, A})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub BX(Of U As A)()
~~
BC32071: Constraint type 'T' already specified for this type parameter.
Friend MustOverride Overrides Sub CM(Of V As {T, T})()
~
BC32077: 'Friend MustOverride Overrides Sub DM(Of V As A)()' cannot override 'Friend MustOverride Sub DM(Of V As {I, A})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub DM(Of V As A)()
~~
BC32071: Constraint type 'A' already specified for this type parameter.
Friend MustOverride Overrides Sub DM(Of V As {A, I, A, I})()
~
BC32071: Constraint type 'I' already specified for this type parameter.
Friend MustOverride Overrides Sub DM(Of V As {A, I, A, I})()
~
BC32077: 'Friend MustOverride Overrides Sub EM(Of U As Structure)()' cannot override 'Friend MustOverride Sub EM(Of V As {Structure, Object, ValueType})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub EM(Of U As Structure)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
End Interface
Class A
Implements I
End Class
Structure S
End Structure
Interface IA(Of T)
Sub AM(Of U As {T, Structure})()
End Interface
Class A1
Implements IA(Of S)
Private Sub AM(Of U As {Structure, S})() Implements IA(Of S).AM
End Sub
End Class
Class A2
Implements IA(Of S)
Private Sub AM(Of U As S)() Implements IA(Of S).AM
End Sub
End Class
Interface IB(Of T)
Sub BX(Of U As {T, Class})()
End Interface
Class B1
Implements IB(Of A)
Private Sub BX(Of U As {Class, A})() Implements IB(Of A).BX
End Sub
End Class
Class B2
Implements IB(Of A)
Private Sub BX(Of U As A)() Implements IB(Of A).BX
End Sub
End Class
Interface IC(Of T, U)
Sub CM(Of V As {T, U})()
End Interface
Class C1(Of T)
Implements IC(Of T, T)
Private Sub CM(Of V As T)() Implements IC(Of T, T).CM
End Sub
End Class
Class C2(Of T)
Implements IC(Of T, T)
Private Sub CM(Of V As {T, T})() Implements IC(Of T, T).CM
End Sub
End Class
Interface ID(Of T, U)
Sub DM(Of V As {T, U, A, I})()
End Interface
Class D1
Implements ID(Of I, A)
Private Sub DM(Of V As A)() Implements ID(Of I, A).DM
End Sub
End Class
Class D2
Implements ID(Of I, A)
Private Sub DM(Of V As {A, I})() Implements ID(Of I, A).DM
End Sub
End Class
Class D3
Implements ID(Of A, I)
Private Sub DM(Of V As {A, I, A, I})() Implements ID(Of A, I).DM
End Sub
End Class
Interface IE(Of T, U)
Sub EM(Of V As {T, U, Structure})()
End Interface
Class E1
Implements IE(Of Object, ValueType)
Private Sub EM(Of U As Structure)() Implements IE(Of Object, ValueType).EM
End Sub
End Class
Class E2
Implements IE(Of Object, ValueType)
Private Sub EM(Of U As {Structure, Object, ValueType})() Implements IE(Of Object, ValueType).EM
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32078: 'Private Sub AM(Of U As S)()' cannot implement 'IA(Of S).Sub AM(Of U As {Structure, S})()' because they differ by type parameter constraints.
Private Sub AM(Of U As S)() Implements IA(Of S).AM
~~~~~~~~~~~
BC32078: 'Private Sub BX(Of U As A)()' cannot implement 'IB(Of A).Sub BX(Of U As {Class, A})()' because they differ by type parameter constraints.
Private Sub BX(Of U As A)() Implements IB(Of A).BX
~~~~~~~~~~~
BC32071: Constraint type 'T' already specified for this type parameter.
Private Sub CM(Of V As {T, T})() Implements IC(Of T, T).CM
~
BC32078: 'Private Sub DM(Of V As A)()' cannot implement 'ID(Of I, A).Sub DM(Of V As {I, A})()' because they differ by type parameter constraints.
Private Sub DM(Of V As A)() Implements ID(Of I, A).DM
~~~~~~~~~~~~~~
BC32071: Constraint type 'A' already specified for this type parameter.
Private Sub DM(Of V As {A, I, A, I})() Implements ID(Of A, I).DM
~
BC32071: Constraint type 'I' already specified for this type parameter.
Private Sub DM(Of V As {A, I, A, I})() Implements ID(Of A, I).DM
~
BC32078: 'Private Sub EM(Of U As Structure)()' cannot implement 'IE(Of Object, ValueType).Sub EM(Of V As {Structure, Object, ValueType})()' because they differ by type parameter constraints.
Private Sub EM(Of U As Structure)() Implements IE(Of Object, ValueType).EM
~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Single method implementing multiple interface methods.
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
Sub AM(Of U As {T, Structure})()
End Interface
Interface IB(Of T)
Sub BX(Of U As {T, Class})()
End Interface
Class C(Of T)
Implements IA(Of T), IB(Of T)
Public Sub M(Of U As T)() Implements IA(Of T).AM, IB(Of T).BX
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32078: 'Public Sub M(Of U As T)()' cannot implement 'IA(Of T).Sub AM(Of U As {Structure, T})()' because they differ by type parameter constraints.
Public Sub M(Of U As T)() Implements IA(Of T).AM, IB(Of T).BX
~~~~~~~~~~~
BC32078: 'Public Sub M(Of U As T)()' cannot implement 'IB(Of T).Sub BX(Of U As {Class, T})()' because they differ by type parameter constraints.
Public Sub M(Of U As T)() Implements IA(Of T).AM, IB(Of T).BX
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Interface II
Sub m(Of T As I)()
End Interface
Class CLS
Implements II
Partial Private Sub X()
End Sub
Private Sub X(Of T)() Implements II.m
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC32078: 'Private Sub X(Of T)()' cannot implement 'II.Sub m(Of T As I)()' because they differ by type parameter constraints.
Private Sub X(Of T)() Implements II.m
~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Interface II
Sub m(Of T As I)()
End Interface
Class CLS
Implements II
Partial Private Sub X(Of T)()
End Sub
Private Sub X(Of T)() Implements II.m
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC32078: 'Private Sub X(Of T)()' cannot implement 'II.Sub m(Of T As I)()' because they differ by type parameter constraints.
Private Sub X(Of T)() Implements II.m
~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC32080ERR_HandlesInvalidOnGenericMethod()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="HandlesInvalidOnGenericMethod">
<file name="a.vb"><![CDATA[
Class A
Event X()
Sub Goo(Of T)() Handles Me.X
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32080: Generic methods cannot use 'Handles' clause.
Sub Goo(Of T)() Handles Me.X
~~~
BC31029: Method 'Goo' cannot handle event 'X' because they do not have a compatible signature.
Sub Goo(Of T)() Handles Me.X
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32081ERR_MultipleNewConstraints()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleNewConstraints">
<file name="a.vb"><![CDATA[
Imports System
Class C(Of T As {New, New})
Sub M(Of U As {New, Class, New})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32081: 'New' constraint cannot be specified multiple times for the same type parameter.
Class C(Of T As {New, New})
~~~
BC32081: 'New' constraint cannot be specified multiple times for the same type parameter.
Sub M(Of U As {New, Class, New})()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32082ERR_MustInheritForNewConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustInheritForNewConstraint2">
<file name="a.vb"><![CDATA[
Class C1(Of T)
Dim x As New C2(Of Base).C2Inner(Of Derived)
Sub New()
End Sub
End Class
Class Base
End Class
MustInherit Class Derived
Inherits Base
Public Sub New()
End Sub
End Class
Class C2(Of T As New)
Class C2Inner(Of S As {T, Derived, New})
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32082: Type argument 'Derived' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter 'S'.
Dim x As New C2(Of Base).C2Inner(Of Derived)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32083ERR_NoSuitableNewForNewConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoSuitableNewForNewConstraint2">
<file name="a.vb"><![CDATA[
Class [Public]
Public Sub New()
End Sub
End Class
Class [Friend]
Friend Sub New()
End Sub
End Class
Class ProtectedFriend
Protected Friend Sub New()
End Sub
End Class
Class [Protected]
Protected Sub New()
End Sub
End Class
Class [Private]
Private Sub New()
End Sub
End Class
Interface [Interface]
End Interface
Structure [Structure]
End Structure
Class C
Function F(Of T As New)() As T
Return New T
End Function
Sub M()
Dim o
o = F(Of [Public])()
o = F(Of [Friend])()
o = F(Of [ProtectedFriend])()
o = F(Of [Protected])()
o = F(Of [Private])()
o = F(Of [Interface])()
o = F(Of [Structure])()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32083: Type argument '[Friend]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Friend])()
~~~~~~~~~~~~~~
BC32083: Type argument 'ProtectedFriend' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [ProtectedFriend])()
~~~~~~~~~~~~~~~~~~~~~~~
BC32083: Type argument '[Protected]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Protected])()
~~~~~~~~~~~~~~~~~
BC32083: Type argument '[Private]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Private])()
~~~~~~~~~~~~~~~
BC32083: Type argument '[Interface]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Interface])()
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
' Constructors with optional and params args
' should not be considered parameterless.
<Fact()>
Public Sub BC32083ERR_NoSuitableNewForNewConstraint2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoSuitableNewForNewConstraint2">
<file name="a.vb"><![CDATA[
Class A
Public Sub New(Optional o As Object = Nothing)
End Sub
End Class
Class B
Public Sub New(ParamArray o As Object())
End Sub
End Class
Class C(Of T As New)
Shared Sub M(Of U As New)()
Dim o
o = New A()
o = New C(Of A)()
M(Of A)()
o = New B()
o = New C(Of B)()
M(Of B)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32083: Type argument 'A' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = New C(Of A)()
~
BC32083: Type argument 'A' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'U'.
M(Of A)()
~~~~~~~
BC32083: Type argument 'B' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = New C(Of B)()
~
BC32083: Type argument 'B' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'U'.
M(Of B)()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32084ERR_BadGenericParamForNewConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Structure S
End Structure
Class A
Shared Sub M(Of T As New)()
End Sub
End Class
Class B(Of T)
Overridable Sub M(Of U As T)()
End Sub
Shared Sub M(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U)()
A.M(Of T1)()
A.M(Of T2)()
A.M(Of T3)()
A.M(Of T4)()
A.M(Of T5)()
A.M(Of T6)()
A.M(Of T7)()
End Sub
End Class
Class CI
Inherits B(Of I)
Public Overrides Sub M(Of UI As I)()
A.M(Of UI)()
End Sub
End Class
Class CS
Inherits B(Of S)
Public Overrides Sub M(Of US As S)()
A.M(Of US)()
End Sub
End Class
Class CA
Inherits B(Of A)
Public Overrides Sub M(Of UA As A)()
A.M(Of UA)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32084: Type parameter 'T1' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T1)()
~~~~~~~~
BC32084: Type parameter 'T2' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T2)()
~~~~~~~~
BC32084: Type parameter 'T5' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T5)()
~~~~~~~~
BC32084: Type parameter 'T6' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T6)()
~~~~~~~~
BC32084: Type parameter 'T7' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T7)()
~~~~~~~~
BC32084: Type parameter 'UI' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of UI)()
~~~~~~~~
BC32084: Type parameter 'UA' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of UA)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32086ERR_DuplicateRawGenericTypeImport1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateRawGenericTypeImport1">
<file name="a.vb"><![CDATA[
Imports ns1.c1(Of String)
Imports ns1.c1(Of Integer)
Namespace ns1
Public Class c1(Of t)
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32086: Generic type 'c1(Of t)' cannot be imported more than once.
Imports ns1.c1(Of Integer)
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32089ERR_NameSameAsMethodTypeParam1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NameSameAsMethodTypeParam1">
<file name="a.vb"><![CDATA[
Class c1
Function fun(Of T1, T2) (ByVal t1 As T1, ByVal t2 As T2) As Integer
Return 5
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32089: 't1' is already declared as a type parameter of this method.
Function fun(Of T1, T2) (ByVal t1 As T1, ByVal t2 As T2) As Integer
~~
BC32089: 't2' is already declared as a type parameter of this method.
Function fun(Of T1, T2) (ByVal t1 As T1, ByVal t2 As T2) As Integer
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32089ERR_NameSameAsMethodTypeParam1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NameSameAsMethodTypeParam1">
<file name="a.vb"><![CDATA[
Class c1
Sub sub1(Of T1, T2 As T1) (ByVal p1 As T1, ByVal t2 As T2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32089: 't2' is already declared as a type parameter of this method.
Sub sub1(Of T1, T2 As T1) (ByVal p1 As T1, ByVal t2 As T2)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(543642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543642")>
Public Sub BC32090ERR_TypeParamNameFunctionNameCollision()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="TypeParamNameFunctionNameCollision">
<file name="a.vb"><![CDATA[
Module M
Function Goo(Of Goo)()
Return Nothing
End Function
' Allowed for Sub -- should not generate error below.
Sub Bar(Of Bar)()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32090: Type parameter cannot have the same name as its defining function.
Function Goo(Of Goo)()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32101ERR_MultipleReferenceConstraints()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {Class, Class})
Sub M(Of U As {Class, New, Class})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32101: 'Class' constraint cannot be specified multiple times for the same type parameter.
Class C(Of T As {Class, Class})
~~~~~
BC32101: 'Class' constraint cannot be specified multiple times for the same type parameter.
Sub M(Of U As {Class, New, Class})()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32102ERR_MultipleValueConstraints()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class C(Of T As {Structure, Structure})
Sub M(Of U As {Structure, I, Structure})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32102: 'Structure' constraint cannot be specified multiple times for the same type parameter.
Class C(Of T As {Structure, Structure})
~~~~~~~~~
BC32102: 'Structure' constraint cannot be specified multiple times for the same type parameter.
Sub M(Of U As {Structure, I, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32103ERR_NewAndValueConstraintsCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {Structure, New})
Sub M(Of U As {New, Structure})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32103: 'New' constraint and 'Structure' constraint cannot be combined.
Class C(Of T As {Structure, New})
~~~
BC32103: 'New' constraint and 'Structure' constraint cannot be combined.
Sub M(Of U As {New, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32104ERR_RefAndValueConstraintsCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {Structure, Class})
Sub M(Of U As {Class, Structure})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32104: 'Class' constraint and 'Structure' constraint cannot be combined.
Class C(Of T As {Structure, Class})
~~~~~
BC32104: 'Class' constraint and 'Structure' constraint cannot be combined.
Sub M(Of U As {Class, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Class B(Of T As Structure)
End Class
Class C
Shared Sub F(Of U As Structure)()
End Sub
Shared Sub M1(Of T1)()
Dim o = New B(Of T1)()
F(Of T1)()
End Sub
Shared Sub M2(Of T2 As Class)()
Dim o = New B(Of T2)()
F(Of T2)()
End Sub
Shared Sub M3(Of T3 As Structure)()
Dim o = New B(Of T3)()
F(Of T3)()
End Sub
Shared Sub M4(Of T4 As New)()
Dim o = New B(Of T4)()
F(Of T4)()
End Sub
Shared Sub M5(Of T5 As I)()
Dim o = New B(Of T5)()
F(Of T5)()
End Sub
Shared Sub M6(Of T6 As A)()
Dim o = New B(Of T6)()
F(Of T6)()
End Sub
Shared Sub M7(Of T7 As U, U)()
Dim o = New B(Of T7)()
F(Of T7)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'T1' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T1)()
~~
BC32105: Type argument 'T1' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T1)()
~~~~~~~~
BC32105: Type argument 'T2' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T2)()
~~
BC32105: Type argument 'T2' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T2)()
~~~~~~~~
BC32105: Type argument 'T4' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T4)()
~~
BC32105: Type argument 'T4' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T4)()
~~~~~~~~
BC32105: Type argument 'T5' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T5)()
~~
BC32105: Type argument 'T5' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T5)()
~~~~~~~~
BC32105: Type argument 'T6' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T6)()
~~
BC32105: Type argument 'T6' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T6)()
~~~~~~~~
BC32105: Type argument 'T7' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T7)()
~~
BC32105: Type argument 'T7' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T7)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Shared Sub F(Of T As Structure, U As Structure)(a As T, b As U)
End Sub
Shared Sub M(a As Integer, b As Object)
F(b, a)
F(a, b)
F(Of Integer, Object)(a, b)
End Sub
End Class
]]></file>
</compilation>)
' TODO: Dev10 highlights the first type parameter or argument that
' violates a generic method constraint, not the entire expression.
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
F(b, a)
~
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(a, b)
~
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of Integer, Object)(a, b)
~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports N.A(Of Object).B(Of String)
Imports C = N.A(Of Object).B(Of String)
Namespace N
Class A(Of T As Structure)
Friend Class B(Of U As Structure)
End Class
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
Imports N.A(Of Object).B(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'U'.
Imports N.A(Of Object).B(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
Imports C = N.A(Of Object).B(Of String)
~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'U'.
Imports C = N.A(Of Object).B(Of String)
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I(Of T As Structure)
Sub M(Of U As I(Of U))()
End Interface
Class A(Of T As Structure)
Friend Interface I
End Interface
End Class
Class B(Of T As I(Of T), U As A(Of U).I)
Sub M(Of V As A(Of V).I)()
End Sub
End Class
]]></file>
</compilation>)
' TODO: Dev10 reports errors on the type argument violating the
' constraint rather than the type with type argument (reporting
' error in U in I(Of U) rather than entire I(Of U) for instance).
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T'.
Sub M(Of U As I(Of U))()
~~~~~~~
BC32105: Type argument 'T' does not satisfy the 'Structure' constraint for type parameter 'T'.
Class B(Of T As I(Of T), U As A(Of U).I)
~~~~~~~
BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T'.
Class B(Of T As I(Of T), U As A(Of U).I)
~~~~~~~~~
BC32105: Type argument 'V' does not satisfy the 'Structure' constraint for type parameter 'T'.
Sub M(Of V As A(Of V).I)()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_4()
Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"N.A(Of Object).B(Of String)", "C=N.A(Of N.B).B(Of Object)"}))
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Class A(Of T As Structure)
Friend Class B(Of U As Structure)
End Class
End Class
Class B
End Class
End Namespace
]]></file>
</compilation>, options)
Dim expectedErrors = <errors><![CDATA[
BC32105: Error in project-level import 'C=N.A(Of N.B).B(Of Object)' at 'C=N.A(Of N.B).B(Of Object)' : Type argument 'B' does not satisfy the 'Structure' constraint for type parameter 'T'.
BC32105: Error in project-level import 'C=N.A(Of N.B).B(Of Object)' at 'C=N.A(Of N.B).B(Of Object)' : Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'U'.
BC32105: Error in project-level import 'N.A(Of Object).B(Of String)' at 'N.A(Of Object).B(Of String)' : Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
BC32105: Error in project-level import 'N.A(Of Object).B(Of String)' at 'N.A(Of Object).B(Of String)' : Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'U'.
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC32106ERR_BadTypeArgForRefConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Class B(Of T As Class)
End Class
Class C
Shared Sub F(Of T As Class)()
End Sub
Shared Sub M1(Of T1)()
Dim o = New B(Of T1)()
F(Of T1)()
End Sub
Shared Sub M2(Of T2 As Class)()
Dim o = New B(Of T2)()
F(Of T2)()
End Sub
Shared Sub M3(Of T3 As Structure)()
Dim o = New B(Of T3)()
F(Of T3)()
End Sub
Shared Sub M4(Of T4 As New)()
Dim o = New B(Of T4)()
F(Of T4)()
End Sub
Shared Sub M5(Of T5 As I)()
Dim o = New B(Of T5)()
F(Of T5)()
End Sub
Shared Sub M6(Of T6 As A)()
Dim o = New B(Of T6)()
F(Of T6)()
End Sub
Shared Sub M7(Of T7 As U, U)()
Dim o = New B(Of T7)()
F(Of T7)()
End Sub
Shared Sub M8()
Dim o = New B(Of Integer?)()
F(Of Integer?)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32106: Type argument 'T1' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T1)()
~~
BC32106: Type argument 'T1' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T1)()
~~~~~~~~
BC32106: Type argument 'T3' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T3)()
~~
BC32106: Type argument 'T3' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T3)()
~~~~~~~~
BC32106: Type argument 'T4' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T4)()
~~
BC32106: Type argument 'T4' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T4)()
~~~~~~~~
BC32106: Type argument 'T5' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T5)()
~~
BC32106: Type argument 'T5' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T5)()
~~~~~~~~
BC32106: Type argument 'T7' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T7)()
~~
BC32106: Type argument 'T7' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T7)()
~~~~~~~~
BC32106: Type argument 'Integer?' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of Integer?)()
~~~~~~~~
BC32106: Type argument 'Integer?' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of Integer?)()
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32107ERR_RefAndClassTypeConstrCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
Inherits A
End Class
Interface IA(Of T, U As {A, T, Class})
End Interface
Interface IB
Sub M(Of T, U As {T, Class, A})()
End Interface
MustInherit Class C(Of T, U)
MustOverride Sub M(Of V As {T, Class, U})()
End Class
MustInherit Class D
Inherits C(Of A, B)
Public Overrides Sub M(Of V As {A, Class, B})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32107: 'Class' constraint and a specific class type constraint cannot be combined.
Interface IA(Of T, U As {A, T, Class})
~~~~~
BC32107: 'Class' constraint and a specific class type constraint cannot be combined.
Sub M(Of T, U As {T, Class, A})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32108ERR_ValueAndClassTypeConstrCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
Inherits A
End Class
Interface IA(Of T, U As {A, T, Structure})
End Interface
Interface IB
Sub M(Of T, U As {T, Structure, A})()
End Interface
MustInherit Class C(Of T, U)
MustOverride Sub M(Of V As {T, Structure, U})()
End Class
MustInherit Class D
Inherits C(Of A, B)
Public Overrides Sub M(Of V As {A, Structure, B})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32108: 'Structure' constraint and a specific class type constraint cannot be combined.
Interface IA(Of T, U As {A, T, Structure})
~~~~~~~~~
BC32108: 'Structure' constraint and a specific class type constraint cannot be combined.
Sub M(Of T, U As {T, Structure, A})()
~
BC32119: Constraint 'Structure' conflicts with the constraint 'Class A' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {A, Structure, B})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32109ERR_ConstraintClashIndirectIndirect4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Interface IA(Of T As A, U As B, V As U, W As {T, U, V})
End Interface
Interface IB(Of T1 As A, T2 As B)
Sub M1(Of T3 As {T1, T2})()
Sub M2(Of T3 As {T2, T1})()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32109: Indirect constraint 'Class B' obtained from the type parameter constraint 'U' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T'.
Interface IA(Of T As A, U As B, V As U, W As {T, U, V})
~
BC32109: Indirect constraint 'Class B' obtained from the type parameter constraint 'V' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T'.
Interface IA(Of T As A, U As B, V As U, W As {T, U, V})
~
BC32109: Indirect constraint 'Class B' obtained from the type parameter constraint 'T2' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Sub M1(Of T3 As {T1, T2})()
~~
BC32109: Indirect constraint 'Class A' obtained from the type parameter constraint 'T1' conflicts with the indirect constraint 'Class B' obtained from the type parameter constraint 'T2'.
Sub M2(Of T3 As {T2, T1})()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32110ERR_ConstraintClashDirectIndirect3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Interface IA(Of T1 As A, T2 As B, T3 As {Structure, T1, T2})
End Interface
Interface IB(Of T1 As A)
Sub M(Of T2, T3 As {T2, B, T1})()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32110: Constraint 'Structure' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Interface IA(Of T1 As A, T2 As B, T3 As {Structure, T1, T2})
~~~~~~~~~
BC32110: Constraint 'Structure' conflicts with the indirect constraint 'Class B' obtained from the type parameter constraint 'T2'.
Interface IA(Of T1 As A, T2 As B, T3 As {Structure, T1, T2})
~~~~~~~~~
BC32110: Constraint 'Class B' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Sub M(Of T2, T3 As {T2, B, T1})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32110ERR_ConstraintClashDirectIndirect3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Class C
End Class
Class D(Of T1 As A, T2 As B)
Sub M(Of U1 As T1, U2 As T2, V As {C, T1, T2})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32110: Constraint 'Class C' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Sub M(Of U1 As T1, U2 As T2, V As {C, T1, T2})()
~
BC32110: Constraint 'Class C' conflicts with the indirect constraint 'Class B' obtained from the type parameter constraint 'T2'.
Sub M(Of U1 As T1, U2 As T2, V As {C, T1, T2})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32110ERR_ConstraintClashDirectIndirect3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Enum E
A
End Enum
MustInherit Class A(Of T1, T2)
MustOverride Sub M(Of U1 As T1, U2 As {T2, U1})()
End Class
Class B0
Inherits A(Of Integer, Integer)
Public Overrides Sub M(Of U1 As Integer, U2 As {Integer, U1})()
End Sub
End Class
Class B1
Inherits A(Of Integer, Object)
Public Overrides Sub M(Of U1 As Integer, U2 As {Object, U1})()
End Sub
End Class
Class B2
Inherits A(Of Integer, Short)
Public Overrides Sub M(Of U1 As Integer, U2 As {Short, U1})()
End Sub
End Class
Class B3
Inherits A(Of Integer, Long)
Public Overrides Sub M(Of U1 As Integer, U2 As {Long, U1})()
End Sub
End Class
Class B4
Inherits A(Of Integer, UInteger)
Public Overrides Sub M(Of U1 As Integer, U2 As {UInteger, U1})()
End Sub
End Class
Class B5
Inherits A(Of Integer, E)
Public Overrides Sub M(Of U1 As Integer, U2 As {E, U1})()
End Sub
End Class
Class C0
Inherits A(Of Object(), Object())
Public Overrides Sub M(Of U1 As Object(), U2 As {Object(), U1})()
End Sub
End Class
Class C1
Inherits A(Of Object(), String())
Public Overrides Sub M(Of U1 As Object(), U2 As {String(), U1})()
End Sub
End Class
Class C2
Inherits A(Of Integer(), Integer())
Public Overrides Sub M(Of U1 As Integer(), U2 As {Integer(), U1})()
End Sub
End Class
Class C3
Inherits A(Of Integer(), E())
Public Overrides Sub M(Of U1 As Integer(), U2 As {E(), U1})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32110: Constraint 'Short' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {Short, U1})()
~~~~~
BC32110: Constraint 'Long' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {Long, U1})()
~~~~
BC32110: Constraint 'UInteger' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {UInteger, U1})()
~~~~~~~~
BC32110: Constraint 'Enum E' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {E, U1})()
~
BC32110: Constraint 'E()' conflicts with the indirect constraint 'Integer()' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer(), U2 As {E(), U1})()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32111ERR_ConstraintClashIndirectDirect3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Class C
End Class
Interface IA(Of T As A, U As {T, Structure})
End Interface
Interface IB(Of T1 As A)
Sub M(Of T2, T3 As {T2, T1, B})()
End Interface
MustInherit Class D(Of T1, T2)
MustOverride Sub M(Of U As C, V As {U, T1, T2})()
End Class
Class E
Inherits D(Of A, B)
Public Overrides Sub M(Of U As C, V As {U, A, B})()
End Sub
End Class
]]></file>
</compilation>)
' Note: Dev10 never seems to generate BC32111. Instead, Dev10 generates
' BC32110 in the following cases, which is essentially the same error
' with arguments reordered, but with the other constraint highlighted.
Dim expectedErrors1 = <errors><![CDATA[
BC32111: Indirect constraint 'Class A' obtained from the type parameter constraint 'T' conflicts with the constraint 'Structure'.
Interface IA(Of T As A, U As {T, Structure})
~
BC32111: Indirect constraint 'Class A' obtained from the type parameter constraint 'T1' conflicts with the constraint 'Class B'.
Sub M(Of T2, T3 As {T2, T1, B})()
~~
BC32111: Indirect constraint 'Class C' obtained from the type parameter constraint 'U' conflicts with the constraint 'Class A'.
Public Overrides Sub M(Of U As C, V As {U, A, B})()
~
BC32111: Indirect constraint 'Class C' obtained from the type parameter constraint 'U' conflicts with the constraint 'Class B'.
Public Overrides Sub M(Of U As C, V As {U, A, B})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32113ERR_ConstraintCycle2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ConstraintCycle2">
<file name="a.vb"><![CDATA[
Class A(Of T1 As T2, T2 As T3, T3 As T4, T4 As T1)
End Class
Class B
Sub M(Of T As T)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32113: Type parameter 'T1' cannot be constrained to itself:
'T1' is constrained to 'T2'.
'T2' is constrained to 'T3'.
'T3' is constrained to 'T4'.
'T4' is constrained to 'T1'.
Class A(Of T1 As T2, T2 As T3, T3 As T4, T4 As T1)
~~
BC32113: Type parameter 'T' cannot be constrained to itself:
'T' is constrained to 'T'.
Sub M(Of T As T)()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32114ERR_TypeParamWithStructConstAsConst()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeParamWithStructConstAsConst">
<file name="a.vb"><![CDATA[
Interface I
End Interface
Interface IA(Of T As Structure, U As V, V As {T, New})
End Interface
Interface IB
Sub M(Of T As U, U As {I, V}, V As {I, Structure})()
End Interface
Interface IC(Of T1 As {I, Structure})
Sub M(Of T2 As T3, T3 As T1)()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32114: Type parameter with a 'Structure' constraint cannot be used as a constraint.
Interface IA(Of T As Structure, U As V, V As {T, New})
~
BC32114: Type parameter with a 'Structure' constraint cannot be used as a constraint.
Sub M(Of T As U, U As {I, V}, V As {I, Structure})()
~
BC32114: Type parameter with a 'Structure' constraint cannot be used as a constraint.
Sub M(Of T2 As T3, T3 As T1)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub M()
Dim n1? As Nullable(Of Integer) = New Nullable(Of Nullable(Of Integer))
Dim n2 As Nullable(Of Integer)? = New Nullable(Of Integer)?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n1? As Nullable(Of Integer) = New Nullable(Of Nullable(Of Integer))
~~~~~~~~~~~~~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n1? As Nullable(Of Integer) = New Nullable(Of Nullable(Of Integer))
~~~~~~~~~~~~~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n2 As Nullable(Of Integer)? = New Nullable(Of Integer)?
~~~~~~~~~~~~~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n2 As Nullable(Of Integer)? = New Nullable(Of Integer)?
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As Structure)
Shared Sub F(Of U As Structure)()
End Sub
Shared Sub M()
Dim o = New C(Of Integer?)()
F(Of T?)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o = New C(Of Integer?)()
~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'U'. Only non-nullable 'Structure' types are allowed.
F(Of T?)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As Structure)
Shared Sub F(Of U As Structure)()
End Sub
Shared Function M() As System.Action
Return AddressOf F(Of T?)
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'U'. Only non-nullable 'Structure' types are allowed.
Return AddressOf F(Of T?)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Structure S
End Structure
MustInherit Class A(Of T)
Friend MustOverride Sub M(Of U As T)()
End Class
Class B
Inherits A(Of S?)
Friend Overrides Sub M(Of U As S?)()
Dim o1? As U
Dim o2 As Nullable(Of U) = New Nullable(Of U)
Dim o3 As U? = New U?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC42024: Unused local variable: 'o1'.
Dim o1? As U
~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o1? As U
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o2 As Nullable(Of U) = New Nullable(Of U)
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o2 As Nullable(Of U) = New Nullable(Of U)
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o3 As U? = New U?
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o3 As U? = New U?
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32117ERR_NoAccessibleNonGeneric1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoAccessibleNonGeneric1">
<file name="a.vb"><![CDATA[
Module M1
Dim x As New C1.C2
End Module
Public Class C1
Public Class C2(Of T)
End Class
Public Class C2(Of U, V)
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32042: Too few type arguments to 'C1.C2(Of T)'.
Dim x As New C1.C2
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32118ERR_NoAccessibleGeneric1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoAccessibleGeneric1">
<file name="a.vb"><![CDATA[
Module M1
Dim x As New C1(Of Object).C2(Of SByte, Byte)
End Module
Public Class C1
Public Class C2(Of T)
End Class
Public Class C2(Of U, V)
End Class
End Class
Public Class C1(Of T)
Public Class C2
End Class
Public Class C2(Of X)
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32045: 'C1(Of Object).C2' has no type parameters and so cannot have type arguments.
Dim x As New C1(Of Object).C2(Of SByte, Byte)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32119ERR_ConflictingDirectConstraints3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A(Of T1, T2, T3)
MustOverride Sub M(Of U As {T1, T2, T3, Structure})()
End Class
Class B
Inherits A(Of C1, C2, C3)
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
End Sub
End Class
Class C1
End Class
Class C2
End Class
Class C3
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32119: Constraint 'Class C2' conflicts with the constraint 'Class C1' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
~~
BC32119: Constraint 'Class C3' conflicts with the constraint 'Class C1' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
~~
BC32119: Constraint 'Structure' conflicts with the constraint 'Class C1' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32119ERR_ConflictingDirectConstraints3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
MustInherit Class C(Of T1, T2)
MustOverride Sub M(Of U As {T1, T2})()
End Class
Class D
Inherits C(Of A, B)
Public Overrides Sub M(Of U As {A, B})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32119: Constraint 'Class B' conflicts with the constraint 'Class A' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {A, B})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32119ERR_ConflictingDirectConstraints3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Enum E
A
End Enum
MustInherit Class A(Of T, U)
MustOverride Sub M(Of V As {T, U})()
End Class
Class B0
Inherits A(Of Integer, Integer)
Public Overrides Sub M(Of V As {Integer})()
End Sub
End Class
Class B1
Inherits A(Of Integer, Object)
Public Overrides Sub M(Of V As {Integer, Object})()
End Sub
End Class
Class B2
Inherits A(Of Integer, Short)
Public Overrides Sub M(Of V As {Integer, Short})()
End Sub
End Class
Class B3
Inherits A(Of Integer, Long)
Public Overrides Sub M(Of V As {Integer, Long})()
End Sub
End Class
Class B4
Inherits A(Of Integer, UInteger)
Public Overrides Sub M(Of V As {Integer, UInteger})()
End Sub
End Class
Class B5
Inherits A(Of Integer, E)
Public Overrides Sub M(Of V As {Integer, E})()
End Sub
End Class
Class C0
Inherits A(Of Object(), Object())
Public Overrides Sub M(Of V As {Object()})()
End Sub
End Class
Class C1
Inherits A(Of Object(), String())
Public Overrides Sub M(Of V As {Object(), String()})()
End Sub
End Class
Class C2
Inherits A(Of Integer(), Integer())
Public Overrides Sub M(Of V As {Integer()})()
End Sub
End Class
Class C3
Inherits A(Of Integer(), E())
Public Overrides Sub M(Of V As {Integer(), E()})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32119: Constraint 'Short' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, Short})()
~~~~~
BC32119: Constraint 'Long' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, Long})()
~~~~
BC32119: Constraint 'UInteger' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, UInteger})()
~~~~~~~~
BC32119: Constraint 'Enum E' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, E})()
~
BC32119: Constraint 'E()' conflicts with the constraint 'Integer()' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer(), E()})()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543643")>
Public Sub BC32120ERR_InterfaceUnifiesWithInterface2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnifiesWithInterface2">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Interface derivedInterface(Of t1, t2)
Inherits interfaceA(Of t1), interfaceA(Of t2)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32120: Cannot inherit interface 'interfaceA(Of t2)' because it could be identical to interface 'interfaceA(Of t1)' for some type arguments.
Inherits interfaceA(Of t1), interfaceA(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(1042692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042692")>
<Fact()>
Public Sub BC32120ERR_InterfaceUnifiesWithInterface2_SubstituteWithOtherTypeParameter()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T, U)
End Interface
Interface IB(Of T, U)
Inherits IA(Of U, Object), IA(Of T, U)
End Interface
]]></file>
</compilation>)
compilation1.AssertTheseDeclarationDiagnostics(
<errors><![CDATA[
BC32120: Cannot inherit interface 'IA(Of T, U)' because it could be identical to interface 'IA(Of U, Object)' for some type arguments.
Inherits IA(Of U, Object), IA(Of T, U)
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact(), WorkItem(543726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543726")>
Public Sub BC32121ERR_BaseUnifiesWithInterfaces3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseUnifiesWithInterfaces3">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
Sub goo(Of G As T)(ByVal x As G)
End Interface
Interface I2(Of T)
Inherits I1(Of T)
End Interface
Interface I02(Of T, G)
Inherits I1(Of T), I2(Of G)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32121: Cannot inherit interface 'I2(Of G)' because the interface 'I1(Of G)' from which it inherits could be identical to interface 'I1(Of T)' for some type arguments.
Inherits I1(Of T), I2(Of G)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543727")>
Public Sub BC32122ERR_InterfaceBaseUnifiesWithBase4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceBaseUnifiesWithBase4">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Interface interfaceX(Of v)
Inherits interfaceA(Of v)
End Interface
Public Interface interfaceY(Of w)
Inherits interfaceA(Of w)
End Interface
Public Interface derivedInterface(Of t1, t2)
Inherits interfaceX(Of t1), interfaceY(Of t2)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32122: Cannot inherit interface 'interfaceY(Of t2)' because the interface 'interfaceA(Of t2)' from which it inherits could be identical to interface 'interfaceA(Of t1)' from which the interface 'interfaceX(Of t1)' inherits for some type arguments.
Inherits interfaceX(Of t1), interfaceY(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543729")>
Public Sub BC32123ERR_InterfaceUnifiesWithBase3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnifiesWithBase3">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
Inherits interfaceX(Of u)
End Interface
Public Interface interfaceX(Of v)
End Interface
Public Interface derivedInterface(Of t1, t2)
Inherits interfaceA(Of t1), interfaceX(Of t2)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32123: Cannot inherit interface 'interfaceX(Of t2)' because it could be identical to interface 'interfaceX(Of t1)' from which the interface 'interfaceA(Of t1)' inherits for some type arguments.
Inherits interfaceA(Of t1), interfaceX(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543643")>
Public Sub BC32072ERR_InterfacePossiblyImplTwice2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfacePossiblyImplTwice2">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Class derivedClass(Of t1, t2)
Implements interfaceA(Of t1), interfaceA(Of t2)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32072: Cannot implement interface 'interfaceA(Of t2)' because its implementation could conflict with the implementation of another implemented interface 'interfaceA(Of t1)' for some type arguments.
Implements interfaceA(Of t1), interfaceA(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543726")>
Public Sub BC32131ERR_ClassInheritsBaseUnifiesWithInterfaces3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassInheritsBaseUnifiesWithInterfaces3">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
End Interface
Interface I2(Of T)
Inherits I1(Of T)
End Interface
Class I02(Of T, G)
Implements I1(Of T), I2(Of G)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32131: Cannot implement interface 'I2(Of G)' because the interface 'I1(Of G)' from which it inherits could be identical to implemented interface 'I1(Of T)' for some type arguments.
Implements I1(Of T), I2(Of G)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543727")>
Public Sub BC32132ERR_ClassInheritsInterfaceBaseUnifiesWithBase4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassInheritsInterfaceBaseUnifiesWithBase4">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Interface interfaceX(Of v)
Inherits interfaceA(Of v)
End Interface
Public Interface interfaceY(Of w)
Inherits interfaceA(Of w)
End Interface
Public Class derivedClass(Of t1, t2)
Implements interfaceX(Of t1), interfaceY(Of t2)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32132: Cannot implement interface 'interfaceY(Of t2)' because the interface 'interfaceA(Of t2)' from which it inherits could be identical to interface 'interfaceA(Of t1)' from which the implemented interface 'interfaceX(Of t1)' inherits for some type arguments.
Implements interfaceX(Of t1), interfaceY(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543729")>
Public Sub BC32133ERR_ClassInheritsInterfaceUnifiesWithBase3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassInheritsInterfaceUnifiesWithBase3">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
Inherits interfaceX(Of u)
End Interface
Public Interface interfaceX(Of v)
End Interface
Public Class derivedClass(Of t1, t2)
Implements interfaceA(Of t1), interfaceX(Of t2)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32133: Cannot implement interface 'interfaceX(Of t2)' because it could be identical to interface 'interfaceX(Of t1)' from which the implemented interface 'interfaceA(Of t1)' inherits for some type arguments.
Implements interfaceA(Of t1), interfaceX(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32125ERR_InterfaceMethodImplsUnify3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceMethodImplsUnify3">
<file name="a.vb"><![CDATA[
Public Interface iFace1(Of t)
Sub testSub()
End Interface
Public Interface iFace2(Of u)
Inherits iFace1(Of u)
End Interface
Public Class testClass(Of y, z)
Implements iFace1(Of y), iFace2(Of z)
Public Sub testSuby() Implements iFace1(Of y).testSub
End Sub
Public Sub testSubz() Implements iFace1(Of z).testSub
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32131: Cannot implement interface 'iFace2(Of z)' because the interface 'iFace1(Of z)' from which it inherits could be identical to implemented interface 'iFace1(Of y)' for some type arguments.
Implements iFace1(Of y), iFace2(Of z)
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32200ERR_ShadowingTypeOutsideClass1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingTypeOutsideClass1">
<file name="a.vb"><![CDATA[
Public Shadows Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32200: 'C1' cannot be declared 'Shadows' outside of a class, structure, or interface.
Public Shadows Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32201ERR_PropertySetParamCollisionWithValue()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PropertySetParamCollisionWithValue">
<file name="a.vb"><![CDATA[
Interface IA
ReadOnly Property Goo(ByVal value As String) As String
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32201: Property parameters cannot have the name 'Value'.
ReadOnly Property Goo(ByVal value As String) As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32201ERR_PropertySetParamCollisionWithValue_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PropertySetParamCollisionWithValue">
<file name="a.vb"><![CDATA[
Structure S
Property P(Index, Value)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Structure
Class C
WriteOnly Property P(value)
Set(val)
End Set
End Property
ReadOnly Property Value(Value)
Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32201: Property parameters cannot have the name 'Value'.
Property P(Index, Value)
~~~~~
BC32201: Property parameters cannot have the name 'Value'.
WriteOnly Property P(value)
~~~~~
BC32201: Property parameters cannot have the name 'Value'.
ReadOnly Property Value(Value)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32205ERR_WithEventsNameTooLong()
Dim witheventname = New String("A"c, 1020)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module Program
' Declare a WithEvents variable.
Dim WithEvents <%= witheventname %> As New EventClass
' Call the method that raises the object's events.
Sub TestEvents()
<%= witheventname %>.RaiseEvents()
End Sub
' Declare an event handler that handles multiple events.
Sub EClass_EventHandler() Handles <%= witheventname %>.XEvent, <%= witheventname %>.YEvent
Console.WriteLine("Received Event.")
End Sub
Class EventClass
Public Event XEvent()
Public Event YEvent()
' RaiseEvents raises both events.
Sub RaiseEvents()
RaiseEvent XEvent()
RaiseEvent YEvent()
End Sub
End Class
End Module
</file>
</compilation>)
Dim squiggle As New String("~"c, witheventname.Length())
Dim expectedErrors1 = <errors>
BC37220: Name 'get_<%= witheventname %>' exceeds the maximum length allowed in metadata.
Dim WithEvents <%= witheventname %> As New EventClass
<%= squiggle %>
BC37220: Name 'set_<%= witheventname %>' exceeds the maximum length allowed in metadata.
Dim WithEvents <%= witheventname %> As New EventClass
<%= squiggle %>
</errors>
CompilationUtils.AssertNoDeclarationDiagnostics(compilation1)
CompilationUtils.AssertTheseEmitDiagnostics(compilation1, expectedErrors1)
End Sub
' BC32206ERR_SxSIndirectRefHigherThanDirectRef1: See ReferenceManagerTests.ReferenceBinding_SymbolUsed
' BC32208ERR_DuplicateReference2: See ReferenceManagerTests.BC32208ERR_DuplicateReference2
' BC32208ERR_DuplicateReference2_2: See ReferenceManagerTests.BC32208ERR_DuplicateReference2_2
<Fact()>
Public Sub BC32501ERR_ComClassAndReservedAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassAndReservedAttribute1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
<ComClass("287E43DD-5282-452C-91AF-8F1B34290CA3"), System.Runtime.InteropServices.ComSourceInterfaces(GetType(a), GetType(a))> _
Public Class c
Public Sub GOO()
End Sub
End Class
Public Interface a
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class.
Public Class c
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32504ERR_ComClassRequiresPublicClass2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassRequiresPublicClass2">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
Class C
Protected Class C1
<ComClass()>
Class C2
End Class
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'C2' because its container 'C1' is not declared 'Public'.
Class C2
~~
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C2' but 'C2' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Class C2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32507ERR_ComClassDuplicateGuids1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassDuplicateGuids1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
<ComClass("22904D63-46C2-47b6-97A7-8970D8EC789A", "22904D63-46C2-47b6-97A7-8970D8EC789A", "22904D63-46C2-47b6-97A7-8970D8EC789A")>
Public Class Class11
Sub test()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32507: 'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on 'Class11' cannot have the same value.
Public Class Class11
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32508ERR_ComClassCantBeAbstract0()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassCantBeAbstract0">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
<ComClass()>
Public MustInherit Class C
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32508: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.
Public MustInherit Class C
~
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C' but 'C' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Public MustInherit Class C
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32509ERR_ComClassRequiresPublicClass1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassRequiresPublicClass1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
Class C
<ComClass()>
Protected Class C1
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32509: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'C1' because it is not declared 'Public'.
Protected Class C1
~~
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C1' but 'C1' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Protected Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC33009ERR_ParamArrayIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamArrayIllegal1">
<file name="a.vb"><![CDATA[
Class C1
Delegate Sub Goo(ByVal ParamArray args() As String)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC33009: 'Delegate' parameters cannot be declared 'ParamArray'.
Delegate Sub Goo(ByVal ParamArray args() As String)
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33010ERR_OptionalIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OptionalIllegal1">
<file name="a.vb"><![CDATA[
Class C1
Event E(Optional ByVal z As String = "")
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC33010: 'Event' parameters cannot be declared 'Optional'.
Event E(Optional ByVal z As String = "")
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33011ERR_OperatorMustBePublic()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorMustBePublic">
<file name="a.vb"><![CDATA[
Public Structure S1
Private Shared Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorMustBePublic, "Private").WithArguments("Private"))
End Sub
<Fact()>
Public Sub BC33012ERR_OperatorMustBeShared()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorMustBeShared">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorMustBeShared, "IsFalse"))
End Sub
<Fact()>
Public Sub BC33013ERR_BadOperatorFlags1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadOperatorFlags1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Overridable Shared Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadOperatorFlags1, "Overridable").WithArguments("Overridable"))
End Sub
<Fact()>
Public Sub BC33014ERR_OneParameterRequired1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OneParameterRequired1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator IsFalse(ByVal z As S1, ByVal x As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1, ByVal x As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_OneParameterRequired1, "IsFalse").WithArguments("IsFalse"),
Diagnostic(ERRID.ERR_OneParameterRequired1, "IsTrue").WithArguments("IsTrue"))
End Sub
<Fact()>
Public Sub BC33015ERR_TwoParametersRequired1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="TwoParametersRequired1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator And(ByVal x As S1) As S1
Dim r As New S1
Return r
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_TwoParametersRequired1, "And").WithArguments("And"))
End Sub
' Roslyn extra errors
<Fact()>
Public Sub BC33016ERR_OneOrTwoParametersRequired1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OneOrTwoParametersRequired1">
<file name="a.vb"><![CDATA[
Public Class C1
Public Shared Operator +
(ByVal p1 As C1, ByVal p2 As Integer) As Integer
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExpectedLparen, ""),
Diagnostic(ERRID.ERR_ExpectedRparen, ""),
Diagnostic(ERRID.ERR_Syntax, "("),
Diagnostic(ERRID.ERR_OneOrTwoParametersRequired1, "+").WithArguments("+"),
Diagnostic(ERRID.WRN_DefAsgNoRetValOpRef1, "End Operator").WithArguments("+"))
' Dim expectedErrors1 = <errors><![CDATA[
'BC30199: '(' expected.
' Public Shared Operator +
' ~
'BC33016: Operator '+' must have either one or two parameters.
' Public Shared Operator +
' ~
'BC30035: Syntax error.
' (ByVal p1 As C1, ByVal p2 As Integer) As Integer
' ~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33017ERR_ConvMustBeWideningOrNarrowing()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConvMustBeWideningOrNarrowing">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator CType(ByVal x As S1) As Integer
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConvMustBeWideningOrNarrowing, "CType"))
End Sub
<Fact()>
Public Sub BC33019ERR_InvalidSpecifierOnNonConversion1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidSpecifierOnNonConversion1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator And(ByVal x As S1, ByVal y As S1) As Integer
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidSpecifierOnNonConversion1, "Widening").WithArguments("Widening"))
End Sub
<Fact()>
Public Sub BC33020ERR_UnaryParamMustBeContainingType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnaryParamMustBeContainingType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator IsTrue(ByVal x As Integer) As Boolean
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_UnaryParamMustBeContainingType1, "IsTrue").WithArguments("S1"))
End Sub
<Fact()>
Public Sub BC33021ERR_BinaryParamMustBeContainingType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BinaryParamMustBeContainingType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator And(ByVal x As Integer, ByVal y As Integer) As Boolean
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BinaryParamMustBeContainingType1, "And").WithArguments("S1"))
End Sub
<Fact()>
Public Sub BC33022ERR_ConvParamMustBeContainingType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConvParamMustBeContainingType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator CType(ByVal x As Integer) As Boolean
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConvParamMustBeContainingType1, "CType").WithArguments("S1"))
End Sub
<Fact()>
Public Sub BC33023ERR_OperatorRequiresBoolReturnType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorRequiresBoolReturnType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator IsTrue(ByVal x As S1) As Integer
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorRequiresBoolReturnType1, "IsTrue").WithArguments("IsTrue"))
End Sub
<Fact()>
Public Sub BC33024ERR_ConversionToSameType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToSameType">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator CType(ByVal x As S1) As S1
Return Nothing
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToSameType, "CType"))
End Sub
<Fact()>
Public Sub BC33025ERR_ConversionToInterfaceType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToInterfaceType">
<file name="a.vb"><![CDATA[
Interface I1
End Interface
Public Structure S1
Public Shared Widening Operator CType(ByVal x As S1) As I1
Return Nothing
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_AccessMismatchOutsideAssembly4, "I1").WithArguments("op_Implicit", "I1", "structure", "S1"),
Diagnostic(ERRID.ERR_ConversionToInterfaceType, "CType"))
End Sub
<Fact()>
Public Sub BC33026ERR_ConversionToBaseType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToBaseType">
<file name="a.vb"><![CDATA[
Class C1
End Class
Class S1
Inherits C1
Public Shared Widening Operator CType(ByVal x As S1) As C1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToBaseType, "CType"))
End Sub
<Fact()>
Public Sub BC33027ERR_ConversionToDerivedType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToDerivedType">
<file name="a.vb"><![CDATA[
Class C1
Inherits S1
End Class
Class S1
Public Shared Widening Operator CType(ByVal x As S1) As C1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToDerivedType, "CType"))
End Sub
<Fact()>
Public Sub BC33028ERR_ConversionToObject()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToObject">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator CType(ByVal x As S1) As Object
Return Nothing
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToObject, "CType"))
End Sub
<Fact()>
Public Sub BC33029ERR_ConversionFromInterfaceType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromInterfaceType">
<file name="a.vb"><![CDATA[
Interface I1
End Interface
Class S1
Public Shared Widening Operator CType(ByVal x As I1) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromInterfaceType, "CType"))
End Sub
<Fact()>
Public Sub BC33030ERR_ConversionFromBaseType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromBaseType">
<file name="a.vb"><![CDATA[
Class C1
End Class
Class S1
Inherits C1
Public Shared Widening Operator CType(ByVal x As C1) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromBaseType, "CType"))
End Sub
<Fact()>
Public Sub BC33031ERR_ConversionFromDerivedType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromDerivedType">
<file name="a.vb"><![CDATA[
Class C1
Inherits S1
End Class
Class S1
Public Shared Widening Operator CType(ByVal x As C1) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromDerivedType, "CType"))
End Sub
<Fact()>
Public Sub BC33032ERR_ConversionFromObject()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromObject">
<file name="a.vb"><![CDATA[
Class S1
Public Shared Widening Operator CType(ByVal x As Object) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromObject, "CType"))
End Sub
<Fact()>
Public Sub BC33033ERR_MatchingOperatorExpected2()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MatchingOperatorExpected2">
<file name="a.vb"><![CDATA[
Public Structure S1
Dim d As Date
Public Shared Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MatchingOperatorExpected2, "IsFalse").WithArguments("IsTrue", "Public Shared Operator IsFalse(z As S1) As Boolean"))
End Sub
<Fact()>
Public Sub BC33041ERR_OperatorRequiresIntegerParameter1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorRequiresIntegerParameter1">
<file name="a.vb"><![CDATA[
Class S1
Public Shared Operator >>(ByVal x As S1, ByVal y As String) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorRequiresIntegerParameter1, ">>").WithArguments(">>"))
End Sub
<Fact()>
Public Sub BC33101ERR_BadTypeArgForStructConstraintNull()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation name="BadTypeArgForStructConstraintNull">
<file name="a.vb"><![CDATA[
Imports System
Interface I
End Interface
Structure S
End Structure
Class A
End Class
Class B(Of T)
Shared Sub M1(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As T)()
Dim o? As Object
Dim s? As S
Dim _1? As T1
Dim _2? As T2
Dim _3? As T3
Dim _4? As T4
Dim _5? As T5
Dim _6? As T6
Dim _7? As T7
End Sub
Shared Sub M2(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As T)()
Dim o As Nullable(Of Object) = New Nullable(Of Object)
Dim s As Nullable(Of S) = New Nullable(Of S)
Dim _1 As Nullable(Of T1) = New Nullable(Of T1)
Dim _2 As Nullable(Of T2) = New Nullable(Of T2)
Dim _3 As Nullable(Of T3) = New Nullable(Of T3)
Dim _4 As Nullable(Of T4) = New Nullable(Of T4)
Dim _5 As Nullable(Of T5) = New Nullable(Of T5)
Dim _6 As Nullable(Of T6) = New Nullable(Of T6)
Dim _7 As Nullable(Of T7) = New Nullable(Of T7)
End Sub
Shared Sub M3(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As T)()
Dim o As Object? = New Object?
Dim s As S? = New S?
Dim _1 As T1? = New T1?
Dim _2 As T2? = New T2?
Dim _3 As T3? = New T3?
Dim _4 As T4? = New T4?
Dim _5 As T5? = New T5?
Dim _6 As T6? = New T6?
Dim _7 As T7? = New T7?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC42024: Unused local variable: 'o'.
Dim o? As Object
~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o? As Object
~~
BC42024: Unused local variable: 's'.
Dim s? As S
~
BC42024: Unused local variable: '_1'.
Dim _1? As T1
~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1? As T1
~~~
BC42024: Unused local variable: '_2'.
Dim _2? As T2
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2? As T2
~~~
BC42024: Unused local variable: '_3'.
Dim _3? As T3
~~
BC42024: Unused local variable: '_4'.
Dim _4? As T4
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4? As T4
~~~
BC42024: Unused local variable: '_5'.
Dim _5? As T5
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5? As T5
~~~
BC42024: Unused local variable: '_6'.
Dim _6? As T6
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6? As T6
~~~
BC42024: Unused local variable: '_7'.
Dim _7? As T7
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7? As T7
~~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Nullable(Of Object) = New Nullable(Of Object)
~~~~~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Nullable(Of Object) = New Nullable(Of Object)
~~~~~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As Nullable(Of T1) = New Nullable(Of T1)
~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As Nullable(Of T1) = New Nullable(Of T1)
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As Nullable(Of T2) = New Nullable(Of T2)
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As Nullable(Of T2) = New Nullable(Of T2)
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As Nullable(Of T4) = New Nullable(Of T4)
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As Nullable(Of T4) = New Nullable(Of T4)
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As Nullable(Of T5) = New Nullable(Of T5)
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As Nullable(Of T5) = New Nullable(Of T5)
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As Nullable(Of T6) = New Nullable(Of T6)
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As Nullable(Of T6) = New Nullable(Of T6)
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As Nullable(Of T7) = New Nullable(Of T7)
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As Nullable(Of T7) = New Nullable(Of T7)
~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Object? = New Object?
~~~~~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Object? = New Object?
~~~~~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As T1? = New T1?
~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As T1? = New T1?
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As T2? = New T2?
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As T2? = New T2?
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As T4? = New T4?
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As T4? = New T4?
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As T5? = New T5?
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As T5? = New T5?
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As T6? = New T6?
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As T6? = New T6?
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As T7? = New T7?
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As T7? = New T7?
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33102ERR_CantSpecifyArrayAndNullableOnBoth()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantSpecifyArrayAndNullableOnBoth">
<file name="a.vb"><![CDATA[
Class S1
Sub goo()
Dim numbers? As Integer()
Dim values() As Integer?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC42024: Unused local variable: 'numbers'.
Dim numbers? As Integer()
~~~~~~~
BC33101: Type 'Integer()' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim numbers? As Integer()
~~~~~~~~
BC42024: Unused local variable: 'values'.
Dim values() As Integer?
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33109ERR_CantSpecifyAsNewAndNullable()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantSpecifyAsNewAndNullable">
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub M()
Dim x? As New Guid()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC33109: Nullable modifier cannot be specified in variable declarations with 'As New'.
Dim x? As New Guid()
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC33112ERR_NullableImplicit()
Dim expectedErrors As New Dictionary(Of String, XElement) From {
{"On",
<expected><![CDATA[
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field1?()
~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field2?(,)
~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field3?()()
~~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field4?
~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local1?()
~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local2?(,)
~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local3?()()
~~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local4?
~~~~~~~
]]></expected>},
{"Off",
<expected><![CDATA[
BC36629: Nullable type inference is not supported in this context.
Dim local5? = 23 ' this is ok for Option Infer On
~~~~~~~
]]></expected>}}
For Each infer In {"On", "Off"}
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NullableImplicit">
<file name="a.vb">
Option Infer <%= infer %>
Class C1
Public field1?()
Public field2?(,)
Public field3?()()
Public field4?
'Public field5? = 23 ' this is _NOT_ ok for Option Infer On, but it gives another diagnostic.
Public field6?(1) ' this is ok for Option Infer On
Public field7?(1)() ' this is ok for Option Infer On
Sub goo()
Dim local1?()
Dim local2?(,)
Dim local3?()()
Dim local4?
Dim local5? = 23 ' this is ok for Option Infer On
Dim local6?(1) ' this is ok for Option Infer On
Dim local7?(1)() ' this is ok for Option Infer On
local1 = nothing
local2 = nothing
local3 = nothing
local4 = nothing
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors(infer))
Next
End Sub
<Fact(), WorkItem(651624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651624")>
Public Sub NestedNullableWithAttemptedConversion()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb">
Imports System
Class C
Public Sub Main()
Dim x As Nullable(Of Nullable(Of Integer)) = Nothing
Dim y As Nullable(Of Integer) = Nothing
Console.WriteLine(x Is Nothing)
Console.WriteLine(y Is Nothing)
Console.WriteLine(x = y)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp,
<errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim x As Nullable(Of Nullable(Of Integer)) = Nothing
~~~~~~~~~~~~~~~~~~~~
BC30452: Operator '=' is not defined for types 'Integer??' and 'Integer?'.
Console.WriteLine(x = y)
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC36015ERR_PropertyNameConflictInMyCollection()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PropertyNameConflictInMyCollection">
<file name="a.vb"><![CDATA[
Module module1
Public f As New GRBB
End Module
<Global.Microsoft.VisualBasic.MyGroupCollection("base", "create", "DisposeI", "Module1.f")> _
Public NotInheritable Class GRBB
Private Shared Function Create(Of T As {New, base})(ByVal Instance As T) As T
Return Nothing
End Function
Private Sub DisposeI(Of T As base)(ByRef Instance As T)
End Sub
Public m_derived As Short
End Class
Public Class base
Public i As Integer
End Class
Public Class disposei
Inherits base
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36015: 'Private Sub DisposeI(Of T As base)(ByRef Instance As T)' has the same name as a member used for type 'disposei' exposed in a 'My' group. Rename the type or its enclosing namespace.
<Global.Microsoft.VisualBasic.MyGroupCollection("base", "create", "DisposeI", "Module1.f")> _
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36551ERR_ExtensionMethodNotInModule()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ExtensionMethodNotInModule">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System
Class C1
<Extension()> _
Public Sub Print(ByVal str As String)
End Sub
End Class
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36551: Extension methods can be defined only in modules.
<Extension()> _
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36552ERR_ExtensionMethodNoParams()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="ExtensionMethodNoParams">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Module C1
<Extension()> _
Public Sub Print()
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend.
Public Sub Print()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36553ERR_ExtensionMethodOptionalFirstArg()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="ExtensionMethodOptionalFirstArg">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Module C1
<Extension()> _
Public Sub Print(Optional ByVal str As String = "hello")
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36553: 'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.
Public Sub Print(Optional ByVal str As String = "hello")
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36554ERR_ExtensionMethodParamArrayFirstArg()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="ExtensionMethodParamArrayFirstArg">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Module C1
<Extension()> _
Public Sub Print(ByVal ParamArray str() As String)
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36554: 'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.
Public Sub Print(ByVal ParamArray str() As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36561ERR_ExtensionMethodUncallable1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Interface I(Of T)
End Interface
Module M
<Extension()>
Sub M1(Of T, U As T)(o As T)
End Sub
<Extension()>
Sub M2(Of T As I(Of U), U)(o As T)
End Sub
<Extension()>
Sub M3(Of T, U As T)(o As U)
End Sub
<Extension()>
Sub M4(Of T As I(Of U), U)(o As U)
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36561: Extension method 'M2' has type constraints that can never be satisfied.
Sub M2(Of T As I(Of U), U)(o As T)
~~
BC36561: Extension method 'M3' has type constraints that can never be satisfied.
Sub M3(Of T, U As T)(o As U)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36632ERR_NullableParameterMustSpecifyType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NullableParameterMustSpecifyType">
<file name="a.vb"><![CDATA[
Imports System
Public Module M
Delegate Sub Del(x?)
Sub Main()
Dim x As Action(Of Integer?) = Sub(y?) Console.WriteLine()
End Sub
Sub goo(x?)
End Sub
Sub goo2(Of T)(x?)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36632: Nullable parameters must specify a type.
Delegate Sub Del(x?)
~~
BC36632: Nullable parameters must specify a type.
Dim x As Action(Of Integer?) = Sub(y?) Console.WriteLine()
~~
BC36632: Nullable parameters must specify a type.
Sub goo(x?)
~~
BC36632: Nullable parameters must specify a type.
Sub goo2(Of T)(x?)
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36634ERR_LambdasCannotHaveAttributes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LambdasCannotHaveAttributes">
<file name="a.vb"><![CDATA[
Public Module M
Sub LambdaAttribute()
Dim add1 = _
Function(<System.Runtime.InteropServices.InAttribute()> m As Integer) _
m + 1
End Sub
End Module
]]></file>
</compilation>)
compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_LambdasCannotHaveAttributes, "<System.Runtime.InteropServices.InAttribute()>"))
End Sub
<WorkItem(528712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528712")>
<Fact()>
Public Sub BC36643ERR_CantSpecifyParamsOnLambdaParamNoType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CantSpecifyParamsOnLambdaParamNoType">
<file name="a.vb"><![CDATA[
Imports System
Public Module M
Sub Main()
Dim x As Action(Of String()) = Sub(y()) Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_CantSpecifyParamsOnLambdaParamNoType, "y()"))
End Sub
<Fact()>
Public Sub BC36713ERR_AutoPropertyInitializedInStructure()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Structure S1(Of T As IEnumerable(Of T))
Property AP() As New T
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AutoPropertyInitializedInStructure, "AP"),
Diagnostic(ERRID.ERR_NewIfNullOnGenericParam, "T"))
End Sub
<WorkItem(542471, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542471")>
<Fact>
Public Sub BC36713ERR_AutoPropertyInitializedInStructure_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Structure S1
Public Property age1() As Integer = 10
Public Shared Property age2() As Integer = 10
End Structure
Module M1
Public Property age3() As Integer = 10
End Module
Class C1
Public Property age4() As Integer = 10
Public Shared Property age5() As Integer = 10
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36713: Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.
Public Property age1() As Integer = 10
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540702")>
<Fact>
Public Sub BC36759ERR_AutoPropertyCantHaveParams()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Imports System
Class A
Public Property Item(index As Integer) As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36759: Auto-implemented properties cannot have parameters.
Public Property Item(index As Integer) As String
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540702")>
<Fact>
Public Sub BC36759ERR_AutoPropertyCantHaveParams_MustOverride()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Imports System
Class A
Public MustOverride Property P(index As Integer) As T
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31411: 'A' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Class A
~
BC30002: Type 'T' is not defined.
Public MustOverride Property P(index As Integer) As T
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540702")>
<Fact>
Public Sub BC36759ERR_AutoPropertyCantHaveParams_Default()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Class C
Default Public Property P(a As Integer) As T
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30025: Property missing 'End Property'.
Default Public Property P(a As Integer) As T
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Default Public Property P(a As Integer) As T
~
BC30002: Type 'T' is not defined.
Default Public Property P(a As Integer) As T
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36722ERR_VarianceDisallowedHere()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceDisallowedHere">
<file name="a.vb"><![CDATA[
Class C1
Structure Z(Of T, In U, Out V)
End Structure
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure Z(Of T, In U, Out V)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure Z(Of T, In U, Out V)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36723ERR_VarianceInterfaceNesting()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInterfaceNesting">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Class C : End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C : End Class
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36724ERR_VarianceOutParamDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub GOO(ByVal x As R(Of Tout))
End Interface
Interface R(Of Out T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Sub GOO(ByVal x As R(Of Tout))
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36725ERR_VarianceInParamDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As W(Of Tin))
End Interface
Interface W(Of In T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As W(Of Tin))
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36726ERR_VarianceOutParamDisallowedForGeneric3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowedForGeneric3">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of Tout, Tout))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because 'Tout' is an 'Out' type parameter.
Sub goo(ByVal x As RW(Of Tout, Tout))
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36727ERR_VarianceInParamDisallowedForGeneric3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowedForGeneric3">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of Tin, Tin))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1, T2)' in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As RW(Of Tin, Tin))
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36728ERR_VarianceOutParamDisallowedHere2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowedHere2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As R(Of R(Of Tout)))
End Interface
Interface R(Of Out T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub goo(ByVal x As R(Of R(Of Tout)))
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36729ERR_VarianceInParamDisallowedHere2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowedHere2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As W(Of R(Of Tin)))
End Interface
Interface R(Of Out T) : End Interface
Interface W(Of In T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As W(Of R(Of Tin)))
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36730ERR_VarianceOutParamDisallowedHereForGeneric4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowedHereForGeneric4">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin)))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of Tout, Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub goo(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin)))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36731ERR_VarianceInParamDisallowedHereForGeneric4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowedHereForGeneric4">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin)))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1, T2)' in 'RW(Of Tin, Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin)))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36732ERR_VarianceTypeDisallowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowed2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As J)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As J)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36733ERR_VarianceTypeDisallowedForGeneric4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowedForGeneric4">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As RW(Of J, Tout))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As RW(Of J, Tout))
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36735ERR_VarianceTypeDisallowedHere3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowedHere3">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As R(Of R(Of J)))
End Interface
Interface R(Of Out T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36735: Type 'J' cannot be used in 'R(Of I(Of Tout, Tin, TSout, TSin).J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As R(Of R(Of J)))
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36736ERR_VarianceTypeDisallowedHereForGeneric5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowedHereForGeneric5">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin)))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of I(Of Tout, Tin, TSout, TSin).J, Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin)))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36738ERR_VariancePreventsSynthesizedEvents2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VariancePreventsSynthesizedEvents2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Event e()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout, Tin, TSout, TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout, Tin, TSout, TSin)'. For example, 'Event e As Action(Of ...)'.
Event e()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36740ERR_VarianceOutNullableDisallowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutNullableDisallowed2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Function goo() As TSout?
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36740: Type 'TSout' cannot be used in 'TSout?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSout' is an 'Out' type parameter.
Function goo() As TSout?
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36741ERR_VarianceInNullableDisallowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInNullableDisallowed2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As TSin?)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36741: Type 'TSin' cannot be used in 'TSin?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSin' is an 'In' type parameter.
Sub goo(ByVal x As TSin?)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36742ERR_VarianceOutByValDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutByValDisallowed1">
<file name="a.vb"><![CDATA[
Interface IVariance(Of Out T)
Sub Goo(ByVal a As T)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36742: Type 'T' cannot be used as a ByVal parameter type because 'T' is an 'Out' type parameter.
Sub Goo(ByVal a As T)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36743ERR_VarianceInReturnDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInReturnDisallowed1">
<file name="a.vb"><![CDATA[
Interface IVariance(Of In T)
Function Goo() As T
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36743: Type 'T' cannot be used as a return type because 'T' is an 'In' type parameter.
Function Goo() As T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36744ERR_VarianceOutConstraintDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutConstraintDisallowed1">
<file name="a.vb"><![CDATA[
Interface IVariance(Of Out T)
Function Goo(Of U As T)() As T
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36744: Type 'T' cannot be used as a generic type constraint because 'T' is an 'Out' type parameter.
Function Goo(Of U As T)() As T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36745ERR_VarianceInReadOnlyPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInReadOnlyPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
ReadOnly Property p() As Tin
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an 'In' type parameter.
ReadOnly Property p() As Tin
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36746ERR_VarianceOutWriteOnlyPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutWriteOnlyPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
WriteOnly Property p() As Tout
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an 'Out' type parameter.
WriteOnly Property p() As Tout
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36747ERR_VarianceOutPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Property p() As Tout
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an 'Out' type parameter and the property is not marked ReadOnly.
Property p() As Tout
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36748ERR_VarianceInPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Property p() As Tin
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an 'In' type parameter and the property is not marked WriteOnly.
Property p() As Tin
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36749ERR_VarianceOutByRefDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutByRefDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub f(ByRef x As Tout)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36749: Type 'Tout' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tout' is an 'Out' type parameter.
Sub f(ByRef x As Tout)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36750ERR_VarianceInByRefDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInByRefDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub f(ByRef x As Tin)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36750: Type 'Tin' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tin' is an 'In' type parameter.
Sub f(ByRef x As Tin)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36917ERR_OverloadsModifierInModule()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverloadsModifierInModule">
<file name="a.vb"><![CDATA[
Module M1
Overloads Function goo(x as integer) as double
return nothing
End Function
Overloads Function goo(ByVal x As Long) As Double
Return Nothing
End Function
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Function goo(x as integer) as double
~~~~~~~~~
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Function goo(ByVal x As Long) As Double
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Old name"MethodErrorsOverloadsInModule"
<Fact>
Public Sub BC36917ERR_OverloadsModifierInModule_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Overloads Sub S()
End Sub
Overloads Property P
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Sub S()
~~~~~~~~~
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Property P
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
#End Region
#Region "Targeted Warning Tests"
<Fact>
Public Sub BC40000WRN_UseOfObsoleteSymbol2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UseOfObsoleteSymbol2">
<file name="a.vb"><![CDATA[
Imports System.Net
Module Module1
Sub Main()
Dim RemoteEndPoint As EndPoint = Nothing
Dim x As Long
x = CType(CType(RemoteEndPoint, IPEndPoint).Address.Address Mod 256, Byte)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40000: 'Public Overloads Property Address As Long' is obsolete: 'This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202'.
x = CType(CType(RemoteEndPoint, IPEndPoint).Address.Address Mod 256, Byte)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40003WRN_MustOverloadBase4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustOverloadBase4">
<file name="a.vb"><![CDATA[
Interface I
Sub S()
End Interface
Class C1
Implements I
Public Sub S() Implements I.S
End Sub
End Class
Class C2
Inherits C1
Public Sub S()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: sub 'S' shadows an overloadable member declared in the base class 'C1'. If you want to overload the base method, this method must be declared 'Overloads'.
Public Sub S()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40004WRN_OverrideType5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideType5">
<file name="a.vb"><![CDATA[
Public Class Base
Public i As Integer = 10
End Class
Public Class C1
Inherits Base
Public i As String = "hi"
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40004: variable 'i' conflicts with variable 'i' in the base class 'Base' and should be declared 'Shadows'.
Public i As String = "hi"
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40005WRN_MustOverride2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustOverride2">
<file name="a.vb"><![CDATA[
Class C1
Overridable ReadOnly Property Goo(ByVal x As Integer) As Integer
Get
Return 1
End Get
End Property
End Class
Class C2
Inherits C1
ReadOnly Property Goo(ByVal x As Integer) As Integer
Get
Return 1
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40005: property 'Goo' shadows an overridable method in the base class 'C1'. To override the base method, this method must be declared 'Overrides'.
ReadOnly Property Goo(ByVal x As Integer) As Integer
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(543734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543734")>
<WorkItem(561748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/561748")>
<Fact>
Public Sub BC40007WRN_DefaultnessShadowed4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Namespace N1
Class base
Default Public ReadOnly Property Item(ByVal i As Integer) As Integer
Get
Return i
End Get
End Property
End Class
Class base2
Inherits base
End Class
Class derive
Inherits base
Default Public Overloads ReadOnly Property Item1(ByVal i As Integer) As Integer
Get
Return 2 * i
End Get
End Property
End Class
Class derive2
Inherits base2
Default Public Overloads ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
Get
Return 2 * i
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40007: Default property 'Item1' conflicts with the default property 'Item' in the base class 'base'. 'Item1' will be the default property. 'Item1' should be declared 'Shadows'.
Default Public Overloads ReadOnly Property Item1(ByVal i As Integer) As Integer
~~~~~
BC40007: Default property 'Item3' conflicts with the default property 'Item' in the base class 'base'. 'Item3' will be the default property. 'Item3' should be declared 'Shadows'.
Default Public Overloads ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(546773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546773")>
Public Sub BC40007WRN_DefaultnessShadowed4_NoErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Base
Default Public ReadOnly Property TeamName(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
Class Derived
Inherits Base
Default Public Shadows ReadOnly Property TeamProject(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors><![CDATA[]]></errors>)
End Sub
<Fact, WorkItem(546773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546773")>
Public Sub BC40007WRN_DefaultnessShadowed4_TwoErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Base
Default Public ReadOnly Property TeamName(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
Class Derived
Inherits Base
Default Public ReadOnly Property TeamProject(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
Default Public ReadOnly Property TeamProject(ByVal index As String) As String
Get
Return ""
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40007: Default property 'TeamProject' conflicts with the default property 'TeamName' in the base class 'Base'. 'TeamProject' will be the default property. 'TeamProject' should be declared 'Shadows'.
Default Public ReadOnly Property TeamProject(ByVal index As Integer) As String
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(546773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546773")>
Public Sub BC40007WRN_DefaultnessShadowed4_MixedErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Base
Default Public ReadOnly Property TeamName(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
Class Derived
Inherits Base
Default Public Shadows ReadOnly Property TeamProject(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
Default Public ReadOnly Property TeamProject(ByVal index As String) As String
Get
Return ""
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30695: property 'TeamProject' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Default Public ReadOnly Property TeamProject(ByVal index As String) As String
~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(543734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543734")>
<Fact>
Public Sub BC40007WRN_DefaultnessShadowed4_DifferentCasing()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Namespace N1
Class base
Default Public ReadOnly Property Item(ByVal i As Integer) As Integer
Get
Return i
End Get
End Property
End Class
Class derive
Inherits base
Default Public Overloads ReadOnly Property item(ByVal i As Integer, j as Integer) As Integer
Get
Return 2 * i
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
' Differs only by case, shouldn't have errors.
Dim expectedErrors1 = <errors><![CDATA[
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(543734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543734")>
<WorkItem(561748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/561748")>
<Fact>
Public Sub BC40007WRN_DefaultnessShadowed4_Interface()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface base1
End Interface
Interface base2
Default ReadOnly Property Item2(ByVal i As Integer) As Integer
End Interface
Interface base3
Inherits base2
End Interface
Interface derive1
Inherits base1, base2
Default ReadOnly Property Item1(ByVal i As Integer) As Integer
End Interface
Interface derive2
Inherits base3
Default ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40007: Default property 'Item1' conflicts with the default property 'Item2' in the base interface 'base2'. 'Item1' will be the default property. 'Item1' should be declared 'Shadows'.
Default ReadOnly Property Item1(ByVal i As Integer) As Integer
~~~~~
BC40007: Default property 'Item3' conflicts with the default property 'Item2' in the base interface 'base2'. 'Item3' will be the default property. 'Item3' should be declared 'Shadows'.
Default ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC40011WRN_ComClassNoMembers1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassNoMembers1">
<file name="a.vb"><![CDATA[
<Microsoft.VisualBasic.ComClassAttribute()>
Public Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C1' but 'C1' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Public Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40012WRN_SynthMemberShadowsMember5_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
Public Sub get_P()
End Sub
Public Sub set_P()
End Sub
Public Function get_Q()
Return Nothing
End Function
Public Sub set_Q()
End Sub
Public Function get_R(value)
Return Nothing
End Function
Public Sub set_R(value)
End Sub
Public Function get_S()
Return Nothing
End Function
Public Function set_S()
Return Nothing
End Function
Public get_T
Public Interface set_T
End Interface
Public Enum get_U
A
End Enum
Public Structure set_U
End Structure
End Class
MustInherit Class B
Inherits A
Public Property P
Public ReadOnly Property Q
Get
Return Nothing
End Get
End Property
Friend WriteOnly Property R
Set(value)
End Set
End Property
Protected MustOverride Property S
Public Property T
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Public Property U
End Class
MustInherit Class C
Inherits A
Public Shadows Property P
Public Shadows ReadOnly Property Q
Get
Return Nothing
End Get
End Property
Friend Shadows WriteOnly Property R
Set(value)
End Set
End Property
Protected MustOverride Shadows Property S
Public Shadows Property T
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Public Shadows Property U
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40012: property 'P' implicitly declares 'get_P', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property P
~
BC40012: property 'P' implicitly declares 'set_P', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property P
~
BC40012: property 'Q' implicitly declares 'get_Q', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public ReadOnly Property Q
~
BC40012: property 'R' implicitly declares 'set_R', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Friend WriteOnly Property R
~
BC40012: property 'S' implicitly declares 'get_S', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Protected MustOverride Property S
~
BC40012: property 'S' implicitly declares 'set_S', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Protected MustOverride Property S
~
BC40012: property 'T' implicitly declares 'get_T', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property T
~
BC40012: property 'T' implicitly declares 'set_T', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property T
~
BC40012: property 'U' implicitly declares 'get_U', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property U
~
BC40012: property 'U' implicitly declares 'set_U', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property U
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(541355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541355")>
<Fact>
Public Sub BC40012WRN_SynthMemberShadowsMember5_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
Private _P1
Protected _P2
Friend _P3
Public Sub _Q1()
End Sub
Public Interface _Q2
End Interface
Public Enum _Q3
A
End Enum
Public _R1
Public _R2
Public _R3
Public _R4
End Class
MustInherit Class B
Inherits A
Friend Property P1
Protected Property P2
Private Property P3
Public Property Q1
Public Property Q2
Public Property Q3
Public ReadOnly Property R1
Get
Return Nothing
End Get
End Property
Public WriteOnly Property R2
Set(value)
End Set
End Property
Public MustOverride Property R3
Public Property R4
End Class
MustInherit Class C
Inherits A
Friend Shadows Property P1
Protected Shadows Property P2
Private Shadows Property P3
Public Shadows Property Q1
Public Shadows Property Q2
Public Shadows Property Q3
Public Shadows ReadOnly Property R1
Get
Return Nothing
End Get
End Property
Public Shadows WriteOnly Property R2
Set(value)
End Set
End Property
Public MustOverride Shadows Property R3
Public Shadows Property R4
End Class
MustInherit Class D
Friend Property P1
Protected Property P2
Private Property P3
Public Property Q1
Public Property Q2
Public Property Q3
Public ReadOnly Property R1
Get
Return Nothing
End Get
End Property
Public WriteOnly Property R2
Set(value)
End Set
End Property
Public MustOverride Property R3
End Class
MustInherit Class E
Inherits D
Private _P1
Protected _P2
Friend _P3
Public Sub _Q1()
End Sub
Public Interface _Q2
End Interface
Public Enum _Q3
A
End Enum
Public _R1
Public _R2
Public _R3
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40012: property 'P2' implicitly declares '_P2', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Protected Property P2
~~
BC40012: property 'P3' implicitly declares '_P3', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Private Property P3
~~
BC40012: property 'Q1' implicitly declares '_Q1', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property Q1
~~
BC40012: property 'Q2' implicitly declares '_Q2', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property Q2
~~
BC40012: property 'Q3' implicitly declares '_Q3', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property Q3
~~
BC40012: property 'R4' implicitly declares '_R4', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property R4
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539827")>
<Fact>
Public Sub BC40012WRN_SynthMemberShadowsMember5_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA
Function get_Goo() As String
End Interface
Interface IB
Inherits IA
ReadOnly Property Goo() As Integer
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC40012: property 'Goo' implicitly declares 'get_Goo', which conflicts with a member in the base interface 'IA', and so the property should be declared 'Shadows'.
ReadOnly Property Goo() As Integer
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC40012WRN_SynthMemberShadowsMember5_4()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public add_E
Public remove_E
Public EEvent
Public EEventHandler
End Class
Class B
Inherits A
Public Event E()
End Class
Class C
Inherits A
Public Shadows Event E()
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "EEventHandler", "class", "A"),
Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "EEvent", "class", "A"),
Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "add_E", "class", "A"),
Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "remove_E", "class", "A"))
End Sub
<Fact>
Public Sub BC40014WRN_MemberShadowsSynthMember6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
Public Property P
Public ReadOnly Property Q
Get
Return Nothing
End Get
End Property
Friend WriteOnly Property R
Set(value)
End Set
End Property
Protected MustOverride Property S
End Class
MustInherit Class B
Inherits A
Public Sub get_P()
End Sub
Public Sub set_P()
End Sub
Public Function get_Q()
Return Nothing
End Function
Public Sub set_Q()
End Sub
Public Function get_R(value)
Return Nothing
End Function
Public Sub set_R(value)
End Sub
Public Function get_S()
Return Nothing
End Function
Public Function set_S()
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40014: sub 'get_P' conflicts with a member implicitly declared for property 'P' in the base class 'A' and should be declared 'Shadows'.
Public Sub get_P()
~~~~~
BC40014: sub 'set_P' conflicts with a member implicitly declared for property 'P' in the base class 'A' and should be declared 'Shadows'.
Public Sub set_P()
~~~~~
BC40014: function 'get_Q' conflicts with a member implicitly declared for property 'Q' in the base class 'A' and should be declared 'Shadows'.
Public Function get_Q()
~~~~~
BC40014: sub 'set_R' conflicts with a member implicitly declared for property 'R' in the base class 'A' and should be declared 'Shadows'.
Public Sub set_R(value)
~~~~~
BC40014: function 'get_S' conflicts with a member implicitly declared for property 'S' in the base class 'A' and should be declared 'Shadows'.
Public Function get_S()
~~~~~
BC40014: function 'set_S' conflicts with a member implicitly declared for property 'S' in the base class 'A' and should be declared 'Shadows'.
Public Function set_S()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40019WRN_UseOfObsoletePropertyAccessor3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoletePropertyAccessor3">
<file name="a.vb"><![CDATA[
Imports System
Class C1
ReadOnly Property p As String
<Obsolete("hello", False)>
Get
Return "hello"
End Get
End Property
End Class
Class C2
Sub goo()
Dim s As C1 = New C1()
Dim a = s.p
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40019: 'Get' accessor of 'Public ReadOnly Property p As String' is obsolete: 'hello'.
Dim a = s.p
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40025WRN_FieldNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="FieldNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(True)> Public Class GenCompClass(Of T)
<CLSCompliant(False)> Public Structure NonCompStruct
Public a As UInteger
End Structure
<CLSCompliant(False)> Class cls1
End Class
End Class
Public Class C(Of t)
Inherits GenCompClass(Of String)
Public x As GenCompClass(Of String).cls1
Public y As GenCompClass(Of String).NonCompStruct
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40025: Type of member 'x' is not CLS-compliant.
Public x As GenCompClass(Of String).cls1
~
BC40025: Type of member 'y' is not CLS-compliant.
Public y As GenCompClass(Of String).NonCompStruct
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40026WRN_BaseClassNotCLSCompliant2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseClassNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class MyCompliantClass
Inherits BASE
End Class
Public Class BASE
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40026: 'MyCompliantClass' is not CLS-compliant because it derives from 'BASE', which is not CLS-compliant.
Public Class MyCompliantClass
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40027WRN_ProcTypeNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ProcTypeNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class MyCompliantClass
Public Function ChangeValue() As UInt32
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40027: Return type of function 'ChangeValue' is not CLS-compliant.
Public Function ChangeValue() As UInt32
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40028WRN_ParamNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class MyCompliantClass
Public Sub ChangeValue(ByVal value As UInt32)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40028: Type of parameter 'value' is not CLS-compliant.
Public Sub ChangeValue(ByVal value As UInt32)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40029WRN_InheritedInterfaceNotCLSCompliant2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritedInterfaceNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<assembly: clscompliant(true)>
<CLSCompliant(False)> Public Interface i1
End Interface
Public Interface i2
Inherits i1
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40029: 'i2' is not CLS-compliant because the interface 'i1' it inherits from is not CLS-compliant.
Public Interface i2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40030WRN_CLSMemberInNonCLSType3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CLSMemberInNonCLSType3">
<file name="a.vb"><![CDATA[
Imports System
Public Module M1
<CLSCompliant(True)> Class C1
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40030: class 'M1.C1' cannot be marked CLS-compliant because its containing type 'M1' is not CLS-compliant.
<CLSCompliant(True)> Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40031WRN_NameNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NameNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Namespace _NS
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40031: Name '_NS' is not CLS-compliant.
Namespace _NS
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40032WRN_EnumUnderlyingTypeNotCLS1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EnumUnderlyingTypeNotCLS1">
<file name="a.vb"><![CDATA[
<Assembly: System.CLSCompliant(True)>
Public Class c1
Public Enum COLORS As UInteger
RED
GREEN
BLUE
End Enum
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40032: Underlying type 'UInteger' of Enum is not CLS-compliant.
Public Enum COLORS As UInteger
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40033WRN_NonCLSMemberInCLSInterface1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NonCLSMemberInCLSInterface1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)> Public Interface IFace
<CLSCompliant(False)> Property Prop1() As Long
<CLSCompliant(False)> Function F2() As Integer
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
<CLSCompliant(False)> Sub Sub4()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40033: Non CLS-compliant 'Property Prop1 As Long' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Property Prop1() As Long
~~~~~
BC40033: Non CLS-compliant 'Function F2() As Integer' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Function F2() As Integer
~~
BC40033: Non CLS-compliant 'Event EV3(i3 As Integer)' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
~~~
BC40033: Non CLS-compliant 'Sub Sub4()' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Sub Sub4()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40034WRN_NonCLSMustOverrideInCLSType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NonCLSMustOverrideInCLSType1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)> Public MustInherit Class QuiteCompliant
<CLSCompliant(False)> Public MustOverride Sub Sub1()
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
<CLSCompliant(False)> Friend MustOverride Function Fun4(ByVal x As Long) As Long
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Public MustOverride Sub Sub1()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40035WRN_ArrayOverloadsNonCLS2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ArrayOverloadsNonCLS2">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public MustInherit Class QuiteCompliant
Public Sub goo(Of t)(ByVal p1()()() As Integer)
End Sub
Public Sub goo(Of t)(ByVal p1()()()()() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40035: 'Public Sub goo(Of t)(p1 As Integer()()()()())' is not CLS-compliant because it overloads 'Public Sub goo(Of t)(p1 As Integer()()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub goo(Of t)(ByVal p1()()()()() As Integer)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40038WRN_RootNamespaceNotCLSCompliant1()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("_CLS")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RootNamespaceNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Module M1
End Module
]]></file>
</compilation>, opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40038: Root namespace '_CLS' is not CLS-compliant.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40039WRN_RootNamespaceNotCLSCompliant2()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("A._B")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RootNamespaceNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Module M1
End Module
]]></file>
</compilation>, opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40039: Name '_B' in the root namespace 'A._B' is not CLS-compliant.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40041WRN_TypeNotCLSCompliant1()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(True)> Public Class GenCompClass(Of T)
End Class
Public Class C(Of t)
Inherits GenCompClass(Of UInteger)
End Class
]]></file>
</compilation>, options:=opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Class C(Of t)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40042WRN_OptionalValueNotCLSCompliant1()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OptionalValueNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Module M1
Public Sub goo(Of t)(Optional ByVal p1 As Object = 3UI)
End Sub
End Module
]]></file>
</compilation>, opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40042: Type of optional value for optional parameter 'p1' is not CLS-compliant.
Public Sub goo(Of t)(Optional ByVal p1 As Object = 3UI)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40043WRN_CLSAttrInvalidOnGetSet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CLSAttrInvalidOnGetSet">
<file name="a.vb"><![CDATA[
Imports System
Class C1
Property PROP As String
<CLSCompliant(True)>
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40046WRN_TypeConflictButMerged6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface ii
End Interface
Structure teststruct
Implements ii
End Structure
Partial Structure teststruct
End Structure
Structure teststruct
Dim a As String
End Structure
Partial Interface ii
End Interface
Interface ii ' 3
End Interface
Module m
End Module
Partial Module m
End Module
Module m ' 3
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40046: interface 'ii' and partial interface 'ii' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Interface ii
~~
BC40046: structure 'teststruct' and partial structure 'teststruct' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Structure teststruct
~~~~~~~~~~
BC40046: structure 'teststruct' and partial structure 'teststruct' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Structure teststruct
~~~~~~~~~~
BC40046: interface 'ii' and partial interface 'ii' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Interface ii ' 3
~~
BC40046: module 'm' and partial module 'm' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Module m
~
BC40046: module 'm' and partial module 'm' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Module m ' 3
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40046WRN_TypeConflictButMerged6_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Partial Class C
Private F
End Class
Class C ' Warning 1
Private G
End Class
Class C ' Warning 2
Private H
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40046: class 'C' and partial class 'C' conflict in namespace 'N', but are being merged because one of them is declared partial.
Class C ' Warning 1
~
BC40046: class 'C' and partial class 'C' conflict in namespace 'N', but are being merged because one of them is declared partial.
Class C ' Warning 2
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40048WRN_ShadowingGenericParamWithParam1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingGenericParamWithParam1">
<file name="a.vb"><![CDATA[
Interface I1(Of V)
Class C1(Of V)
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40048: Type parameter 'V' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Class C1(Of V)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543528")>
Public Sub BC40048WRN_ShadowingGenericParamWithParam1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingGenericParamWithParam1">
<file name="a.vb"><![CDATA[
Class base(Of T)
Function TEST(Of T)(ByRef X As T)
Return Nothing
End Function
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.WRN_ShadowingGenericParamWithParam1, "T").WithArguments("T"))
End Sub
<Fact>
Public Sub BC40050WRN_EventDelegateTypeNotCLSCompliant2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventDelegateTypeNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class ETester
<CLSCompliant(False)> Public Delegate Sub abc(ByVal n As Integer)
Public Custom Event E As abc
AddHandler(ByVal Value As abc)
End AddHandler
RemoveHandler(ByVal Value As abc)
End RemoveHandler
RaiseEvent(ByVal n As Integer)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40050: Delegate type 'ETester.abc' of event 'E' is not CLS-compliant.
Public Custom Event E As abc
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40053WRN_CLSEventMethodInNonCLSType3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CLSEventMethodInNonCLSType3">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(False)> _
Public Class cls1
Delegate Sub del1()
Custom Event e1 As del1
AddHandler(ByVal value As del1)
End AddHandler
<CLSCompliant(True)> _
RemoveHandler(ByVal value As del1)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40053: 'RemoveHandler' method for event 'e1' cannot be marked CLS compliant because its containing type 'cls1' is not CLS compliant.
<CLSCompliant(True)> _
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539496")>
<Fact>
Public Sub BC40055WRN_NamespaceCaseMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NamespaceCaseMismatch3">
<file name="a.vb"><![CDATA[
Namespace ns1
End Namespace
Namespace Ns1
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'Ns1' in 'a.vb'.
Namespace ns1
~~~
]]></errors>)
compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NamespaceCaseMismatch3">
<file name="a.vb"><![CDATA[
Namespace ns1
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Namespace Ns1
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'Ns1' in 'b.vb'.
Namespace ns1
~~~
]]></errors>)
compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NamespaceCaseMismatch3">
<file name="a.vb"><![CDATA[
Namespace Ns
End Namespace
Namespace ns.AB
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Namespace NS.Ab
End Namespace
Namespace Ns
Namespace Ab
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40055: Casing of namespace name 'Ns' does not match casing of namespace name 'NS' in 'b.vb'.
Namespace Ns
~~
BC40055: Casing of namespace name 'Ab' does not match casing of namespace name 'AB' in 'a.vb'.
Namespace NS.Ab
~~
]]></errors>)
End Sub
<WorkItem(545727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545727")>
<Fact()>
Public Sub BC40055_WRN_NamespaceCaseMismatch3_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="ConsoleApplicationVB"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'CONSOLEAPPLICATIONVB' does not match casing of namespace name 'ConsoleApplicationVB' in '<project settings>'.
Namespace CONSOLEAPPLICATIONVB
~~~~~~~~~~~~~~~~~~~~
]]></expected>)
' different casing to see that best name has no influence on error
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace consoleapplicationvb
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="CONSOLEAPPLICATIONVB"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'consoleapplicationvb' does not match casing of namespace name 'CONSOLEAPPLICATIONVB' in '<project settings>'.
Namespace consoleapplicationvb
~~~~~~~~~~~~~~~~~~~~
]]></expected>)
' passing nested ns to rootnamespace
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace GOO
Namespace BAR
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="GOO.bar"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'BAR' does not match casing of namespace name 'bar' in '<project settings>'.
Namespace BAR
~~~
]]></expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace GOO
Namespace bar
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="GOO.BAR"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'bar' does not match casing of namespace name 'BAR' in '<project settings>'.
Namespace bar
~~~
]]></expected>)
' passing nested ns to rootnamespace
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace goo
Namespace BAR
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="GOO.BAR"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'goo' does not match casing of namespace name 'GOO' in '<project settings>'.
Namespace goo
~~~
]]></expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace GOO
Namespace BAR
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="goo.BAR"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'GOO' does not match casing of namespace name 'goo' in '<project settings>'.
Namespace GOO
~~~
]]></expected>)
' no warnings if spelling is correct
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="CONSOLEAPPLICATIONVB"))
compilation.AssertNoErrors()
' no warnings if no root namespace is given
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>)
compilation.AssertNoErrors()
' no warnings for global namespace itself
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace GLObAl
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>)
compilation.AssertNoErrors()
End Sub
<WorkItem(528713, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528713")>
<Fact>
Public Sub BC40056WRN_UndefinedOrEmptyNamespaceOrClass1()
Dim options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("BC40056WRN_UndefinedOrEmptyNamespaceOrClass1")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedOrEmptyNamespaceOrClass1">
<file name="a.vb"><![CDATA[
Imports alias1 = ns1.GenStruct(Of String)
Structure GenStruct(Of T)
End Structure
]]></file>
</compilation>,
options:=options
)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'ns1.GenStruct' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports alias1 = ns1.GenStruct(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40056WRN_UndefinedOrEmptyNamespaceOrClass1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UndefinedOrEmptyNamespaceOrClass1">
<file name="a.vb"><![CDATA[
Imports ns1.GOO
Namespace ns1
Module M1
Sub GOO()
End Sub
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'ns1.GOO' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports ns1.GOO
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40056WRN_UndefinedOrEmptyNamespaceOrClass1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedOrEmptyNamespaceOrClass1">
<file name="a.vb"><![CDATA[
Imports Alias2 = System
Imports N12 = Alias2
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'Alias2' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports N12 = Alias2
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40057WRN_UndefinedOrEmptyProjectNamespaceOrClass1()
Dim globalImports = GlobalImport.Parse({"Alias2 = System", "N12 = Alias2"})
Dim options = TestOptions.ReleaseExe.WithGlobalImports(globalImports)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedOrEmpyProjectNamespaceOrClass1">
<file name="a.vb"><![CDATA[
]]></file>
</compilation>, options:=options)
Dim expectedErrors1 = <errors><![CDATA[
BC40057: Namespace or type specified in the project-level Imports 'N12 = Alias2' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(545385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545385")>
<Fact>
Public Sub BC41005WRN_MissingAsClauseinOperator()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class D
Shared Operator +(ByVal x As D) ' BC41005 -> BC42021. "Operator without an 'As' clause; type of Object assumed."
Return Nothing
End Operator
End Class
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict:=OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42021: Operator without an 'As' clause; type of Object assumed.
Shared Operator +(ByVal x As D) ' BC41005 -> BC42021. "Operator without an 'As' clause; type of Object assumed."
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528714"), WorkItem(1070286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070286")>
<Fact()>
Public Sub BC42000WRN_MustShadowOnMultipleInheritance2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustShadowOnMultipleInheritance2">
<file name="a.vb"><![CDATA[
Interface I1
Sub goo(ByVal arg As Integer)
End Interface
Interface I2
Sub goo(ByVal arg As Integer)
End Interface
Interface I3
Inherits I1, I2
Sub goo()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: sub 'goo' shadows an overloadable member declared in the base interface 'I1'. If you want to overload the base method, this method must be declared 'Overloads'.
Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC42014WRN_IndirectlyImplementedBaseMember5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IndirectlyImplementedBaseMember5">
<file name="a.vb"><![CDATA[
Interface I1
Sub goo()
End Interface
Interface I2
Inherits I1
End Interface
Class C1
Implements I1
Public Sub goo() Implements I1.goo
End Sub
End Class
Class C2
Inherits C1
Implements I2
Public Shadows Sub goo() Implements I1.goo
End Sub
End Class
]]></file>
</compilation>)
' BC42014 is deprecated
Dim expectedErrors1 = <errors></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC42015WRN_ImplementedBaseMember4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementedBaseMember4">
<file name="a.vb"><![CDATA[
Imports System
Class c1
Implements IDisposable
Public Sub Dispose1() Implements System.IDisposable.Dispose
End Sub
End Class
Class c2
Inherits c1
Implements IDisposable
Public Sub Dispose1() Implements System.IDisposable.Dispose
End Sub
End Class
]]></file>
</compilation>)
' BC42015 is deprecated
Dim expectedErrors1 = <errors><![CDATA[
BC40003: sub 'Dispose1' shadows an overloadable member declared in the base class 'c1'. If you want to overload the base method, this method must be declared 'Overloads'.
Public Sub Dispose1() Implements System.IDisposable.Dispose
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539499")>
<Fact>
Public Sub BC42020WRN_ObjectAssumedVar1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Dim y() = New Object() {3}
End Sub
Public Fld
Public Function Goo(ByVal x) As Integer
Return 1
End Function
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe.WithOptionInfer(False).WithOptionStrict(OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42020: Variable declaration without an 'As' clause; type of Object assumed.
Dim y() = New Object() {3}
~
BC42020: Variable declaration without an 'As' clause; type of Object assumed.
Public Fld
~~~
BC42020: Variable declaration without an 'As' clause; type of Object assumed.
Public Function Goo(ByVal x) As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
compilation1 = compilation1.WithOptions(TestOptions.ReleaseExe.WithOptionInfer(False).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(compilation1)
End Sub
<WorkItem(539499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539499")>
<WorkItem(529849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529849")>
<Fact()>
Public Sub BC42020WRN_ObjectAssumedVar1WithStaticLocal()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Static x = 3
End Sub
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42020: Static variable declared without an 'As' clause; type of Object assumed.
Static x = 3
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
compilation1 = compilation1.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(compilation1)
compilation1 = compilation1.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static x = 3
~
]]></expected>)
End Sub
<Fact>
Public Sub ValidTypeNameAsVariableNameInAssignment()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Imports System
Namespace NS
End Namespace
Module Program2
Sub Main2(args As System.String())
DateTime = "hello"
NS = "hello"
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors><![CDATA[
BC30110: 'Date' is a structure type and cannot be used as an expression.
DateTime = "hello"
~~~~~~~~
BC30112: 'NS' is a namespace and cannot be used as an expression.
NS = "hello"
~~
]]></errors>)
End Sub
<Fact>
Public Sub BC30209ERR_StrictDisallowImplicitObject()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Public Fld
End Module
]]></file>
</compilation>, TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation1,
<errors><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public Fld
~~~
]]></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Dim y() = New Object() {3}
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe.WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation2, <errors/>)
compilation2 = compilation2.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(False).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation2,
<errors><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim y() = New Object() {3}
~
]]></errors>)
End Sub
<WorkItem(529849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529849")>
<Fact>
Public Sub BC30209ERR_StrictDisallowImplicitObjectWithStaticLocals()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BC30209ERR_StrictDisallowImplicitObjectWithStaticLocals">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Static x = 3
End Sub
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation1,
<errors><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static x = 3
~
]]></errors>)
End Sub
<WorkItem(539501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539501")>
<Fact>
Public Sub BC42021WRN_ObjectAssumed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Function Func1()
Return 3
End Function
Sub Main()
End Sub
Delegate Function Func2()
ReadOnly Property Prop3
Get
Return Nothing
End Get
End Property
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom).WithOptionInfer(True))
Dim expectedErrors1 = <errors><![CDATA[
BC42021: Function without an 'As' clause; return type of Object assumed.
Function Func1()
~~~~~
BC42021: Function without an 'As' clause; return type of Object assumed.
Delegate Function Func2()
~~~~~
BC42022: Property without an 'As' clause; type of Object assumed.
ReadOnly Property Prop3
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
compilation1 = compilation1.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off).WithOptionInfer(True))
CompilationUtils.AssertNoErrors(compilation1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Function Func1()
Return 3
End Function
Sub Main()
End Sub
Delegate Function Func2()
ReadOnly Property Prop3
Get
Return Nothing
End Get
End Property
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On).WithOptionInfer(True))
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Function Func1()
~~~~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Delegate Function Func2()
~~~~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
ReadOnly Property Prop3
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' vbc Module1.vb /target:library /noconfig /optionstrict:custom
<Fact()>
Public Sub BC42022WRN_ObjectAssumedProperty1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ObjectAssumedProperty1">
<file name="a.vb"><![CDATA[
Module Module1
ReadOnly Property p()
Get
Return 2
End Get
End Property
End Module
]]></file>
</compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42022: Property without an 'As' clause; type of Object assumed.
ReadOnly Property p()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' EDMAURER: tested elsewhere
' <Fact()>
' Public Sub BC42102WRN_ComClassPropertySetObject1()
' Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib(
' <compilation name="ComClassPropertySetObject1">
' <file name="a.vb"><![CDATA[
' Imports Microsoft.VisualBasic
' <ComClass()> Public Class Class1
' Public WriteOnly Property prop2(ByVal x As String) As Object
' Set(ByVal Value As Object)
' End Set
' End Property
' End Class
' ]]></file>
' </compilation>)
' Dim expectedErrors1 = <errors><![CDATA[
'BC42102: 'Public WriteOnly Property prop2(x As String) As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.
' Public WriteOnly Property prop2(ByVal x As String) As Object
' ~~~~~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
' End Sub
<Fact()>
Public Sub BC42309WRN_XMLDocCrefAttributeNotFound1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocCrefAttributeNotFound1">
<file name="a.vb">
<![CDATA[
''' <see cref="System.Collections.Generic.List(Of _)"/>
Class E
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocCrefAttributeNotFound1">
<file name="a.vb">
<![CDATA[
''' <see cref="System.Collections.Generic.List(Of _)"/>
Class E
End Class
]]></file>
</compilation>, parseOptions:=VisualBasic.VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors = <errors><![CDATA[
BC42309: XML comment has a tag with a 'cref' attribute 'System.Collections.Generic.List(Of _)' that could not be resolved.
''' <see cref="System.Collections.Generic.List(Of _)"/>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42310WRN_XMLMissingFileOrPathAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLMissingFileOrPathAttribute1">
<file name="a.vb"><![CDATA[
'''<include/>
Class E
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLMissingFileOrPathAttribute1">
<file name="a.vb"><![CDATA[
'''<include/>
Class E
End Class
]]></file>
</compilation>, parseOptions:=VisualBasic.VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored.
'''<include/>
~~~~~~~~~~
BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored.
'''<include/>
~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42312WRN_XMLDocWithoutLanguageElement()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocWithoutLanguageElement">
<file name="a.vb"><![CDATA[
Class E
ReadOnly Property quoteForTheDay() As String
''' <summary>
Get
Return "hello"
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocWithoutLanguageElement">
<file name="a.vb"><![CDATA[
Class E
ReadOnly Property quoteForTheDay() As String
''' <summary>
Get
Return "hello"
End Get
End Property
End Class
]]></file>
</compilation>, parseOptions:=VisualBasic.VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
CompilationUtils.AssertTheseDiagnostics(compilation2,
<errors>
<![CDATA[
BC42312: XML documentation comments must precede member or type declarations.
''' <summary>
~~~~~~~~~~~
BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored.
''' <summary>
~~~~~~~~~
BC42304: XML documentation parse error: '>' expected. XML comment will be ignored.
''' <summary>
~
BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored.
''' <summary>
~
]]>
</errors>)
End Sub
<Fact()>
Public Sub BC42313WRN_XMLDocReturnsOnWriteOnlyProperty()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocReturnsOnWriteOnlyProperty">
<file name="a.vb"><![CDATA[
Class E
''' <returns></returns>
WriteOnly Property quoteForTheDay() As String
set
End set
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocReturnsOnWriteOnlyProperty">
<file name="a.vb"><![CDATA[
Class E
''' <returns></returns>
WriteOnly Property quoteForTheDay() As String
set
End set
End Property
End Class
]]></file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors = <errors><![CDATA[
BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.
''' <returns></returns>
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42314WRN_XMLDocOnAPartialType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="XMLDocOnAPartialType">
<file name="a.vb"><![CDATA[
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="XMLDocOnAPartialType">
<file name="a.vb"><![CDATA[
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary> 3
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary> 4
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary> 5
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
''' <summary> 6
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
]]></file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors = <errors><![CDATA[
BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored.
''' <summary>
~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored.
''' <summary>
~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial interface. XML comments for this interface will be ignored.
''' <summary> 3
~~~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial interface. XML comments for this interface will be ignored.
''' <summary> 4
~~~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial module. XML comments for this module will be ignored.
''' <summary> 5
~~~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial module. XML comments for this module will be ignored.
''' <summary> 6
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42317WRN_XMLDocBadGenericParamTag2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocBadGenericParamTag2">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam name="X">typeparam E1</typeparam>
''' <summary>summary - E1</summary>
''' <remarks>remarks - E1</remarks>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocBadGenericParamTag2">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam name="X">typeparam E1</typeparam>
''' <summary>summary - E1</summary>
''' <remarks>remarks - E1</remarks>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42317: XML comment type parameter 'X' does not match a type parameter on the corresponding 'sub' statement.
''' <typeparam name="X">typeparam E1</typeparam>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42318WRN_XMLDocGenericParamTagWithoutName()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocGenericParamTagWithoutName">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam>typeparam E1</typeparam>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocGenericParamTagWithoutName">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam>typeparam E1</typeparam>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42318: XML comment type parameter must have a 'name' attribute.
''' <typeparam>typeparam E1</typeparam>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42319WRN_XMLDocExceptionTagWithoutCRef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocExceptionTagWithoutCRef">
<file name="a.vb"><![CDATA[
Class Myexception
''' <exception></exception>
Sub Test()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocExceptionTagWithoutCRef">
<file name="a.vb"><![CDATA[
Class Myexception
''' <exception></exception>
Sub Test()
End Sub
End Class
]]></file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42319: XML comment exception must have a 'cref' attribute.
''' <exception></exception>
~~~~~~~~~~~~~~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<WorkItem(541661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541661")>
<Fact()>
Public Sub BC42333WRN_VarianceDeclarationAmbiguous3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="VarianceDeclarationAmbiguous3">
<file name="a.vb"><![CDATA[
Imports System.Xml.Linq
Imports System.Linq
Module M1
Class C1
'COMPILEWARNING : BC42333, "System.Collections.Generic.IEnumerable(Of XDocument)", BC42333, "System.Collections.Generic.IEnumerable(Of XElement)"
Implements System.Collections.Generic.IEnumerable(Of XDocument), System.Collections.Generic.IEnumerable(Of XElement)
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Xml.Linq.XDocument) Implements System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XDocument).GetEnumerator
Return Nothing
End Function
Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator(Of System.Xml.Linq.XElement) Implements System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement).GetEnumerator
Return Nothing
End Function
Public Function GetEnumerator2() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return Nothing
End Function
End Class
End Module
]]></file>
</compilation>, XmlReferences)
Dim expectedErrors1 = <errors><![CDATA[
BC42333: Interface 'System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)' is ambiguous with another implemented interface 'System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XDocument)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements System.Collections.Generic.IEnumerable(Of XDocument), System.Collections.Generic.IEnumerable(Of XElement)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
' vbc Module1.vb /target:library /noconfig /optionstrict:custom
<Fact()>
Public Sub BC42347WRN_MissingAsClauseinFunction()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinFunction">
<file name="a.vb"><![CDATA[
Module M1
Function Goo()
Return Nothing
End Function
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict:=OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42021: Function without an 'As' clause; return type of Object assumed.
Function Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
#End Region
' Check that errors are reported for type parameters.
<Fact>
Public Sub TypeParameterErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class X(Of T$)
End Class
Partial Class Y(Of T, U)
End Class
Class Z(Of T, In U, Out V)
End Class
Interface IZ(Of T, In U, Out V)
End Interface
]]></file>
<file name="b.vb"><![CDATA[
Partial Class Y(Of T, V)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32041: Type character cannot be used in a type parameter declaration.
Class X(Of T$)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class Z(Of T, In U, Out V)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class Z(Of T, In U, Out V)
~~~
BC30931: Type parameter name 'V' does not match the name 'U' of the corresponding type parameter defined on one of the other partial types of 'Y'.
Partial Class Y(Of T, V)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
'Check that errors are reported for multiple type arguments
<Fact>
Public Sub MultipleTypeArgumentErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Class G(Of T)
Dim x As G(Of System.Int64,
System.Collections.Hashtable)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32043: Too many type arguments to 'G(Of T)'.
Dim x As G(Of System.Int64,
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
' Check that errors are reported for duplicate option statements in a single file.
<Fact>
Public Sub BC30225ERR_DuplicateOption1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Compare Text
Option Infer On
Option Compare On
]]></file>
<file name="b.vb"><![CDATA[
Option Strict On
Option Infer On
Option Strict On
Option Explicit
Option Explicit Off
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30225: 'Option Compare' statement can only appear once per file.
Option Compare On
~~~~~~~~~~~~~~~
BC30207: 'Option Compare' must be followed by 'Text' or 'Binary'.
Option Compare On
~~
BC30225: 'Option Strict' statement can only appear once per file.
Option Strict On
~~~~~~~~~~~~~~~~
BC30225: 'Option Explicit' statement can only appear once per file.
Option Explicit Off
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC31393ERR_ExpressionHasTheTypeWhichIsARestrictedType()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub M(tr As System.TypedReference)
Dim t = tr.GetType()
End Sub
End Module
]]></file>
</compilation>).VerifyDiagnostics()
End Sub
' Check that errors are reported for import statements in a single file.
<Fact>
Public Sub ImportErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports N1(Of String)
Imports A = N1
Imports B = N1
Imports N1.M1
Imports N1.M1
Imports A = N1.N2.C
Imports N3
Imports N1.N2
Imports N1.Gen(Of C)
Imports N1.Gen(Of Integer, String)
Imports System$.Collections%
Imports D$ = System.Collections
Imports N3
Imports System.Cheesecake.Frosting
]]></file>
<file name="b.vb"><![CDATA[
Namespace N1
Class Gen(Of T)
End Class
Module M1
End Module
End Namespace
Namespace N1.N2
Class C
End Class
End Namespace
Namespace N3
Class D
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32045: 'N1' has no type parameters and so cannot have type arguments.
Imports N1(Of String)
~~~~~~~~~~~~~
BC31051: Namespace or type 'M1' has already been imported.
Imports N1.M1
~~~~~
BC30572: Alias 'A' is already declared.
Imports A = N1.N2.C
~
BC30002: Type 'C' is not defined.
Imports N1.Gen(Of C)
~
BC32043: Too many type arguments to 'Gen(Of T)'.
Imports N1.Gen(Of Integer, String)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30468: Type declaration characters are not valid in this context.
Imports System$.Collections%
~~~~~~~
BC30468: Type declaration characters are not valid in this context.
Imports System$.Collections%
~~~~~~~~~~~~
BC31398: Type characters are not allowed on Imports aliases.
Imports D$ = System.Collections
~~
BC31051: Namespace or type 'N3' has already been imported.
Imports N3
~~
BC40056: Namespace or type specified in the Imports 'System.Cheesecake.Frosting' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports System.Cheesecake.Frosting
~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
' Check that errors are reported for import statements in a single file.
<Fact>
Public Sub ProjectImportErrors()
Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing
Dim globalImports = GlobalImport.Parse({
"N1(Of String)",
"A = N1",
"B = N1",
"N1.M1",
"N1.M1",
"A = N1.N2.C",
"N3",
"N1.N2",
"N1.Gen(Of C)",
"N1.Gen(Of Integer, String)",
"System$.Collections%",
"D$ = System.Collections",
"N3",
"System.Cheesecake.Frosting"
}, diagnostics)
Assert.NotEqual(diagnostics, Nothing)
CompilationUtils.AssertTheseDiagnostics(diagnostics,
<errors><![CDATA[
BC31398: Error in project-level import 'D$ = System.Collections' at 'D$' : Type characters are not allowed on Imports aliases.
]]></errors>)
' only include the imports with correct syntax:
Dim options = TestOptions.ReleaseDll.WithGlobalImports(globalImports)
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="b.vb"><![CDATA[
Namespace N1
Class Gen(Of T)
End Class
Module M1
End Module
End Namespace
Namespace N1.N2
Class C
End Class
End Namespace
Namespace N3
Class D
End Class
End Namespace
]]></file>
</compilation>, options)
Dim expectedErrors = <errors><![CDATA[
BC30002: Error in project-level import 'N1.Gen(Of C)' at 'C' : Type 'C' is not defined.
BC30468: Error in project-level import 'System$.Collections%' at 'Collections%' : Type declaration characters are not valid in this context.
BC30468: Error in project-level import 'System$.Collections%' at 'System$' : Type declaration characters are not valid in this context.
BC30572: Error in project-level import 'A = N1.N2.C' at 'A' : Alias 'A' is already declared.
BC32043: Error in project-level import 'N1.Gen(Of Integer, String)' at 'N1.Gen(Of Integer, String)' : Too many type arguments to 'Gen(Of T)'.
BC32045: Error in project-level import 'N1(Of String)' at 'N1(Of String)' : 'N1' has no type parameters and so cannot have type arguments.
BC40057: Namespace or type specified in the project-level Imports 'System.Cheesecake.Frosting' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub ModifierErrorsInsideNamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace n1
Shadows Enum e6
x
End Enum
Private Enum e7
x
End Enum
End Namespace
Shadows Enum e8
x
End Enum
Private Enum e9
x
End Enum
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32200: 'e6' cannot be declared 'Shadows' outside of a class, structure, or interface.
Shadows Enum e6
~~
BC31089: Types declared 'Private' must be inside another type.
Private Enum e7
~~
BC32200: 'e8' cannot be declared 'Shadows' outside of a class, structure, or interface.
Shadows Enum e8
~~
BC31089: Types declared 'Private' must be inside another type.
Private Enum e9
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub ModifierErrorsInsideInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface i
Private Class c1
End Class
Shared Class c2
End Class
MustInherit Class c3
End Class
MustOverride Class c4
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31070: Class in an interface cannot be declared 'Private'.
Private Class c1
~~~~~~~
BC30461: Classes cannot be declared 'Shared'.
Shared Class c2
~~~~~~
BC30461: Classes cannot be declared 'MustOverride'.
MustOverride Class c4
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
' Checks for accessibility across partial types
<Fact>
Public Sub ModifierErrorsAcrossPartialTypes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Partial public Class c1
End Class
Partial friend Class c1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30925: Specified access 'Friend' for 'c1' does not match the access 'Public' specified on one of its other partial types.
Partial friend Class c1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
NotInheritable class A
end class
Partial MustInherit Class A
End class
]]></file>
</compilation>)
Dim expectedErrors2 = <errors><![CDATA[
BC30926: 'MustInherit' cannot be specified for partial type 'A' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.
Partial MustInherit Class A
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation2, expectedErrors2)
End Sub
' Checks for missing partial on classes
<Fact>
Public Sub ModifierWarningsAcrossPartialTypes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class cc1
End Class
Class cC1
End Class
partial Class Cc1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40046: class 'cc1' and partial class 'Cc1' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Class cc1
~~~
BC40046: class 'cC1' and partial class 'Cc1' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Class cC1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class cc1
End Class
Class cC1
End Class
Class Cc1
End Class
]]></file>
</compilation>)
Dim expectedErrors2 = <errors><![CDATA[
BC30179: class 'cC1' and class 'cc1' conflict in namespace '<Default>'.
Class cC1
~~~
BC30179: class 'Cc1' and class 'cc1' conflict in namespace '<Default>'.
Class Cc1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation2, expectedErrors2)
End Sub
<Fact>
Public Sub ErrorTypeNotDefineType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim errs = compilation.GetDeclarationDiagnostics()
Assert.Equal(1, errs.Length())
Dim err = DirectCast(errs.Single(), Diagnostic)
Assert.Equal(DirectCast(ERRID.ERR_UndefinedType1, Integer), err.Code)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers()(1), FieldSymbol)
Dim sym = fsym.Type
Assert.Equal(SymbolKind.ErrorType, sym.Kind)
Assert.Equal("B", sym.Name)
Assert.Null(sym.ContainingAssembly)
Assert.Null(sym.ContainingSymbol)
Assert.Equal(Accessibility.Public, sym.DeclaredAccessibility)
Assert.False(sym.IsShared)
Assert.False(sym.IsMustOverride)
Assert.False(sym.IsNotOverridable)
Assert.False(sym.IsValueType)
Assert.True(sym.IsReferenceType)
Assert.Equal(0, sym.Interfaces.Length())
Assert.Null(sym.BaseType)
Assert.Equal("B", DirectCast(sym, ErrorTypeSymbol).ConstructedFrom.ToTestDisplayString())
Assert.Equal(0, sym.GetAttributes().Length()) ' Enumerable.Empty<SymbolAttribute>()
Assert.Equal(0, sym.GetMembers().Length()) ' Enumerable.Empty<Symbol>()
Assert.Equal(0, sym.GetMembers(String.Empty).Length())
Assert.Equal(0, sym.GetTypeMembers().Length()) ' Enumerable.Empty<NamedTypeSymbol>()
Assert.Equal(0, sym.GetTypeMembers(String.Empty).Length())
Assert.Equal(0, sym.GetTypeMembers(String.Empty, 0).Length())
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClass()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31447: Class 'B' cannot reference itself in Inherits clause.
Inherits B.C.X
~
]]></errors>)
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClass2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
Public Class A
End Class
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31447: Class 'B' cannot reference itself in Inherits clause.
Inherits B.C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
Public Class A
End Class
End Class
End Class
Class B
Inherits C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface A
Class X
End Class
End Interface
Class B
Inherits C.X
Public Interface C
Inherits A
End Interface
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass6()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
End Class
End Class
Class B
Inherits C(Of Integer).X
Public Class C(Of T)
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C(Of Integer)' in Inherits clause.
Inherits C(Of Integer).X
~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass7()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
Class A
End Class
End Class
End Class
Class B
Inherits D.X
Public Class C
Inherits A
End Class
End Class
Class D
Inherits B.C
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31449: Inherits clause of class 'B' causes cyclic dependency:
'B.C' is nested in 'B'.
Base type of 'B' needs 'B.C' to be resolved.
Inherits D.X
~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass8()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
Class A
End Class
End Class
End Class
Class B
Inherits D
Public Class C
Inherits A
End Class
End Class
Class D
Inherits B.C.X
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31449: Inherits clause of class 'B.C' causes cyclic dependency:
Base type of 'D' needs 'B.C' to be resolved.
Base type of 'B.C' needs 'D' to be resolved.
Inherits A
~
BC30002: Type 'B.C.X' is not defined.
Inherits B.C.X
~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass9()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
Class A
End Class
End Class
End Class
Class B
Inherits D.C.X
Public Class C
Inherits A
End Class
End Class
Class D
Inherits B
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits D.C.X
~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClassA()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IIndia(Of T)
End Interface
Class Alpha
Class Bravo
End Class
End Class
Class Charlie
Inherits Alpha
Implements IIndia(Of Charlie.Bravo)
End Class
Class Echo
Implements IIndia(Of Echo)
End Class
Class Golf
Implements IIndia(Of Golf.Hotel)
Class Hotel
End Class
End Class
Class Juliet
Implements IIndia(Of Juliet.Kilo.Lima)
Class Kilo
Class Lima
End Class
End Class
End Class
Class November(Of T)
End Class
Class Oscar
Inherits November(Of Oscar)
End Class
Class Papa
Inherits November(Of Papa.Quebec)
Class Quebec
End Class
End Class
Class Romeo
Inherits November(Of Romeo.Sierra.Tango)
Class Sierra
Class Tango
End Class
End Class
End Class
Class Uniform
Implements Uniform.IIndigo
Interface IIndigo
End Interface
End Class
Interface IBlah
Inherits Victor.IIdiom
End Interface
Class Victor
Implements IBlah
Interface IIdiom
End Interface
End Class
Class Xray
Implements Yankee.IIda
Class Yankee
Inherits Xray
Interface IIda
End Interface
End Class
End Class
Class Beta
Inherits Gamma
Class Gamma
End Class
End Class
Class Delta
Inherits Delta.Epsilon
Class Epsilon
End Class
End Class
Class Zeta(Of T)
Inherits Eta(Of Beta)
End Class
Class Eta(Of T)
Inherits Zeta(Of Delta)
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'Beta' cannot reference its nested type 'Beta.Gamma' in Inherits clause.
Inherits Gamma
~~~~~
BC31447: Class 'Delta' cannot reference itself in Inherits clause.
Inherits Delta.Epsilon
~~~~~
BC30257: Class 'Zeta(Of T)' cannot inherit from itself:
'Zeta(Of T)' inherits from 'Eta(Of Beta)'.
'Eta(Of Beta)' inherits from 'Zeta(Of T)'.
Inherits Eta(Of Beta)
~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessInterfaceThroughNestedClass()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Interface X
End Interface
End Class
Class B
Implements B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClassSemantic_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve X from 'Inherits B.C.X' first, then 'Inherits A'
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClassSemantic_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve 'Inherits A', then X from 'Inherits B.C.X' first
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessInterfaceThroughNestedClassSemantic_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Interface X
End Interface
End Class
Class B
Implements B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve X from 'Inherits B.C.X' first, then 'Implements A'
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessInterfaceThroughNestedClassSemantic_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Interface X
End Interface
End Class
Class B
Implements B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve 'Inherits A', then X from 'Implements B.C.X' first
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
End Sub
<Fact>
Public Sub InterfaceModifierErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Static Interface i1
End Interface
Static Class c1
End Class
Static Structure s1
End Structure
Static Enum e1
dummy
End Enum
Static Delegate Sub s()
Static Module m
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30397: 'Static' is not valid on an Interface declaration.
Static Interface i1
~~~~~~
BC30461: Classes cannot be declared 'Static'.
Static Class c1
~~~~~~
BC30395: 'Static' is not valid on a Structure declaration.
Static Structure s1
~~~~~~
BC30396: 'Static' is not valid on an Enum declaration.
Static Enum e1
~~~~~~
BC30385: 'Static' is not valid on a Delegate declaration.
Static Delegate Sub s()
~~~~~~
BC31052: Modules cannot be declared 'Static'.
Static Module m
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BaseClassErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="1.vb"><![CDATA[
Option Strict On
Class C1
Inherits Object, Object
End Class
Class C11
Inherits System.Exception
Inherits System.Exception
End Class
Class C2
Inherits System.Collections.ArrayList, System.Collections.Generic.List(Of Integer)
End Class
Class C3(Of T)
Inherits T
End Class
Partial Class C4
Inherits System.Collections.ArrayList
End Class
NotInheritable Class NI
End class
]]></file>
<file name="a.vb"><![CDATA[
Option Strict Off
Public Partial Class C4
Inherits System.Collections.Generic.List(Of Integer)
End Class
Interface I1
End Interface
Class C5
Inherits I1
End Class
Class C6
Inherits System.Guid
End Class
Class C7
Inherits NI
End Class
Class C8
Inherits System.Delegate
End Class
Module M1
Inherits System.Object
End Module
Structure S1
Inherits System.Collections.Hashtable
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits Object, Object
~~~~~~~~~~~~~~~~~~~~~~~
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits System.Exception
~~~~~~~~~~~~~~~~~~~~~~~~~
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits System.Collections.ArrayList, System.Collections.Generic.List(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32055: Class 'C3' cannot inherit from a type parameter.
Inherits T
~
BC30928: Base class 'List(Of Integer)' specified for class 'C4' cannot be different from the base class 'ArrayList' of one of its other partial types.
Inherits System.Collections.Generic.List(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30258: Classes can inherit only from other classes.
Inherits I1
~~
BC30258: Classes can inherit only from other classes.
Inherits System.Guid
~~~~~~~~~~~
BC30299: 'C7' cannot inherit from class 'NI' because 'NI' is declared 'NotInheritable'.
Inherits NI
~~
BC30015: Inheriting from '[Delegate]' is not valid.
Inherits System.Delegate
~~~~~~~~~~~~~~~
BC30230: 'Inherits' not valid in Modules.
Inherits System.Object
~~~~~~~~~~~~~~~~~~~~~~
BC30628: Structures cannot have 'Inherits' statements.
Inherits System.Collections.Hashtable
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BaseClassErrors2a()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class B(Of T)
Class Inner
End Class
End Class
Class D1
Inherits B(Of Integer)
Dim x As B(Of D1.Inner)
End Class
Class D2
Inherits B(Of D2.Inner)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30002: Type 'D2.Inner' is not defined.
Inherits B(Of D2.Inner)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BaseClassErrors2b()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class XC
Inherits XB(Of XD.Inner2)
End Class
Class XD
Inherits XB(Of XC.Inner2)
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31449: Inherits clause of class 'XC' causes cyclic dependency:
Base type of 'XD' needs 'XC' to be resolved.
Base type of 'XC' needs 'XD' to be resolved.
Inherits XB(Of XD.Inner2)
~~~~~~~~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XB(Of XC.Inner2)
~~~~~~~~~
]]></errors>)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2c()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class X0
Inherits XB(Of X1.Inner2)
End Class
Class X1
Inherits XB(Of X2.Inner2)
End Class
Class X2
Inherits XB(Of X3.Inner2)
End Class
Class X3
Inherits XB(Of X4.Inner2)
End Class
Class X4
Inherits XB(Of X5.Inner2)
End Class
Class X5
Inherits XB(Of X6.Inner2)
End Class
Class X6
Inherits XB(Of X7.Inner2)
End Class
Class X7
Inherits XB(Of X8.Inner2)
End Class
Class X8
Inherits XB(Of X9.Inner2)
End Class
Class X9
Inherits XB(Of X0.Inner2)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31449: Inherits clause of class 'X0' causes cyclic dependency:
Base type of 'X1' needs 'X2' to be resolved.
Base type of 'X2' needs 'X3' to be resolved.
Base type of 'X3' needs 'X4' to be resolved.
Base type of 'X4' needs 'X5' to be resolved.
Base type of 'X5' needs 'X6' to be resolved.
Base type of 'X6' needs 'X7' to be resolved.
Base type of 'X7' needs 'X8' to be resolved.
Base type of 'X8' needs 'X9' to be resolved.
Base type of 'X9' needs 'X0' to be resolved.
Base type of 'X0' needs 'X1' to be resolved.
Inherits XB(Of X1.Inner2)
~~~~~~~~~~~~~~~~
BC30002: Type 'X0.Inner2' is not defined.
Inherits XB(Of X0.Inner2)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2d()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class X0
Inherits XB(Of X9.Inner2) ' X0
End Class
Class X1
Inherits XB(Of X9.Inner2) ' X1
End Class
Class X2
Inherits XB(Of X1.Inner2)
End Class
Class X3
Inherits XB(Of X2.Inner2)
End Class
Class X4
Inherits XB(Of X3.Inner2)
End Class
Class X5
Inherits XB(Of X4.Inner2)
End Class
Class X6
Inherits XB(Of X5.Inner2)
End Class
Class X7
Inherits XB(Of X6.Inner2)
End Class
Class X8
Inherits XB(Of X7.Inner2)
End Class
Class X9
Inherits XB(Of X8.Inner2)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31449: Inherits clause of class 'X1' causes cyclic dependency:
Base type of 'X9' needs 'X8' to be resolved.
Base type of 'X8' needs 'X7' to be resolved.
Base type of 'X7' needs 'X6' to be resolved.
Base type of 'X6' needs 'X5' to be resolved.
Base type of 'X5' needs 'X4' to be resolved.
Base type of 'X4' needs 'X3' to be resolved.
Base type of 'X3' needs 'X2' to be resolved.
Base type of 'X2' needs 'X1' to be resolved.
Base type of 'X1' needs 'X9' to be resolved.
Inherits XB(Of X9.Inner2) ' X1
~~~~~~~~~~~~~~~~
BC30002: Type 'X1.Inner2' is not defined.
Inherits XB(Of X1.Inner2)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2e()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class XC
Inherits XB(Of XD.Inner2)
End Class
Class XD
Inherits XB(Of XC.Inner2)
End Class
Class XE
Inherits XB(Of XC.Inner2)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31449: Inherits clause of class 'XC' causes cyclic dependency:
Base type of 'XD' needs 'XC' to be resolved.
Base type of 'XC' needs 'XD' to be resolved.
Inherits XB(Of XD.Inner2)
~~~~~~~~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XB(Of XC.Inner2)
~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XB(Of XC.Inner2)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2f()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XC
Inherits XD.Inner2
End Class
Class XD
Inherits XC.Inner2
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC30002: Type 'XD.Inner2' is not defined.
Inherits XD.Inner2
~~~~~~~~~
BC31449: Inherits clause of class 'XC' causes cyclic dependency:
Base type of 'XD' needs 'XC' to be resolved.
Base type of 'XC' needs 'XD' to be resolved.
Inherits XD.Inner2
~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XC.Inner2
~~~~~~~~~
]]></errors>)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2g()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XC
Inherits XD.Inner2
End Class
Class XD
Inherits XC.Inner2
Class Inner2
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC30002: Type 'XC.Inner2' is not defined.
Inherits XC.Inner2
~~~~~~~~~
BC31449: Inherits clause of class 'XD' causes cyclic dependency:
'XD.Inner2' is nested in 'XD'.
Base type of 'XD' needs 'XD.Inner2' to be resolved.
Inherits XC.Inner2
~~~~~~~~~
]]></errors>)
Next
End Sub
<Fact>
Public Sub FieldErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Partial Class C
Public Public p as Integer
Public Private q as Integer
Private MustOverride r as Integer
Dim s
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict On
Public Partial Class C
Dim x% As Integer
Dim t ' error only if Option Strict is on
Dim u? as Integer?
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30178: Specifier is duplicated.
Public Public p as Integer
~~~~~~
BC30176: Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.
Public Private q as Integer
~~~~~~~
BC30235: 'MustOverride' is not valid on a member variable declaration.
Private MustOverride r as Integer
~~~~~~~~~~~~
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Dim x% As Integer
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim t ' error only if Option Strict is on
~
BC33100: Nullable modifier cannot be specified on both a variable and its type.
Dim u? as Integer?
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MethodErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Partial Class C
Protected Private Sub m1()
End Sub
NotOverridable MustOverride Sub m2()
NotOverridable Overridable Sub m3()
End Sub
Overridable Overrides Sub m4()
End Sub
Overridable Shared Sub m5()
End Sub
Public Function m6()
End Function
Public Function m7%() as string
End Function
Shadows Overloads Sub m8()
End Sub
Sub m9(Of T$)()
End Sub
Public MustInherit Sub m10()
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Partial Class C
Public Sub x$()
End Sub
End Class
]]></file>
</compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
Dim expectedErrors = <errors><![CDATA[
BC36716: Visual Basic 15.0 does not support Private Protected.
Protected Private Sub m1()
~~~~~~~
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
NotOverridable MustOverride Sub m2()
~~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
NotOverridable MustOverride Sub m2()
~~
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
NotOverridable Overridable Sub m3()
~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
NotOverridable Overridable Sub m3()
~~
BC30730: Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.
Overridable Overrides Sub m4()
~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'Overridable' on a method declaration.
Overridable Shared Sub m5()
~~~~~~~~~~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Function m6()
~~
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Public Function m7%() as string
~~~
BC31408: 'Overloads' and 'Shadows' cannot be combined.
Shadows Overloads Sub m8()
~~~~~~~~~
BC32041: Type character cannot be used in a type parameter declaration.
Sub m9(Of T$)()
~~
BC30242: 'MustInherit' is not valid on a method declaration.
Public MustInherit Sub m10()
~~~~~~~~~~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Public Sub x$()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MethodErrorsInInNotInheritableClass()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
NotInheritable Class c
Overridable Sub s1()
End Sub
NotOverridable Sub s2()
End Sub
MustOverride Sub s3()
Default Sub s4()
End Sub
Protected Sub s5()
End Sub
Protected Friend Sub s6()
End Sub
Overridable Sub New()
End Sub
NotOverridable Sub New(ByVal i1 As Integer)
End Sub
MustOverride Sub New(ByVal i1 As Integer, ByVal i2 As Integer)
Default Sub s4(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer)
End Sub
Protected Sub s5(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal i4 As Integer)
End Sub
Protected Friend Sub s6(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal i4 As Integer, ByVal i5 As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Sub s1()
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Sub s2()
~~~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Sub s3()
~~~~~~~~~~~~
BC30242: 'Default' is not valid on a method declaration.
Default Sub s4()
~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Sub New()
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Sub New(ByVal i1 As Integer)
~~~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Sub New(ByVal i1 As Integer, ByVal i2 As Integer)
~~~~~~~~~~~~
BC30242: 'Default' is not valid on a method declaration.
Default Sub s4(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MethodErrorsInInterfaces1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Public Interface i1
Private Sub m1()
Protected Sub m2()
Friend Sub m3()
Static Sub m4()
Shared Sub m5()
Shadows Sub m6()
MustInherit Sub m7()
Overloads Sub m8()
NotInheritable Sub m9()
Overrides Sub m10()
NotOverridable Sub m11()
MustOverride Sub m12()
ReadOnly Sub m13()
WriteOnly Sub m14()
Dim Sub m15()
Const Sub m16()
Default Sub m17()
WithEvents Sub m18()
Widening Sub m19()
Narrowing Sub m20()
sub m21 implements IEnumerator.MoveNext
sub m22 handles DownButton.Click
Iterator Function I1() as IEnumerable(of Integer)
End Interface
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30270: 'Private' is not valid on an interface method declaration.
Private Sub m1()
~~~~~~~
BC30270: 'Protected' is not valid on an interface method declaration.
Protected Sub m2()
~~~~~~~~~
BC30270: 'Friend' is not valid on an interface method declaration.
Friend Sub m3()
~~~~~~
BC30242: 'Static' is not valid on a method declaration.
Static Sub m4()
~~~~~~
BC30270: 'Shared' is not valid on an interface method declaration.
Shared Sub m5()
~~~~~~
BC30242: 'MustInherit' is not valid on a method declaration.
MustInherit Sub m7()
~~~~~~~~~~~
BC30242: 'NotInheritable' is not valid on a method declaration.
NotInheritable Sub m9()
~~~~~~~~~~~~~~
BC30270: 'Overrides' is not valid on an interface method declaration.
Overrides Sub m10()
~~~~~~~~~
BC30270: 'NotOverridable' is not valid on an interface method declaration.
NotOverridable Sub m11()
~~~~~~~~~~~~~~
BC30270: 'MustOverride' is not valid on an interface method declaration.
MustOverride Sub m12()
~~~~~~~~~~~~
BC30242: 'ReadOnly' is not valid on a method declaration.
ReadOnly Sub m13()
~~~~~~~~
BC30242: 'WriteOnly' is not valid on a method declaration.
WriteOnly Sub m14()
~~~~~~~~~
BC30242: 'Dim' is not valid on a method declaration.
Dim Sub m15()
~~~
BC30242: 'Const' is not valid on a method declaration.
Const Sub m16()
~~~~~
BC30242: 'Default' is not valid on a method declaration.
Default Sub m17()
~~~~~~~
BC30242: 'WithEvents' is not valid on a method declaration.
WithEvents Sub m18()
~~~~~~~~~~
BC30242: 'Widening' is not valid on a method declaration.
Widening Sub m19()
~~~~~~~~
BC30242: 'Narrowing' is not valid on a method declaration.
Narrowing Sub m20()
~~~~~~~~~
BC30270: 'implements' is not valid on an interface method declaration.
sub m21 implements IEnumerator.MoveNext
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30270: 'handles' is not valid on an interface method declaration.
sub m22 handles DownButton.Click
~~~~~~~~~~~~~~~~~~~~~~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
sub m22 handles DownButton.Click
~~~~~~~~~~
BC30270: 'Iterator' is not valid on an interface method declaration.
Iterator Function I1() as IEnumerable(of Integer)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_01()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Shared Sub Handler() Handles EventHost.SomeEvent
End Sub
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Shared Sub Handler() Handles EventHost.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_02()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Sub Handler() Handles EventHost.SomeEvent
End Sub
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Private Sub Handler() Handles EventHost.SomeEvent
~~~~~~~~~
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Sub Handler() Handles EventHost.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_03()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Shared Sub Handler() Handles EventHost.SomeEvent, EventHost2.SomeEvent
End Sub
Protected Shared WithEvents EventHost2 As EventHost
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Shared Sub Handler() Handles EventHost.SomeEvent, EventHost2.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_04()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Shared Sub Handler() Handles EventHost2.SomeEvent, EventHost.SomeEvent
End Sub
Protected Shared WithEvents EventHost2 As EventHost
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Shared Sub Handler() Handles EventHost2.SomeEvent, EventHost.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
Public Sub ErrorTypeSymbol_DefaultMember_CodeCoverageItems()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Coverage">
<file name="a.vb"><![CDATA[
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim errs = compilation.GetDeclarationDiagnostics()
Assert.Equal(1, Enumerable.Count(Of Diagnostic)(errs))
Dim err As Diagnostic = Enumerable.Single(Of Diagnostic)(errs)
Assert.Equal(&H7532, err.Code)
Dim fieldSymb As FieldSymbol = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single.GetMembers.Item(1), FieldSymbol)
Dim symbType As TypeSymbol = fieldSymb.Type
Dim errTypeSym As ErrorTypeSymbol = DirectCast(symbType, ErrorTypeSymbol)
Assert.Equal(SymbolKind.ErrorType, errTypeSym.Kind)
Assert.Equal("B", errTypeSym.Name)
Assert.Null(errTypeSym.ContainingAssembly)
Assert.Null(errTypeSym.ContainingSymbol)
Assert.Equal(Accessibility.Public, errTypeSym.DeclaredAccessibility)
Assert.False(errTypeSym.IsShared)
Assert.False(errTypeSym.IsMustOverride)
Assert.False(errTypeSym.IsNotOverridable)
Assert.False(errTypeSym.IsValueType)
Assert.True(errTypeSym.IsReferenceType)
Assert.Equal(SpecializedCollections.EmptyCollection(Of String), errTypeSym.MemberNames)
Assert.Equal(ImmutableArray.Create(Of Symbol)(), errTypeSym.GetMembers)
Assert.Equal(ImmutableArray.Create(Of Symbol)(), errTypeSym.GetMembers("B"))
Assert.Equal(ImmutableArray.Create(Of NamedTypeSymbol)(), errTypeSym.GetTypeMembers)
Assert.Equal(ImmutableArray.Create(Of NamedTypeSymbol)(), errTypeSym.GetTypeMembers("B"))
Assert.Equal(ImmutableArray.Create(Of NamedTypeSymbol)(), errTypeSym.GetTypeMembers("B", 1))
Assert.Equal(TypeKind.Error, errTypeSym.TypeKind)
Assert.Equal(ImmutableArray.Create(Of Location)(), errTypeSym.Locations)
Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), errTypeSym.DeclaringSyntaxReferences)
Assert.Equal(0, errTypeSym.Arity)
Assert.Null(errTypeSym.EnumUnderlyingType)
Assert.Equal("B", errTypeSym.Name)
Assert.Equal(0, errTypeSym.TypeArguments.Length)
Assert.Equal(0, errTypeSym.TypeParameters.Length)
Assert.Equal(errTypeSym.CandidateSymbols.Length, errTypeSym.IErrorTypeSymbol_CandidateSymbols.Length)
End Sub
<Fact>
Public Sub ConstructorErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Partial Class C
Public Overridable Sub New(x as Integer)
End Sub
MustOverride Sub New(y as String)
NotOverridable Friend Sub New(z as Object)
End Sub
Private Shadows Sub New(z as Object, a as integer)
End Sub
Protected Overloads Sub New(z as Object, a as string)
End Sub
Public Static Sub New(z as string, a as Object)
End Sub
Overrides Sub New()
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Partial Class C
End Class
Public Interface I
Sub New()
End Interface
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30364: 'Sub New' cannot be declared 'Overridable'.
Public Overridable Sub New(x as Integer)
~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'MustOverride'.
MustOverride Sub New(y as String)
~~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'NotOverridable'.
NotOverridable Friend Sub New(z as Object)
~~~~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'Shadows'.
Private Shadows Sub New(z as Object, a as integer)
~~~~~~~
BC32040: The 'Overloads' keyword is used to overload inherited members; do not use the 'Overloads' keyword when overloading 'Sub New'.
Protected Overloads Sub New(z as Object, a as string)
~~~~~~~~~
BC30242: 'Static' is not valid on a method declaration.
Public Static Sub New(z as string, a as Object)
~~~~~~
BC30283: 'Sub New' cannot be declared 'Overrides'.
Overrides Sub New()
~~~~~~~~~
BC30363: 'Sub New' cannot be declared in an interface.
Sub New()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub SharedConstructorErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Class C
Public Shared Sub New() '1
End Sub
Private Shared Sub New() '2
End Sub
Friend Shared Sub New() '3
End Sub
Shared Protected Sub New() '4
End Sub
Shared Protected Friend Sub New() '5
End Sub
Shared Sub New(x as integer) '6
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Module M
Public Sub New() '8
End Sub
Private Sub New() '9
End Sub
Friend Sub New() '10
End Sub
Protected Sub New() '11
End Sub
Protected Friend Sub New() '12
End Sub
Sub New(x as Integer, byref y as string) '13
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors =
<errors><![CDATA[
BC30480: Shared 'Sub New' cannot be declared 'Public'.
Public Shared Sub New() '1
~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Public Shared Sub New() '1
~~~
BC30480: Shared 'Sub New' cannot be declared 'Private'.
Private Shared Sub New() '2
~~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Private Shared Sub New() '2
~~~
BC30480: Shared 'Sub New' cannot be declared 'Friend'.
Friend Shared Sub New() '3
~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Friend Shared Sub New() '3
~~~
BC30480: Shared 'Sub New' cannot be declared 'Protected'.
Shared Protected Sub New() '4
~~~~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Shared Protected Sub New() '4
~~~
BC30480: Shared 'Sub New' cannot be declared 'Protected Friend'.
Shared Protected Friend Sub New() '5
~~~~~~~~~~~~~~~~
BC30479: Shared 'Sub New' cannot have any parameters.
Shared Sub New(x as integer) '6
~~~~~~~~~~~~~~
BC30480: Shared 'Sub New' cannot be declared 'Public'.
Public Sub New() '8
~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Public Sub New() '8
~~~
BC30480: Shared 'Sub New' cannot be declared 'Private'.
Private Sub New() '9
~~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Private Sub New() '9
~~~
BC30480: Shared 'Sub New' cannot be declared 'Friend'.
Friend Sub New() '10
~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Friend Sub New() '10
~~~
BC30433: Methods in a Module cannot be declared 'Protected'.
Protected Sub New() '11
~~~~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Protected Sub New() '11
~~~
BC30433: Methods in a Module cannot be declared 'Protected Friend'.
Protected Friend Sub New() '12
~~~~~~~~~~~~~~~~
BC30479: Shared 'Sub New' cannot have any parameters.
Sub New(x as Integer, byref y as string) '13
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub ParameterErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Partial Class C
Public Sub m1(x)
End Sub
Public Sub m2(byref byval k as Integer)
End Sub
Public Sub m3(byref byref k as Integer)
End Sub
Public Sub m4(ByRef ParamArray x() as string)
End Sub
Public Sub m5(ParamArray q as Integer)
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Partial Class C
Public Sub m8(x, y$)
End Sub
Public Sub m9(x, z As String, w)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Public Sub m1(x)
~
BC30641: 'ByVal' and 'ByRef' cannot be combined.
Public Sub m2(byref byval k as Integer)
~~~~~
BC30785: Parameter specifier is duplicated.
Public Sub m3(byref byref k as Integer)
~~~~~
BC30667: ParamArray parameters must be declared 'ByVal'.
Public Sub m4(ByRef ParamArray x() as string)
~~~~~~~~~~
BC30050: ParamArray parameter must be an array.
Public Sub m5(ParamArray q as Integer)
~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Public Sub m8(x, y$)
~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Public Sub m9(x, z As String, w)
~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Public Sub m9(x, z As String, w)
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MoreParameterErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MoreParameterErrors">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1(f1 as integer) as Integer
return 0
End Function
Function F1(i1 as integer, I1 as integer) as Integer
return 0
End Function
Function F1(of T1) (i1 as integer, t1 as integer) as Integer
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30530: Parameter cannot have the same name as its defining function.
Function F1(f1 as integer) as Integer
~~
BC30237: Parameter already declared with name 'I1'.
Function F1(i1 as integer, I1 as integer) as Integer
~~
BC32089: 't1' is already declared as a type parameter of this method.
Function F1(of T1) (i1 as integer, t1 as integer) as Integer
~~
]]></expected>)
End Sub
<Fact>
Public Sub LocalDeclarationSameAsFunctionNameError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalDeclarationSameAsFunctionNameError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1() as Integer
dim f1 as integer = 0
do
dim f1 As integer = 0
loop
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30290: Local variable cannot have the same name as the function containing it.
dim f1 as integer = 0
~~
BC30290: Local variable cannot have the same name as the function containing it.
dim f1 As integer = 0
~~
]]></expected>)
End Sub
<Fact>
Public Sub DuplicateLocalDeclarationError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalDeclarationError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1() as Integer
dim i as long = 0
dim i as integer = 0
dim j,j as integer
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30288: Local variable 'i' is already declared in the current block.
dim i as integer = 0
~
BC42024: Unused local variable: 'j'.
dim j,j as integer
~
BC30288: Local variable 'j' is already declared in the current block.
dim j,j as integer
~
BC42024: Unused local variable: 'j'.
dim j,j as integer
~
]]></expected>)
End Sub
<Fact>
Public Sub LocalDeclarationTypeParameterError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalDeclarationError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1(of T)() as Integer
dim t as integer = 0
do
dim t as integer = 0
loop
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC32089: 't' is already declared as a type parameter of this method.
dim t as integer = 0
~
BC30616: Variable 't' hides a variable in an enclosing block.
dim t as integer = 0
~
]]></expected>)
End Sub
<Fact>
Public Sub LocalDeclarationParameterError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalDeclarationError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1(p as integer) as Integer
dim p as integer = 0
do
dim p as integer = 0
loop
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30734: 'p' is already declared as a parameter of this method.
dim p as integer = 0
~
BC30616: Variable 'p' hides a variable in an enclosing block.
dim p as integer = 0
~
]]></expected>)
End Sub
' Checks for duplicate type parameters
<Fact>
Public Sub DuplicateMethodTypeParameterErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class BB(Of T)
Class A(Of t1)
Public t1 As Integer
Sub f(Of t, t)()
End Sub
End Class
End Class
Class a(Of t)
Inherits BB(Of t)
Class b
Class c(Of t)
End Class
End Class
End Class
Class base(Of T)
Function TEST(Of T)(ByRef X As T)
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32054: 't1' has the same name as a type parameter.
Public t1 As Integer
~~
BC40048: Type parameter 't' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Sub f(Of t, t)()
~
BC32049: Type parameter already declared with name 't'.
Sub f(Of t, t)()
~
BC40048: Type parameter 't' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Class c(Of t)
~
BC40048: Type parameter 'T' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Function TEST(Of T)(ByRef X As T)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(527182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527182")>
Public Sub DuplicatedNameWithDifferentCases()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AAA">
<file name="a.vb"><![CDATA[
Module Module1
Dim S1 As String
Dim s1 As String
Dim S1 As Integer
Function MyFunc() As Integer
Return 0
End Function
Function MYFUNC() As Integer
Return 0
End Function
Sub Main()
End Sub
End Module
Namespace NS
Partial Public Class AAA
Public BBB As Integer
Friend BBb As Integer
Sub SSS()
End Sub
End Class
Partial Public Class AaA
Public Structure ST1
Shared CH1, ch1 As Char
End Structure
Structure st1
Shared ch1, ch2 As Char
End Structure
End Class
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Namespace Ns
Partial Public Class Aaa
Private Bbb As Integer
Sub Sss()
End Sub
End Class
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim myMod = DirectCast(globalNS.GetMembers("module1").Single(), NamedTypeSymbol)
' no merge for non-namespace/type members
Dim mem1 = myMod.GetMembers("S1")
Assert.Equal(3, mem1.Length) ' 3
mem1 = myMod.GetMembers("myfunc")
Assert.Equal(2, mem1.Length) ' 2
Dim myNS = DirectCast(globalNS.GetMembers("ns").Single(), NamespaceSymbol)
Dim types = myNS.GetMembers("aaa")
Assert.Equal(1, types.Length)
Dim type1 = DirectCast(types.First(), NamedTypeSymbol)
' no merge for fields
Dim mem2 = type1.GetMembers("bbb")
Assert.Equal(3, mem2.Length) ' 3
Dim mem3 = type1.GetMembers("sss")
Assert.Equal(2, mem3.Length) ' 2
Dim mem4 = type1.GetMembers("St1")
Assert.Equal(1, mem4.Length)
Dim type2 = DirectCast(mem4.First(), NamedTypeSymbol)
' from both St1
Dim mem5 = type2.GetMembers("Ch1")
Assert.Equal(3, mem2.Length) ' 3
Dim errs = compilation.GetDeclarationDiagnostics()
' Native compilers 9 errors
Assert.True(errs.Length > 6, "Contain Decl Errors")
End Sub
<WorkItem(537443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537443")>
<Fact>
Public Sub DuplicatedTypes()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub sub1()
Dim element1 = <RootEle>
</RootEle>
End Sub
End Module
'COMPILEERROR: BC30179, "Module1"
Module Module1
Sub sub1()
Dim element1 = <RootEle>
</RootEle>
End Sub
End Module
Namespace GenArityErr001
Public Structure ga001Str2 (Of T As Integer)
Dim i As Integer
End Structure
' BC30179: Name conflict
' COMPILEERROR: BC30179, "ga001Str2"
Public Structure ga001Str2 (Of X As New)
Dim i As Integer
End Structure
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.Assembly.GlobalNamespace
Dim modOfNS = DirectCast(globalNS.GetMembers("Module1").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(modOfNS.GetMembers().First(), MethodSymbol)
Assert.Equal("sub1", mem1.Name)
Dim ns = DirectCast(globalNS.GetMembers("GenArityErr001").First(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetMembers("ga001Str2").First(), NamedTypeSymbol)
Assert.NotEmpty(type1.GetMembers().AsEnumerable())
End Sub
<WorkItem(537443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537443")>
<Fact>
Public Sub InvalidPartialTypes()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Namespace PartialStruct118
Interface ii
Sub abc()
End Interface
'COMPILEWARNING: BC40046, "teststruct"
Structure teststruct
Implements ii
'COMPILEERROR: BC30269, "abc"
Public Sub abc() Implements ii.abc
End Sub
Public Scen5 As String
'COMPILEERROR: BC30269, "Scen6"
Public Sub Scen6(ByVal x As String)
End Sub
'COMPILEERROR: BC30269, "New"
Public Sub New(ByVal x As String)
End Sub
End Structure
'COMPILEERROR: BC32200, "teststruct"
partial Shadows Structure teststruct
End Structure
'COMPILEERROR: BC30395, "MustInherit"
partial MustInherit Structure teststruct
End Structure
'COMPILEERROR: BC30395, "NotInheritable"
partial NotInheritable Structure teststruct
End Structure
'COMPILEERROR: BC30178, "partial"
partial partial structure teststruct
End Structure
partial Structure teststruct
'COMPILEERROR: BC30260, "Scen5"
Public Scen5 As String
Public Sub Scen6(ByVal x As String)
End Sub
End Structure
partial Structure teststruct
'COMPILEERROR: BC30628, "Inherits Scen7"
Inherits scen7
End Structure
partial Structure teststruct
Implements ii
Public Sub New(ByVal x As String)
End Sub
Public Sub abc() Implements ii.abc
End Sub
End Structure
'COMPILEWARNING: BC40046, "teststruct"
Structure teststruct
Dim a As String
End Structure
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.Assembly.GlobalNamespace
Dim ns = DirectCast(globalNS.GetMembers("PartialStruct118").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetTypeMembers("teststruct").First(), NamedTypeSymbol)
Assert.Equal("teststruct", type1.Name)
Assert.NotEmpty(type1.GetMembers().AsEnumerable)
End Sub
<WorkItem(537680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537680")>
<Fact>
Public Sub ModuleWithTypeParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Err">
<file name="a.vb"><![CDATA[
Namespace Regression139822
'COMPILEERROR: BC32073, "(of T)"
Module Module1(of T)
End Module
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim ns = DirectCast(globalNS.GetMembers("Regression139822").Single(), NamespaceSymbol)
Dim myMod = DirectCast(ns.GetMembers("Module1").SingleOrDefault(), NamedTypeSymbol)
Assert.Equal(0, myMod.TypeParameters.Length)
Assert.Equal(0, myMod.Arity)
End Sub
<Fact>
Public Sub Bug4577()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4577">
<file name="a.vb"><![CDATA[
Namespace A.B
End Namespace
Namespace A
Class B
End Class
Class B(Of T)
End Class
End Namespace
Class C
Class D
End Class
Public d As Integer
Class E(Of T)
End Class
Public e As Integer
Class D '2
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30179: class 'B' and namespace 'B' conflict in namespace 'A'.
Class B
~
BC30260: 'd' is already declared as 'Class D' in this class.
Public d As Integer
~
BC30260: 'e' is already declared as 'Class E(Of T)' in this class.
Public e As Integer
~
BC30179: class 'D' and class 'D' conflict in class 'C'.
Class D '2
~
]]></expected>)
End Sub
<Fact>
Public Sub Bug4054()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4054">
<file name="a.vb"><![CDATA[
Module Program
Sub Main()
Dim x(0# To 2)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC32059: Array lower bounds can be only '0'.
Dim x(0# To 2)
~~
]]></expected>)
End Sub
<WorkItem(537507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537507")>
<Fact>
Public Sub ReportErrorTypeCharacterInTypeNameDeclaration()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ReportErrorTypeCharacterInTypeNameDeclaration">
<file name="a.vb"><![CDATA[
Namespace n1#
Class C1#
End Class
Class c2#(of T)
end class
Enum e1#
dummy
end enum
Structure s1#
End structure
End Namespace
Module Program#
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30468: Type declaration characters are not valid in this context.
Namespace n1#
~~~
BC30468: Type declaration characters are not valid in this context.
Class C1#
~~~
BC30468: Type declaration characters are not valid in this context.
Class c2#(of T)
~~~
BC30468: Type declaration characters are not valid in this context.
Enum e1#
~~~
BC30468: Type declaration characters are not valid in this context.
Structure s1#
~~~
BC30468: Type declaration characters are not valid in this context.
Module Program#
~~~~~~~~
]]></errors>)
End Sub
<WorkItem(537507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537507")>
<Fact>
Public Sub ReportErrorTypeCharacterInTypeName()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ReportErrorTypeCharacterInTypeName">
<file name="a.vb"><![CDATA[
Namespace n1
Class C1#
End Class
Class c2#(of T)
public f1 as c1#
end class
End Namespace
Module Program
Dim x1 as C1#
dim x2 as N1.C1#
dim x3 as n1.c2#(of integer)
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30468: Type declaration characters are not valid in this context.
Class C1#
~~~
BC30468: Type declaration characters are not valid in this context.
Class c2#(of T)
~~~
BC30468: Type declaration characters are not valid in this context.
public f1 as c1#
~~~
BC30002: Type 'C1' is not defined.
Dim x1 as C1#
~~~
BC30468: Type declaration characters are not valid in this context.
Dim x1 as C1#
~~~
BC30468: Type declaration characters are not valid in this context.
dim x2 as N1.C1#
~~~
BC30468: Type declaration characters are not valid in this context.
dim x3 as n1.c2#(of integer)
~~~
]]></errors>)
End Sub
<WorkItem(540895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540895")>
<Fact>
Public Sub BC31538ERR_FriendAssemblyBadAccessOverride2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassLibrary1">
<file name="a.vb"><![CDATA[
Imports System
Public Class A
Protected Friend Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
]]></file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ConsoleApp">
<file name="c.vb"><![CDATA[
Imports System
Imports ClassLibrary1
MustInherit Class B
Inherits A
Protected Friend Overrides Sub G()
End Sub
End Class
]]></file>
</compilation>, {New VisualBasicCompilationReference(compilation1)})
CompilationUtils.AssertTheseDiagnostics(compilation2, <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'ClassLibrary1' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports ClassLibrary1
~~~~~~~~~~~~~
BC31538: Member 'Protected Friend Overrides Sub G()' cannot override member 'Protected Friend Overridable Sub G()' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.
Protected Friend Overrides Sub G()
~
]]></errors>)
End Sub
' Note that the candidate symbols infrastructure on error types is tested heavily in
' the SemanticModel tests. The following tests just make sure the public
' API is working correctly.
Public Sub ErrorTypeCandidateSymbols1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Option Strict On
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers("n").First(), FieldSymbol)
Dim typ = fsym.Type
Assert.Equal(SymbolKind.ErrorType, typ.Kind)
Assert.Equal("B", typ.Name)
Dim errortype = DirectCast(typ, ErrorTypeSymbol)
Assert.Equal(CandidateReason.None, errortype.CandidateReason)
Assert.Equal(0, errortype.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub ErrorTypeCandidateSymbols2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Private Class B
End Class
End Class
Class A
Inherits C
Dim n As B
End Class
]]></file>
</compilation>)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim classB = DirectCast(DirectCast(compilation.GlobalNamespace.GetTypeMembers("C").Single(), NamedTypeSymbol).GetTypeMembers("B").Single, NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers("n").First(), FieldSymbol)
Dim typ = fsym.Type
Assert.Equal(SymbolKind.ErrorType, typ.Kind)
Assert.Equal("B", typ.Name)
Dim errortyp = DirectCast(typ, ErrorTypeSymbol)
Assert.Equal(CandidateReason.Inaccessible, errortyp.CandidateReason)
Assert.Equal(1, errortyp.CandidateSymbols.Length)
Assert.Equal(classB, errortyp.CandidateSymbols(0))
End Sub
<Fact()>
Public Sub ErrorTypeCandidateSymbols3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Option Strict On
Imports N1, N2
Namespace N1
Class B
End Class
End Namespace
Namespace N2
Class B
End Class
End Namespace
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim classB1 = DirectCast(DirectCast(compilation.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol).GetTypeMembers("B").Single, NamedTypeSymbol)
Dim classB2 = DirectCast(DirectCast(compilation.GlobalNamespace.GetMembers("N2").Single(), NamespaceSymbol).GetTypeMembers("B").Single, NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers("n").First(), FieldSymbol)
Dim typ = fsym.Type
Assert.Equal(SymbolKind.ErrorType, typ.Kind)
Assert.Equal("B", typ.Name)
Dim errortyp = DirectCast(typ, ErrorTypeSymbol)
Assert.Equal(CandidateReason.Ambiguous, errortyp.CandidateReason)
Assert.Equal(2, errortyp.CandidateSymbols.Length)
Assert.True((TypeSymbol.Equals(classB1, TryCast(errortyp.CandidateSymbols(0), TypeSymbol), TypeCompareKind.ConsiderEverything) AndAlso
TypeSymbol.Equals(classB2, TryCast(errortyp.CandidateSymbols(1), TypeSymbol), TypeCompareKind.ConsiderEverything)) OrElse
(TypeSymbol.Equals(classB2, TryCast(errortyp.CandidateSymbols(0), TypeSymbol), TypeCompareKind.ConsiderEverything) AndAlso
TypeSymbol.Equals(classB1, TryCast(errortyp.CandidateSymbols(1), TypeSymbol), TypeCompareKind.ConsiderEverything)), "should have B1 and B2 in some order")
End Sub
<Fact()>
Public Sub TypeArgumentOfFriendType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="E">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleTo("goo")>
Friend Class ImmutableStack(Of T)
End Class
]]></file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="goo">
<file name="a.vb"><![CDATA[
Friend Class Scanner
Protected Class ConditionalState
End Class
Protected Class PreprocessorState
Friend ReadOnly _conditionals As ImmutableStack(Of ConditionalState)
End Class
End Class
]]></file>
</compilation>, {New VisualBasicCompilationReference(compilation)})
Assert.Empty(compilation2.GetDiagnostics())
End Sub
<Fact, WorkItem(544071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544071")>
Public Sub ProtectedTypeExposureGeneric()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="E">
<file name="a.vb"><![CDATA[
Friend Class B(Of T)
Protected Enum ENM
None
End Enum
End Class
Class D
Inherits B(Of Integer)
Protected Sub proc(p1 As ENM)
End Sub
Protected Sub proc(p1 As B(Of Long).ENM)
End Sub
End Class
]]></file>
</compilation>)
Dim diags = compilation.GetDiagnostics()
Assert.Empty(diags)
End Sub
<Fact, WorkItem(574771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574771")>
Public Sub Bug574771()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Interface vbGI6504Int1(Of X)
End Interface
Public Interface vbGI6504Int2(Of T, U)
Function Fun2(ByVal p1 As T, ByVal t2 As U) As Long
End Interface
Public Interface vbGI6504Int3(Of T)
Inherits vbGI6504Int1(Of T)
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
End Interface
Public Class vbGI6504Cls1(Of X)
Implements vbGI6504Int3(Of X)
Public Function Fun2(ByVal p1 As X, ByVal t2 As X) As Long Implements vbGI6504Int2(Of X, X).Fun2
Return 12000L
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32042: Too few type arguments to 'vbGI6504Int2(Of T, U)'.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~~~~~~~~~~~~~~~
BC32093: 'Of' required when specifying type arguments for a generic type or method.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC30002: Type 'O' is not defined.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC30198: ')' expected.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC32055: Interface 'vbGI6504Int3' cannot inherit from a type parameter.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC31035: Interface 'vbGI6504Int2(Of X, X)' is not implemented by this class.
Public Function Fun2(ByVal p1 As X, ByVal t2 As X) As Long Implements vbGI6504Int2(Of X, X).Fun2
~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(578723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578723")>
Public Sub Bug578723()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I(Of T)
Sub Goo(Optional x As Integer = Nothing)
End Interface
Class C
Implements I(Of Integer)
Public Sub Goo(Optional x As Integer = 0) Implements (Of Integer).Goo
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'C' must implement 'Sub Goo([x As Integer = 0])' for interface 'I(Of Integer)'.
Implements I(Of Integer)
~~~~~~~~~~~~~
BC30203: Identifier expected.
Public Sub Goo(Optional x As Integer = 0) Implements (Of Integer).Goo
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(783920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/783920")>
<Fact()>
Public Sub Bug783920()
Dim comp1 = CreateCompilationWithMscorlib40(
<compilation name="Bug783920_VB">
<file name="a.vb"><![CDATA[
Public Class MyAttribute1
Inherits System.Attribute
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll)
Dim comp2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Public Class MyAttribute2
Inherits MyAttribute1
End Class
]]></file>
</compilation>, {New VisualBasicCompilationReference(comp1)}, TestOptions.ReleaseDll)
Dim source3 =
<compilation>
<file name="a.vb"><![CDATA[
<MyAttribute2>
Public Class Test
End Class
]]></file>
</compilation>
Dim expected =
<expected><![CDATA[
BC30652: Reference required to assembly 'Bug783920_VB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'MyAttribute1'. Add one to your project.
<MyAttribute2>
~~~~~~~~~~~~
]]></expected>
Dim comp4 = CreateCompilationWithMscorlib40AndReferences(source3, {comp2.EmitToImageReference()}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(comp4, expected)
Dim comp3 = CreateCompilationWithMscorlib40AndReferences(source3, {New VisualBasicCompilationReference(comp2)}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(comp3, expected)
End Sub
<Fact()>
Public Sub BC30166ERR_ExpectedNewableClass1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Friend Module AttrRegress006mod
' Need this attribute
<System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)>
Class test
End Class
Sub AttrRegress006()
'COMPILEERROR: BC30166, "Test" EDMAURER no longer giving this error.
Dim c As New test
End Sub
End Module]]></file>
</compilation>)
Dim expectedErrors1 = <errors></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(528709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528709")>
Public Sub Bug528709()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Enum TestEnum
One
One
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31421: 'One' is already declared in this enum.
One
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(529327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529327")>
Public Sub Bug529327()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I1
Property Bar As Integer
Sub Goo()
End Interface
Interface I2
Inherits I1
Property Bar As Integer
Sub Goo()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: property 'Bar' shadows an overloadable member declared in the base interface 'I1'. If you want to overload the base method, this method must be declared 'Overloads'.
Property Bar As Integer
~~~
BC40003: sub 'Goo' shadows an overloadable member declared in the base interface 'I1'. If you want to overload the base method, this method must be declared 'Overloads'.
Sub Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(531353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531353")>
Public Sub Bug531353()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class c1
Shared Operator +(ByVal x As c1, ByVal y As c2) As Integer
Return 0
End Operator
End Class
Class c2
Inherits c1
'COMPILEWARNING: BC40003, "+"
Shared Operator +(ByVal x As c1, ByVal y As c2) As Integer
Return 0
End Operator
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: operator 'op_Addition' shadows an overloadable member declared in the base class 'c1'. If you want to overload the base method, this method must be declared 'Overloads'.
Shared Operator +(ByVal x As c1, ByVal y As c2) As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(1068209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068209")>
Public Sub Bug1068209_01()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I1
ReadOnly Property P1 As Integer
Sub get_P2()
Event E1 As System.Action
Sub remove_E2()
End Interface
Interface I3
Inherits I1
Overloads Sub get_P1()
Overloads Property P2 As Integer
Overloads Sub add_E1()
Event E2 As System.Action
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40014: sub 'get_P1' conflicts with a member implicitly declared for property 'P1' in the base interface 'I1' and should be declared 'Shadows'.
Overloads Sub get_P1()
~~~~~~
BC40012: property 'P2' implicitly declares 'get_P2', which conflicts with a member in the base interface 'I1', and so the property should be declared 'Shadows'.
Overloads Property P2 As Integer
~~
BC40014: sub 'add_E1' conflicts with a member implicitly declared for event 'E1' in the base interface 'I1' and should be declared 'Shadows'.
Overloads Sub add_E1()
~~~~~~
BC40012: event 'E2' implicitly declares 'remove_E2', which conflicts with a member in the base interface 'I1', and so the event should be declared 'Shadows'.
Event E2 As System.Action
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(1068209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068209")>
Public Sub Bug1068209_02()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class I1
ReadOnly Property P1 As Integer
Get
return Nothing
End Get
End Property
Sub get_P2()
End Sub
Event E1 As System.Action
Sub remove_E2()
End Sub
End Class
Class I3
Inherits I1
Overloads Sub get_P1()
End Sub
Overloads ReadOnly Property P2 As Integer
Get
return Nothing
End Get
End Property
Overloads Sub add_E1()
End Sub
Event E2 As System.Action
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40014: sub 'get_P1' conflicts with a member implicitly declared for property 'P1' in the base class 'I1' and should be declared 'Shadows'.
Overloads Sub get_P1()
~~~~~~
BC40012: property 'P2' implicitly declares 'get_P2', which conflicts with a member in the base class 'I1', and so the property should be declared 'Shadows'.
Overloads ReadOnly Property P2 As Integer
~~
BC40014: sub 'add_E1' conflicts with a member implicitly declared for event 'E1' in the base class 'I1' and should be declared 'Shadows'.
Overloads Sub add_E1()
~~~~~~
BC40012: event 'E2' implicitly declares 'remove_E2', which conflicts with a member in the base class 'I1', and so the event should be declared 'Shadows'.
Event E2 As System.Action
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub NoObsoleteDiagnosticsForProjectLevelImports_01()
Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"GlobEnumsClass"}))
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
<System.Serializable><System.Obsolete()>
Class GlobEnumsClass
Public Enum xEmailMsg
Option1
Option2
End Enum
End Class
Class Account
Property Status() As xEmailMsg
End Class
]]></file>
</compilation>, options:=options)
CompileAndVerify(compilation).VerifyDiagnostics()
End Sub
<Fact>
Public Sub NoObsoleteDiagnosticsForProjectLevelImports_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports GlobEnumsClass
<System.Serializable><System.Obsolete()>
Class GlobEnumsClass
Public Enum xEmailMsg
Option1
Option2
End Enum
End Class
Class Account
Property Status() As xEmailMsg
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll)
compilation.AssertTheseDiagnostics(<expected>
BC40008: 'GlobEnumsClass' is obsolete.
Imports GlobEnumsClass
~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MustOverrideInScript()
Dim source = <![CDATA[
Friend MustOverride Function F() As Object
Friend MustOverride ReadOnly Property P
]]>
Dim comp = CreateCompilationWithMscorlib45(
{VisualBasicSyntaxTree.ParseText(source.Value, TestOptions.Script)},
references:={SystemCoreRef})
comp.AssertTheseDiagnostics(<expected>
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride Function F() As Object
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride ReadOnly Property P
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MustOverrideInInteractive()
Dim source = <![CDATA[
Friend MustOverride Function F() As Object
Friend MustOverride ReadOnly Property P
]]>
Dim submission = VisualBasicCompilation.CreateScriptCompilation(
"s0.dll",
syntaxTree:=Parse(source.Value, TestOptions.Script),
references:={MscorlibRef, SystemCoreRef})
submission.AssertTheseDiagnostics(<expected>
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride Function F() As Object
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride ReadOnly Property P
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsOfATypeToDifferentAssembliesWithoutUsingItShouldNotReportAnError()
Dim forwardingIL = "
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly Forwarding
{
}
.module Forwarding.dll
.assembly extern Destination1
{
}
.assembly extern Destination2
{
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}
.class public auto ansi beforefieldinit TestSpace.ExistingReference
extends [mscorlib]System.Object
{
.field public static literal string Value = ""TEST VALUE""
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void[mscorlib] System.Object::.ctor()
IL_0006: nop
IL_0007: ret
}
}"
Dim ilReference = CompileIL(forwardingIL, prependDefaultHeader:=False)
Dim code =
<compilation>
<file name="a.vb"><![CDATA[
Imports TestSpace
Namespace UserSpace
Public Class Program
Public Shared Sub Main()
System.Console.WriteLine(ExistingReference.Value)
End Sub
End Class
End Namespace
]]></file>
</compilation>
CompileAndVerify(
source:=code,
references:={ilReference},
expectedOutput:="TEST VALUE")
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsOfFullyQualifiedTypeToDifferentAssembliesWhileReferencingItShouldErrorOut()
Dim userCode =
<compilation>
<file name="a.vb"><![CDATA[
Namespace ForwardingNamespace
Public Class Program
Public Shared Sub Main()
Dim obj = New Destination.TestClass()
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim forwardingIL = "
.assembly extern Destination1
{
.ver 1:0:0:0
}
.assembly extern Destination2
{
.ver 1:0:0:0
}
.assembly Forwarder
{
.ver 1:0:0:0
}
.module ForwarderModule.dll
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}"
Dim compilation = CreateCompilationWithCustomILSource(userCode, forwardingIL, appendDefaultHeader:=False)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30002: Type 'Destination.TestClass' is not defined.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsToManyAssembliesShouldJustReportTheFirstTwo()
Dim userCode =
<compilation>
<file name="a.vb"><![CDATA[
Namespace ForwardingNamespace
Public Class Program
Public Shared Sub Main()
Dim obj = New Destination.TestClass()
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim forwardingIL = "
.assembly Forwarder
{
}
.module ForwarderModule.dll
.assembly extern Destination1 { }
.assembly extern Destination2 { }
.assembly extern Destination3 { }
.assembly extern Destination4 { }
.assembly extern Destination5 { }
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination3
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination4
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination5
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}"
Dim compilation = CreateCompilationWithCustomILSource(userCode, forwardingIL, appendDefaultHeader:=False)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30002: Type 'Destination.TestClass' is not defined.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub RequiredExternalTypesForAMethodSignatureWillReportErrorsIfForwardedToMultipleAssemblies()
' The scenario Is that assembly A Is calling a method from assembly B. This method has a parameter of a type that lives
' in assembly C. If A Is compiled against B And C, it should compile successfully.
' Now if assembly C Is replaced with assembly C2, that forwards the type to both D1 And D2, it should fail with the appropriate error.
Dim codeC = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim referenceC = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="C").EmitToImageReference()
Dim codeB = "
Imports C
Namespace B
Public Class ClassB
Public Shared Sub MethodB(obj As ClassC)
System.Console.WriteLine(obj.GetHashCode())
End Sub
End Class
End Namespace"
Dim compilationB = CreateCompilationWithMscorlib40(
source:=codeB,
references:={referenceC},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="B")
Dim referenceB = compilationB.EmitToImageReference()
Dim codeA = "
Imports B
Namespace A
Public Class ClassA
Public Sub MethodA()
ClassB.MethodB(Nothing)
End Sub
End Class
End Namespace"
Dim compilation = CreateCompilationWithMscorlib40(
source:=codeA,
references:={referenceB, referenceC},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="A")
compilation.VerifyDiagnostics() ' No Errors
Dim codeC2 = "
.assembly C { }
.module CModule.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder C.ClassC
{
.assembly extern D1
}
.class extern forwarder C.ClassC
{
.assembly extern D2
}"
Dim referenceC2 = CompileIL(codeC2, prependDefaultHeader:=False)
compilation = CreateCompilationWithMscorlib40(
source:=codeA,
references:={referenceB, referenceC2},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="A")
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC37208: Module 'CModule.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
ClassB.MethodB(Nothing)
~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleTypeForwardersToTheSameAssemblyShouldNotResultInMultipleForwardError()
Dim codeC = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim compilationC = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="C")
Dim referenceC = compilationC.EmitToImageReference()
Dim codeB = "
Imports C
Namespace B
Public Class ClassB
Public Shared Function MethodB(obj As ClassC) As String
Return ""obj is "" + If(obj Is Nothing, ""nothing"", obj.ToString())
End Function
End Class
End Namespace"
Dim compilationB = CreateCompilationWithMscorlib40(
source:=codeB,
references:={referenceC},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="B")
Dim referenceB = compilationB.EmitToImageReference()
Dim codeA =
<compilation>
<file name="a.vb"><![CDATA[
Imports B
Namespace A
Public Class ClassA
Public Shared Sub Main()
System.Console.WriteLine(ClassB.MethodB(Nothing))
End Sub
End Class
End Namespace
]]></file>
</compilation>
CompileAndVerify(
source:=codeA,
references:={referenceB, referenceC},
expectedOutput:="obj is nothing")
Dim codeC2 = "
.assembly C
{
.ver 0:0:0:0
}
.module C.dll
.assembly extern D { }
.class extern forwarder C.ClassC
{
.assembly extern D
}
.class extern forwarder C.ClassC
{
.assembly extern D
}"
Dim referenceC2 = CompileIL(codeC2, prependDefaultHeader:=False)
Dim compilation = CreateCompilationWithMscorlib40(codeA, references:={referenceB, referenceC2})
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30652: Reference required to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'ClassC'. Add one to your project.
System.Console.WriteLine(ClassB.MethodB(Nothing))
~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
Dim codeD = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim referenceD = CreateCompilationWithMscorlib40(
source:=codeD,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="D").EmitToImageReference()
CompileAndVerify(
source:=codeA,
references:={referenceB, referenceC2, referenceD},
expectedOutput:="obj is nothing")
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub CompilingModuleWithMultipleForwardersToDifferentAssembliesShouldErrorOut()
Dim ilSource = "
.module ForwarderModule.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D1
}
.class extern forwarder Testspace.TestType
{
.assembly extern D2
}"
Dim ilModule = GetILModuleReference(ilSource, prependDefaultHeader:=False)
Dim compilation = CreateCompilationWithMscorlib40(
source:=String.Empty,
references:={ilModule},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="Forwarder")
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub CompilingModuleWithMultipleForwardersToTheSameAssemblyShouldNotProduceMultipleForwardingErrors()
Dim ilSource = "
.assembly extern D { }
.class extern forwarder Testspace.TestType
{
.assembly extern D
}
.class extern forwarder Testspace.TestType
{
.assembly extern D
}"
Dim ilModule = GetILModuleReference(ilSource, prependDefaultHeader:=False)
Dim compilation = CreateCompilationWithMscorlib40(String.Empty, references:={ilModule}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30652: Reference required to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'TestType'. Add one to your project.
]]></errors>)
Dim dCode = "
Namespace Testspace
Public Class TestType
End Class
End Namespace"
Dim dReference = CreateCompilationWithMscorlib40(
source:=dCode,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="D").EmitToImageReference()
' Now compilation succeeds
CreateCompilationWithMscorlib40(
source:=String.Empty,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references:={ilModule, dReference}).VerifyDiagnostics()
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub LookingUpATypeForwardedTwiceInASourceCompilationReferenceShouldFail()
' This test specifically tests that SourceAssembly symbols also produce this error (by using a CompilationReference instead of the usual PEAssembly symbol)
Dim ilSource = "
.module ForwarderModule.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D1
}
.class extern forwarder Testspace.TestType
{
.assembly extern D2
}"
Dim ilModuleReference = GetILModuleReference(ilSource, prependDefaultHeader:=False)
Dim forwarderCompilation = CreateEmptyCompilation(
source:=String.Empty,
references:={ilModuleReference},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="Forwarder")
Dim vbSource = "
Namespace UserSpace
Public Class UserClass
Public Shared Sub Main()
Dim obj = new Testspace.TestType()
End Sub
End Class
End Namespace"
Dim userCompilation = CreateCompilationWithMscorlib40(
source:=vbSource,
references:={forwarderCompilation.ToMetadataReference()},
assemblyName:="UserAssembly")
CompilationUtils.AssertTheseDiagnostics(userCompilation, <errors><![CDATA[
BC30002: Type 'Testspace.TestType' is not defined.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub ForwardingErrorsInLaterModulesAlwaysOverwriteOnesInEarlierModules()
Dim module1IL = "
.module module1IL.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D1
}
.class extern forwarder Testspace.TestType
{
.assembly extern D2
}"
Dim module1Reference = GetILModuleReference(module1IL, prependDefaultHeader:=False)
Dim module2IL = "
.module module12L.dll
.assembly extern D3 { }
.assembly extern D4 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D3
}
.class extern forwarder Testspace.TestType
{
.assembly extern D4
}"
Dim module2Reference = GetILModuleReference(module2IL, prependDefaultHeader:=False)
Dim forwarderCompilation = CreateEmptyCompilation(
source:=String.Empty,
references:={module1Reference, module2Reference},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="Forwarder")
Dim vbSource = "
Namespace UserSpace
Public Class UserClass
Public Shared Sub Main()
Dim obj = new Testspace.TestType()
End Sub
End Class
End Namespace"
Dim userCompilation = CreateCompilationWithMscorlib40(
source:=vbSource,
references:={forwarderCompilation.ToMetadataReference()},
assemblyName:="UserAssembly")
CompilationUtils.AssertTheseDiagnostics(userCompilation, <errors><![CDATA[
BC30002: Type 'Testspace.TestType' is not defined.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
BC37208: Module 'module12L.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsThatChainResultInTheSameAssemblyShouldStillProduceAnError()
' The scenario Is that assembly A Is calling a method from assembly B. This method has a parameter of a type that lives
' in assembly C. Now if assembly C Is replaced with assembly C2, that forwards the type to both D And E, And D fowards it to E,
' it should fail with the appropriate error.
Dim codeC = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim referenceC = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="C").EmitToImageReference()
Dim codeB = "
Imports C
Namespace B
Public Class ClassB
Public Shared Sub MethodB(obj As ClassC)
System.Console.WriteLine(obj.GetHashCode())
End Sub
End Class
End Namespace"
Dim referenceB = CreateCompilationWithMscorlib40(
source:=codeB,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references:={referenceC},
assemblyName:="B").EmitToImageReference()
Dim codeC2 = "
.assembly C { }
.module C.dll
.assembly extern D { }
.assembly extern E { }
.class extern forwarder C.ClassC
{
.assembly extern D
}
.class extern forwarder C.ClassC
{
.assembly extern E
}"
Dim referenceC2 = CompileIL(codeC2, prependDefaultHeader:=False)
Dim codeD = "
.assembly D { }
.assembly extern E { }
.class extern forwarder C.ClassC
{
.assembly extern E
}"
Dim referenceD = CompileIL(codeD, prependDefaultHeader:=False)
Dim referenceE = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="E").EmitToImageReference()
Dim codeA = "
Imports B
Imports C
Namespace A
Public Class ClassA
Public Sub MethodA(obj As ClassC)
ClassB.MethodB(obj)
End Sub
End Class
End Namespace"
Dim userCompilation = CreateCompilationWithMscorlib40(
source:=codeA,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references:={referenceB, referenceC2, referenceD, referenceE},
assemblyName:="A")
CompilationUtils.AssertTheseDiagnostics(userCompilation, <errors><![CDATA[
BC37208: Module 'C.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
ClassB.MethodB(obj)
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(52516, "https://github.com/dotnet/roslyn/issues/52516")>
Public Sub ErrorInfo_01()
Dim [error] = New MissingMetadataTypeSymbol.Nested(New UnsupportedMetadataTypeSymbol(), "Test", 0, False)
Dim info = [error].ErrorInfo
Assert.Equal(ERRID.ERR_UnsupportedType1, CType(info.Code, ERRID))
Assert.Null([error].ContainingModule)
Assert.Null([error].ContainingAssembly)
Assert.NotNull([error].ContainingSymbol)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Xml.Linq
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Roslyn.Test.Utilities.TestMetadata
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' this place is dedicated to various parser and/or symbol errors
Public Class SymbolErrorTests
Inherits BasicTestBase
#Region "Targeted Error Tests"
<Fact>
Public Sub BC30002ERR_UndefinedType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedType1">
<file name="a.vb"><![CDATA[
Structure myStruct
Sub Scen1(FixedRankArray_7(,) As unknowntype)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'unknowntype' is not defined.
Sub Scen1(FixedRankArray_7(,) As unknowntype)
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30002ERR_UndefinedType1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedType1">
<file name="a.vb"><![CDATA[
Namespace NS1
Structure myStruct
Sub Scen1()
End Sub
End Structure
End Namespace
Namespace NS2
Structure myStruct1
Sub Scen1(ByVal S As myStruct)
End Sub
End Structure
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'myStruct' is not defined.
Sub Scen1(ByVal S As myStruct)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30015ERR_InheritsFromRestrictedType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsFromRestrictedType1">
<file name="a.vb"><![CDATA[
Structure myStruct1
Class C1
'COMPILEERROR: BC30015, "System.Enum"
Inherits System.Enum
End Class
Class C2
'COMPILEERROR: BC30015, "System.MulticastDelegate"
Inherits System.MulticastDelegate
End Class
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30015: Inheriting from '[Enum]' is not valid.
Inherits System.Enum
~~~~~~~~~~~
BC30015: Inheriting from 'MulticastDelegate' is not valid.
Inherits System.MulticastDelegate
~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30022ERR_ReadOnlyHasSet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ReadOnlyHasSet">
<file name="a.vb"><![CDATA[
Class C1
Private newPropertyValue As String
Public ReadOnly Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30022: Properties declared 'ReadOnly' cannot have a 'Set'.
Set(ByVal value As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30022ERR_ReadOnlyHasSet2()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="ReadOnlyHasSet2">
<file name="a.vb"><![CDATA[
Class C1
Inherits D2
Public Overrides ReadOnly Property P_rw_rw_r As Integer
Get
Return MyBase.P_rw_rw_r
End Get
Set(value As Integer)
MyBase.P_rw_rw_r = value
End Set
End Property
End Class
]]></file>
</compilation>, ClassesWithReadWriteProperties)
Dim expectedErrors1 = <errors><![CDATA[
BC30022: Properties declared 'ReadOnly' cannot have a 'Set'.
Set(value As Integer)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30023ERR_WriteOnlyHasGet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="WriteOnlyHasGet">
<file name="a.vb"><![CDATA[
Class C1
Private newPropertyValue As String
Public WriteOnly Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30023: Properties declared 'WriteOnly' cannot have a 'Get'.
Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30023ERR_WriteOnlyHasGet2()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="WriteOnlyHasGet2">
<file name="a.vb"><![CDATA[
Class C1
Inherits D2
Public Overrides WriteOnly Property P_rw_rw_w As Integer
Get
Return MyBase.P_rw_rw_w
End Get
Set(value As Integer)
MyBase.P_rw_rw_w = value
End Set
End Property
End Class
]]></file>
</compilation>, ClassesWithReadWriteProperties)
Dim expectedErrors1 = <errors><![CDATA[
BC30023: Properties declared 'WriteOnly' cannot have a 'Get'.
Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30031ERR_FullyQualifiedNameTooLong1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
Namespace EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE.FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
Namespace HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH.IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
Namespace n
Delegate Sub s()
End Namespace
Namespace KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
Namespace NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
Namespace QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ.RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR.SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
Namespace TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU.VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVv
Class CCCCC(Of T)
Sub s1()
End Sub
Dim x As Integer
Class nestedCCCC
End Class
End Class
Structure ssssss
End Structure
Module mmmmmm
End Module
Enum eee
dummy
End Enum
Interface iii
End Interface
Delegate Sub s()
Delegate Function f() As Integer
End Namespace
End Namespace
End Namespace
End Namespace
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>)
Dim namespaceName As String = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB.CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC.DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD.EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE.FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF.GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG.HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH.IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII.JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ.KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP.QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ.RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR.SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS.TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT.UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU.VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVv"
Dim expectedErrors = <errors>
BC37220: Name '<%= namespaceName %>.CCCCC`1' exceeds the maximum length allowed in metadata.
Class CCCCC(Of T)
~~~~~
BC37220: Name '<%= namespaceName %>.ssssss' exceeds the maximum length allowed in metadata.
Structure ssssss
~~~~~~
BC37220: Name '<%= namespaceName %>.mmmmmm' exceeds the maximum length allowed in metadata.
Module mmmmmm
~~~~~~
BC37220: Name '<%= namespaceName %>.eee' exceeds the maximum length allowed in metadata.
Enum eee
~~~
BC37220: Name '<%= namespaceName %>.iii' exceeds the maximum length allowed in metadata.
Interface iii
~~~
BC37220: Name '<%= namespaceName %>.s' exceeds the maximum length allowed in metadata.
Delegate Sub s()
~
BC37220: Name '<%= namespaceName %>.f' exceeds the maximum length allowed in metadata.
Delegate Function f() As Integer
~
</errors>
CompilationUtils.AssertNoDeclarationDiagnostics(compilation)
CompilationUtils.AssertTheseEmitDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30050ERR_ParamArrayNotArray()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ERR_ParamArrayNotArray">
<file name="a.vb"><![CDATA[
Option Explicit
Structure myStruct1
Public sub m1(ParamArray byval q)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30050: ParamArray parameter must be an array.
Public sub m1(ParamArray byval q)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30051ERR_ParamArrayRank()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamArrayRank">
<file name="a.vb"><![CDATA[
Class zzz
Shared Sub Main()
End Sub
Sub abc(ByVal ParamArray s(,) As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30051: ParamArray parameter must be a one-dimensional array.
Sub abc(ByVal ParamArray s(,) As Integer)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30121ERR_MultipleExtends()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleExtends">
<file name="a.vb"><![CDATA[
Class C1(of T)
Inherits Object
Inherits system.StringComparer
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits system.StringComparer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30124ERR_PropMustHaveGetSet_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
'COMPILEERROR: BC30124, "aprop"
Property aprop() As String
Get
Return "30124"
End Get
End Property
End Class
Partial Class C1
'COMPILEERROR: BC30124, "aprop"
Property aprop() As String
Set(ByVal Value As String)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Property aprop() As String
~~~~~
BC30269: 'Public Property aprop As String' has multiple definitions with identical signatures.
Property aprop() As String
~~~~~
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Property aprop() As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30124ERR_PropMustHaveGetSet_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Property P
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30125ERR_WriteOnlyHasNoWrite_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
'COMPILEERROR: BC30125, "aprop"
WriteOnly Property aprop() As String
End Property
End Class
Partial Class C1
Property aprop() As String
Set(ByVal Value As String)
End Set
Get
Return "30125"
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30125: 'WriteOnly' property must provide a 'Set'.
WriteOnly Property aprop() As String
~~~~~
BC30366: 'Public WriteOnly Property aprop As String' and 'Public Property aprop As String' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
WriteOnly Property aprop() As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30126ERR_ReadOnlyHasNoGet_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
'COMPILEERROR: BC30126, "aprop"
ReadOnly Property aprop() As String
End Property
End Class
Partial Class C1
Property aprop() As String
Set(ByVal Value As String)
End Set
Get
Return "30126"
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30126: 'ReadOnly' property must provide a 'Get'.
ReadOnly Property aprop() As String
~~~~~
BC30366: 'Public ReadOnly Property aprop As String' and 'Public Property aprop As String' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
ReadOnly Property aprop() As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30149ERR_UnimplementedMember3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedMember3">
<file name="a.vb"><![CDATA[
Interface Ibase
Function one() As String
End Interface
Interface Iderived
Inherits Ibase
Function two() As String
End Interface
Class C1
Implements Iderived
End Class
Partial Class C1
Public Function two() As String Implements Iderived.two
Return "two"
End Function
End Class
Class C2
Implements Iderived
End Class
Partial Class C2
Public Function one() As String Implements Iderived.one
Return "one"
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'C1' must implement 'Function one() As String' for interface 'Ibase'.
Implements Iderived
~~~~~~~~
BC30149: Class 'C2' must implement 'Function two() As String' for interface 'Iderived'.
Implements Iderived
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Spec changed in Roslyn
<WorkItem(528701, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528701")>
<Fact>
Public Sub BC30154ERR_UnimplementedProperty3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnimplementedProperty3">
<file name="a.vb"><![CDATA[
Interface PropInterface
Property Scen1() As System.Collections.Generic.IEnumerable(Of Integer)
End Interface
Class HasProps
'COMPILEERROR:BC30154,"PropInterface"
Implements PropInterface
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'HasProps' must implement 'Property Scen1 As IEnumerable(Of Integer)' for interface 'PropInterface'.
Implements PropInterface
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30177ERR_DuplicateModifierCategoryUsed()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateModifierCategoryUsed">
<file name="a.vb"><![CDATA[
MustInherit Class C1
MustOverride notoverridable Overridable Function StringFunc() As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
MustOverride notoverridable Overridable Function StringFunc() As String
~~~~~~~~~~~~~~
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
MustOverride notoverridable Overridable Function StringFunc() As String
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30177ERR_DuplicateModifierCategoryUsed_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateModifierCategoryUsed">
<file name="a.vb"><![CDATA[
MustInherit Class C1
MustOverride Overridable Function StringFunc() As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
MustOverride Overridable Function StringFunc() As String
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30178ERR_DuplicateSpecifier()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateSpecifier">
<file name="a.vb"><![CDATA[
Class test
Shared Shared Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30178: Specifier is duplicated.
Shared Shared Sub Goo()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30178ERR_DuplicateSpecifier_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateSpecifier">
<file name="a.vb"><![CDATA[
class test
friend shared friend function Goo()
End function
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30178: Specifier is duplicated.
friend shared friend function Goo()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for duplicate type declarations
<Fact>
Public Sub BC30179ERR_TypeConflict6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class cc1
End Class
Class cC1
End Class
Class Cc1
End Class
structure CC1
end structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: class 'cc1' and structure 'CC1' conflict in namespace '<Default>'.
Class cc1
~~~
BC30179: class 'cC1' and structure 'CC1' conflict in namespace '<Default>'.
Class cC1
~~~
BC30179: class 'Cc1' and structure 'CC1' conflict in namespace '<Default>'.
Class Cc1
~~~
BC30179: structure 'CC1' and class 'cc1' conflict in namespace '<Default>'.
structure CC1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30179ERR_TypeConflict6_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Enum Unicode
one
End Enum
Class Unicode
End Class
Module Unicode
End Module
Interface Unicode
End Interface
Delegate Sub Unicode()
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: enum 'Unicode' and class 'Unicode' conflict in namespace '<Default>'.
Enum Unicode
~~~~~~~
BC30179: class 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Class Unicode
~~~~~~~
BC30179: module 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Module Unicode
~~~~~~~
BC30179: interface 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Interface Unicode
~~~~~~~
BC30179: delegate Class 'Unicode' and enum 'Unicode' conflict in namespace '<Default>'.
Delegate Sub Unicode()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")>
<Fact>
Public Sub BC30179ERR_TypeConflict6_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Interface I
ReadOnly Property P
ReadOnly Property Q
End Interface
Interface I ' BC30179
Property Q
End Interface
Structure S
Class T
End Class
Interface I
End Interface
End Structure
Structure S ' BC30179
Structure T
End Structure
Dim I
End Structure
Enum E
A
B
End Enum
Enum E ' BC30179
A
End Enum
Class S ' BC30179
Dim T
End Class
Delegate Sub D()
Delegate Function D(s$) ' BC30179
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: interface 'I' and interface 'I' conflict in namespace 'N'.
Interface I ' BC30179
~
BC30179: structure 'S' and class 'S' conflict in namespace 'N'.
Structure S
~
BC30179: structure 'S' and class 'S' conflict in namespace 'N'.
Structure S ' BC30179
~
BC30179: enum 'E' and enum 'E' conflict in namespace 'N'.
Enum E
~
BC30179: enum 'E' and enum 'E' conflict in namespace 'N'.
Enum E ' BC30179
~
BC30179: class 'S' and structure 'S' conflict in namespace 'N'.
Class S ' BC30179
~
BC30179: delegate Class 'D' and delegate Class 'D' conflict in namespace 'N'.
Delegate Function D(s$) ' BC30179
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")>
<Fact>
Public Sub BC30179ERR_TypeConflict6_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Interface I
ReadOnly Property P
ReadOnly Property Q
End Interface
Interface I ' BC30179
Property Q
End Interface
Structure S
Class T
End Class
Interface I
End Interface
End Structure
Structure S ' BC30179
Structure T
End Structure
Dim I
End Structure
Enum E
A
B
End Enum
Enum E ' BC30179
A
End Enum
Class S ' BC30179
Dim T
End Class
Delegate Sub D()
Delegate Function D(s$) ' BC30179
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: interface 'I' and interface 'I' conflict in class 'C'.
Interface I ' BC30179
~
BC30179: structure 'S' and class 'S' conflict in class 'C'.
Structure S
~
BC30179: structure 'S' and class 'S' conflict in class 'C'.
Structure S ' BC30179
~
BC30179: enum 'E' and enum 'E' conflict in class 'C'.
Enum E
~
BC30179: enum 'E' and enum 'E' conflict in class 'C'.
Enum E ' BC30179
~
BC30179: class 'S' and structure 'S' conflict in class 'C'.
Class S ' BC30179
~
BC30179: delegate Class 'D' and delegate Class 'D' conflict in class 'C'.
Delegate Function D(s$) ' BC30179
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30179ERR_TypeConflict6_DupNestedEnumDeclarations()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateEnum1">
<file name="a.vb"><![CDATA[
Structure S1
Enum goo
bar
End Enum
Enum goo
bar
another_bar
End Enum
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: enum 'goo' and enum 'goo' conflict in structure 'S1'.
Enum goo
~~~
BC30179: enum 'goo' and enum 'goo' conflict in structure 'S1'.
Enum goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30179ERR_TypeConflict6_DupEnumDeclarations()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateEnum2">
<file name="a.vb"><![CDATA[
Enum goo
bar
End Enum
Enum goo
bar
another_bar
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30179: enum 'goo' and enum 'goo' conflict in namespace '<Default>'.
Enum goo
~~~
BC30179: enum 'goo' and enum 'goo' conflict in namespace '<Default>'.
Enum goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30182_ERR_UnrecognizedType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnrecognizedType">
<file name="a.vb"><![CDATA[
Namespace NS
Class C1
Function GOO() As NS
End Function
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30182: Type expected.
Function GOO() As NS
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30182_ERR_UnrecognizedType_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnrecognizedType">
<file name="a.vb"><![CDATA[
Namespace NS
Class C1
inherits NS
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30182: Type expected.
inherits NS
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Structure S1
Public Function Goo()
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Function Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_1()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
option strict on
Public Class c1
Shared Operator + (ByVal c As c1, ByVal b As c1)
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_StrictDisallowsImplicitProc, "+"),
Diagnostic(ERRID.WRN_DefAsgNoRetValOpRef1, "End Operator").WithArguments("+"))
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Interface I
ReadOnly Property P
End Interface
Structure S
WriteOnly Property P
Set(value As Object)
End Set
End Property
End Structure
Class C
Property P(i As Integer)
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
ReadOnly Property P
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
WriteOnly Property P
~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Property P(i As Integer)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Delegate Sub D()
Delegate Function E(o As Object)
Delegate Function F() As Object
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Delegate Function E(o As Object)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_Declare()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Module M
Declare Sub test Lib "???" (a As Integer)
Declare Sub F Lib "bar" ()
Declare Function G Lib "bar" ()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Declare Function G Lib "bar" ()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30211ERR_StrictDisallowsImplicitArgs()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Structure S1
Public Function Goo(byval x) as integer
return 1
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Public Function Goo(byval x) as integer
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30211ERR_StrictDisallowsImplicitArgs_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Interface I
ReadOnly Property P(i) As Object
End Interface
Structure S
WriteOnly Property P(x) As Object
Set(value)
End Set
End Property
End Structure
Class C
Property P(val) As I
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
ReadOnly Property P(i) As Object
~
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
WriteOnly Property P(x) As Object
~
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Set(value)
~~~~~
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Property P(val) As I
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30230ERR_ModuleCantInherit()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantInherit">
<file name="a.vb"><![CDATA[
interface I1
End interface
module M1
Inherits I1
End module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30230: 'Inherits' not valid in Modules.
Inherits I1
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30231ERR_ModuleCantImplement()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantImplement">
<file name="a.vb"><![CDATA[
Module M1
Implements Object
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30231: 'Implements' not valid in Modules.
Implements Object
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30232ERR_BadImplementsType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadImplementsType">
<file name="a.vb"><![CDATA[
Class cls1
Implements system.Enum
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30232: Implemented type must be an interface.
Implements system.Enum
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30233ERR_BadConstFlags1()
Dim source =
<compilation name="delegates">
<file name="a.vb"><![CDATA[
Option strict on
imports system
Class C1
' BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
Public Const Shared c As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
Public Const ReadOnly e As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Shared ReadOnly Const f As String = "goo"
End Class
Module M1
' Roslyn: Only BC30593: Variables in Modules cannot be declared 'Shared'.
' Dev10: Additional BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
Public Const Shared c As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
Public Const ReadOnly e As String = "goo"
End Module
Structure S1
' BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
Public Const Shared c As String = "goo"
' BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
Public Const ReadOnly e As String = "goo"
End Structure
]]></file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected><![CDATA[
BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Const Shared c As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
~~~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Const ReadOnly e As String = "goo"
~~~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Shared ReadOnly Const f As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Shared ReadOnly Const f As String = "goo"
~~~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Public Shared Const b As String = "goo"
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Public Const Shared c As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
~~~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Const ReadOnly e As String = "goo"
~~~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Shared Const b As String = "goo"
~~~~~~
BC30233: 'Shared' is not valid on a constant declaration.
Public Const Shared c As String = "goo"
~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public ReadOnly Const d As String = "goo"
~~~~~~~~
BC30233: 'ReadOnly' is not valid on a constant declaration.
Public Const ReadOnly e As String = "goo"
~~~~~~~~
]]></expected>)
End Sub
<WorkItem(528365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528365")>
<Fact>
Public Sub BC30233ERR_BadConstFlags1_02()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadConstFlags1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
Module M1
'COMPILEERROR: BC30233, "Static"
Static Const p As Integer = AscW("10")
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30235: 'Static' is not valid on a member variable declaration.
Static Const p As Integer = AscW("10")
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30234ERR_BadWithEventsFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadWithEventsFlags1">
<file name="a.vb"><![CDATA[
Module M1
'COMPILEERROR: BC30234, "ReadOnly"
ReadOnly WithEvents var1 As Object
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30234: 'ReadOnly' is not valid on a WithEvents declaration.
ReadOnly WithEvents var1 As Object
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30235ERR_BadDimFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadDimFlags1">
<file name="a.vb"><![CDATA[
Class cls1
Default i As Integer
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30235: 'Default' is not valid on a member variable declaration.
Default i As Integer
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30237ERR_DuplicateParamName1_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option strict on
Module m
Sub s1(ByVal a As Integer, ByVal a As Integer, a as string)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30237: Parameter already declared with name 'a'.
Sub s1(ByVal a As Integer, ByVal a As Integer, a as string)
~
BC30237: Parameter already declared with name 'a'.
Sub s1(ByVal a As Integer, ByVal a As Integer, a as string)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30237ERR_DuplicateParamName1_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P(ByVal a, ByVal b)
Set(ByVal b)
End Set
End Property
Property Q(x, y, x)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30237: Parameter already declared with name 'b'.
Set(ByVal b)
~
BC30237: Parameter already declared with name 'x'.
Property Q(x, y, x)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30237ERR_DuplicateParamName1_ExternalMethods()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
<MethodImplAttribute(MethodCodeType:=MethodCodeType.Runtime)>
Shared Sub Runtime(a As Integer, a As Integer)
End Sub
<MethodImpl(MethodImplOptions.InternalCall)>
Shared Sub InternalCall(b As Integer, b As Integer)
End Sub
<DllImport("goo")>
Shared Sub DllImp(c As Integer, c As Integer)
End Sub
Declare Sub DeclareSub Lib "bar" (d As Integer, d As Integer)
End Class
]]></file>
</compilation>
CreateCompilationWithMscorlib40(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_DuplicateParamName1, "a").WithArguments("a"),
Diagnostic(ERRID.ERR_DuplicateParamName1, "b").WithArguments("b"),
Diagnostic(ERRID.ERR_DuplicateParamName1, "c").WithArguments("c"))
End Sub
<Fact>
Public Sub BC30242ERR_BadMethodFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadMethodFlags1">
<file name="a.vb"><![CDATA[
Structure S1
Default function goo()
End function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30242: 'Default' is not valid on a method declaration.
Default function goo()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30243ERR_BadEventFlags1()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadEventFlags1">
<file name="a.vb"><![CDATA[
Class c1
Shared Event e1()
Public Event e2()
Sub raiser1()
RaiseEvent e1()
End Sub
Sub raiser2()
RaiseEvent e2()
End Sub
End Class
Class c2
Inherits c1
'COMPILEERROR: BC30243, "Overrides"
Overrides Event e1()
'COMPILEERROR: BC30243, "Overloads"
Overloads Event e2(ByVal i As Integer)
'COMPILEERROR: BC30243, "Overloads", BC30243, "Overrides"
Overloads Overrides Event e3(ByVal i As Integer)
'COMPILEERROR: BC30243, "NotOverridable"
NotOverridable Event e4()
'COMPILEERROR: BC30243, "Default"
Default Event e5()
'COMPILEERROR: BC30243, "Static"
Static Event e6()
End Class
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_BadEventFlags1, "Overrides").WithArguments("Overrides"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Overloads").WithArguments("Overloads"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Overloads").WithArguments("Overloads"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Overrides").WithArguments("Overrides"),
Diagnostic(ERRID.ERR_BadEventFlags1, "NotOverridable").WithArguments("NotOverridable"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Default").WithArguments("Default"),
Diagnostic(ERRID.ERR_BadEventFlags1, "Static").WithArguments("Static"),
Diagnostic(ERRID.WRN_OverrideType5, "e1").WithArguments("event", "e1", "event", "class", "c1"),
Diagnostic(ERRID.WRN_OverrideType5, "e2").WithArguments("event", "e2", "event", "class", "c1"))
End Sub
' BC30244ERR_BadDeclareFlags1
' see AttributeTests
<WorkItem(527697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527697")>
<Fact>
Public Sub BC30246ERR_BadLocalConstFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadLocalConstFlags1">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
'COMPILEERROR: BC30246, "Shared"
Shared Const x As Integer = 10
End Sub
End Module
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"),
Diagnostic(ERRID.WRN_UnusedLocalConst, "x").WithArguments("x"))
End Sub
<WorkItem(538967, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538967")>
<Fact>
Public Sub BC30247ERR_BadLocalDimFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadLocalDimFlags1">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
'COMPILEERROR: BC30247, "Shared"
Shared x As Integer = 10
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30247: 'Shared' is not valid on a local variable declaration.
Shared x As Integer = 10
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30257ERR_InheritanceCycle1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InheritanceCycle1">
<file name="a.vb"><![CDATA[
Public Class C1
Inherits C2
End Class
Public Class C2
Inherits C1
End Class
Module M1
Sub Main()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30257: Class 'C1' cannot inherit from itself:
'C1' inherits from 'C2'.
'C2' inherits from 'C1'.
Inherits C2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30258ERR_InheritsFromNonClass()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsFrom2">
<file name="a.vb"><![CDATA[
Structure myStruct1
Class C1
Inherits myStruct1
End Class
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30258: Classes can inherit only from other classes.
Inherits myStruct1
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for duplicate type declarations
' DEV code
<Fact>
Public Sub BC30260ERR_MultiplyDefinedType3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
class c
sub i(ByVal i As Integer)
End Sub
dim i(,,) as integer
Public i, i As Integer
Private i As Integer
Sub i()
End Sub
end class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
dim i(,,) as integer
~
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
Public i, i As Integer
~
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
Public i, i As Integer
~
BC30260: 'i' is already declared as 'Public Sub i(i As Integer)' in this class.
Private i As Integer
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30260ERR_MultiplyDefinedType3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Enum E As Short
A
End Enum
Function E()
End Function
End Class
Interface I
Structure S
End Structure
Sub S()
End Interface
Structure S
Class C
End Class
Property C
Interface I
End Interface
Private I
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30260: 'E' is already declared as 'Enum E' in this class.
Function E()
~
BC30260: 'S' is already declared as 'Structure S' in this interface.
Sub S()
~
BC30260: 'C' is already declared as 'Class C' in this structure.
Property C
~
BC30260: 'I' is already declared as 'Interface I' in this structure.
Private I
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30260ERR_MultiplyDefinedType3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class C
Overloads Property P
Overloads Function P(o)
Return Nothing
End Function
Overloads Shared Property Q(o)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Overloads Sub Q()
End Sub
Class R
End Class
ReadOnly Property R(x, y)
Get
Return Nothing
End Get
End Property
Private WriteOnly Property S As Integer
Set(value As Integer)
End Set
End Property
Structure S
End Structure
Private Shared ReadOnly Property T As Integer
Get
Return 0
End Get
End Property
Private T
Friend MustOverride Overloads Function U()
Protected Property U
Protected V As Object
Friend Shared Property V
End Class
]]></file>
</compilation>)
' Note: Unlike Dev10, the error with 'S' is reported on the property
' rather than the struct, even though the struct appears first in source.
' That is because types are resolved before other members.
Dim expectedErrors1 = <errors><![CDATA[
BC30260: 'P' is already declared as 'Public Overloads Property P As Object' in this class.
Overloads Function P(o)
~
BC30260: 'Q' is already declared as 'Public Shared Overloads Property Q(o As Object) As Object' in this class.
Overloads Sub Q()
~
BC30260: 'R' is already declared as 'Class R' in this class.
ReadOnly Property R(x, y)
~
BC30260: 'S' is already declared as 'Structure S' in this class.
Private WriteOnly Property S As Integer
~
BC30260: 'T' is already declared as 'Private Shared ReadOnly Property T As Integer' in this class.
Private T
~
BC30260: 'U' is already declared as 'Friend MustOverride Overloads Function U() As Object' in this class.
Protected Property U
~
BC30260: 'V' is already declared as 'Protected V As Object' in this class.
Friend Shared Property V
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30266ERR_BadOverrideAccess2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadLocalDimFlags1">
<file name="a.vb"><![CDATA[
Namespace NS1
Class base
Protected Overridable Function scen2(Of t)(ByVal x As t) As String
Return "30266"
End Function
Public Overridable Function scen1(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
Partial Class base
Friend Overridable Function scen3(Of t)(ByVal x As t) As String
Return "30266"
End Function
Protected Friend Overridable Function scen4(Of t)(ByVal x As t) As String
Return "30266"
End Function
Private Protected Overridable Function scen5(Of t)(ByVal x As t) As String
Return "30266"
End Function
Protected Overridable Function scen6(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
Partial Class derived
'COMPILEERROR: BC30266, "scen4"
Protected Overrides Function scen4(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
Class derived
Inherits base
'COMPILEERROR: BC30266, "scen2"
Friend Overrides Function scen2(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen3"
Public Overrides Function scen3(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen1"
Protected Overrides Function scen1(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen5"
Protected Overrides Function scen5(Of t)(ByVal x As t) As String
Return "30266"
End Function
'COMPILEERROR: BC30266, "scen6"
Private Protected Overrides Function scen6(Of t)(ByVal x As t) As String
Return "30266"
End Function
End Class
End Namespace
]]></file>
</compilation>,
parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_5))
Dim expectedErrors1 = <errors><![CDATA[
BC30266: 'Protected Overrides Function scen4(Of t)(x As t) As String' cannot override 'Protected Friend Overridable Function scen4(Of t)(x As t) As String' because they have different access levels.
Protected Overrides Function scen4(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Friend Overrides Function scen2(Of t)(x As t) As String' cannot override 'Protected Overridable Function scen2(Of t)(x As t) As String' because they have different access levels.
Friend Overrides Function scen2(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Public Overrides Function scen3(Of t)(x As t) As String' cannot override 'Friend Overridable Function scen3(Of t)(x As t) As String' because they have different access levels.
Public Overrides Function scen3(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Protected Overrides Function scen1(Of t)(x As t) As String' cannot override 'Public Overridable Function scen1(Of t)(x As t) As String' because they have different access levels.
Protected Overrides Function scen1(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Protected Overrides Function scen5(Of t)(x As t) As String' cannot override 'Private Protected Overridable Function scen5(Of t)(x As t) As String' because they have different access levels.
Protected Overrides Function scen5(Of t)(ByVal x As t) As String
~~~~~
BC30266: 'Private Protected Overrides Function scen6(Of t)(x As t) As String' cannot override 'Protected Overridable Function scen6(Of t)(x As t) As String' because they have different access levels.
Private Protected Overrides Function scen6(Of t)(ByVal x As t) As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30267ERR_CantOverrideNotOverridable2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverrideNotOverridable2">
<file name="a.vb"><![CDATA[
Class c1
Class c1_0
Overridable Sub goo()
End Sub
End Class
Class c1_1
Inherits c1_0
NotOverridable Overrides Sub goo()
End Sub
End Class
Class c1_2
Inherits c1_1
'COMPILEERROR: BC30267, "goo"
Overrides Sub goo()
End Sub
End Class
End Class
Class c1_2
Inherits c1.c1_1
'COMPILEERROR: BC30267, "goo"
Overrides Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30267: 'Public Overrides Sub goo()' cannot override 'Public NotOverridable Overrides Sub goo()' because it is declared 'NotOverridable'.
Overrides Sub goo()
~~~
BC30267: 'Public Overrides Sub goo()' cannot override 'Public NotOverridable Overrides Sub goo()' because it is declared 'NotOverridable'.
Overrides Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30269ERR_DuplicateProcDef1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Class C1
Public Sub New() ' 1
End Sub
Public Sub New() ' 2
End Sub
Shared Sub New() ' ok :)
End Sub
Public Sub Goo1() ' 1
End Sub
Public Sub Goo1() ' 2
End Sub
Public Sub Goo1() ' 3
End Sub
Public overloads Sub Goo2() ' 1
End Sub
Public overloads Sub Goo2() ' 2
End Sub
Public Sub Goo3(Of T)(X As T) ' 1
End Sub
Public Sub Goo3(Of TT)(X As TT) ' 2
End Sub
Public Sub GooOK(x as Integer) ' 1
End Sub
Public Sub GooOK(x as Decimal) ' 2
End Sub
Public Shared Sub Main()
End Sub
End Class
Class Base
public overridable sub goo4() ' base
End sub
End Class
Class Derived
Inherits Base
public overrides sub goo4() ' derived 1
End sub
public overloads sub goo4() ' derived 2
End sub
End Class
Class PartialClass
Public Sub Goo5() ' 1
End Sub
Public Sub Goo6(x as integer)
End Sub
End Class
Partial Class PartialClass
Public Sub Goo5() ' 2
End Sub
Public Sub Goo6(y as integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Public Sub New()' has multiple definitions with identical signatures.
Public Sub New() ' 1
~~~
BC30269: 'Public Sub Goo1()' has multiple definitions with identical signatures.
Public Sub Goo1() ' 1
~~~~
BC30269: 'Public Sub Goo1()' has multiple definitions with identical signatures.
Public Sub Goo1() ' 2
~~~~
BC30269: 'Public Overloads Sub Goo2()' has multiple definitions with identical signatures.
Public overloads Sub Goo2() ' 1
~~~~
BC30269: 'Public Sub Goo3(Of T)(X As T)' has multiple definitions with identical signatures.
Public Sub Goo3(Of T)(X As T) ' 1
~~~~
BC30269: 'Public Overrides Sub goo4()' has multiple definitions with identical signatures.
public overrides sub goo4() ' derived 1
~~~~
BC30269: 'Public Sub Goo5()' has multiple definitions with identical signatures.
Public Sub Goo5() ' 1
~~~~
BC30269: 'Public Sub Goo6(x As Integer)' has multiple definitions with identical signatures.
Public Sub Goo6(x as integer)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30269ERR_DuplicateProcDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Interface ii
Sub abc()
End Interface
Structure teststruct
Implements ii
'COMPILEERROR: BC30269, "abc"
Public Sub abc() Implements ii.abc
End Sub
'COMPILEERROR: BC30269, "New"
Public Sub New(ByVal x As String)
End Sub
End Structure
Partial Structure teststruct
Implements ii
Public Sub New(ByVal x As String)
End Sub
Public Sub abc() Implements ii.abc
End Sub
End Structure
]]></file>
</compilation>)
' TODO: The last error is expected to go away once "Implements" is supported.
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Public Sub abc()' has multiple definitions with identical signatures.
Public Sub abc() Implements ii.abc
~~~
BC30269: 'Public Sub New(x As String)' has multiple definitions with identical signatures.
Public Sub New(ByVal x As String)
~~~
BC30583: 'ii.abc' cannot be implemented more than once.
Public Sub abc() Implements ii.abc
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(543162, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543162")>
<Fact()>
Public Sub BC30269ERR_DuplicateProcDef1_Shared()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Class C1
Public Sub New1() ' 1
End Sub
Public Shared Sub New1() ' 2
End Sub
End Class
]]></file>
</compilation>)
AssertTheseDiagnostics(compilation1, errs:=<expected><![CDATA[
BC30269: 'Public Sub New1()' has multiple definitions with identical signatures.
Public Sub New1() ' 1
~~~~
]]></expected>)
End Sub
<Fact>
Public Sub BC30270ERR_BadInterfaceMethodFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceMethodFlags1">
<file name="a.vb"><![CDATA[
Imports System.Collections
Interface I
Public Function A()
Private Function B()
Protected Function C()
Friend Function D()
Shared Function E()
MustInherit Function F()
NotInheritable Function G()
Overrides Function H()
Partial Function J()
NotOverridable Function K()
Overridable Function L()
Iterator Function Goo() as IEnumerator
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30270: 'Public' is not valid on an interface method declaration.
Public Function A()
~~~~~~
BC30270: 'Private' is not valid on an interface method declaration.
Private Function B()
~~~~~~~
BC30270: 'Protected' is not valid on an interface method declaration.
Protected Function C()
~~~~~~~~~
BC30270: 'Friend' is not valid on an interface method declaration.
Friend Function D()
~~~~~~
BC30270: 'Shared' is not valid on an interface method declaration.
Shared Function E()
~~~~~~
BC30242: 'MustInherit' is not valid on a method declaration.
MustInherit Function F()
~~~~~~~~~~~
BC30242: 'NotInheritable' is not valid on a method declaration.
NotInheritable Function G()
~~~~~~~~~~~~~~
BC30270: 'Overrides' is not valid on an interface method declaration.
Overrides Function H()
~~~~~~~~~
BC30270: 'Partial' is not valid on an interface method declaration.
Partial Function J()
~~~~~~~
BC30270: 'NotOverridable' is not valid on an interface method declaration.
NotOverridable Function K()
~~~~~~~~~~~~~~
BC30270: 'Overridable' is not valid on an interface method declaration.
Overridable Function L()
~~~~~~~~~~~
BC30270: 'Iterator' is not valid on an interface method declaration.
Iterator Function Goo() as IEnumerator
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30273ERR_BadInterfacePropertyFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfacePropertyFlags1">
<file name="a.vb"><![CDATA[
Imports System.Collections
Interface I
Public Property A
Private Property B
Protected Property C
Friend Property D
Shared Property E
MustInherit Property F
NotInheritable Property G
Overrides Property H
NotOverridable Property J
Overridable Property K
ReadOnly Property L ' No error
WriteOnly Property M ' No error
Default Property N(o) ' No error
Iterator Property Goo() as IEnumerator
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30273: 'Public' is not valid on an interface property declaration.
Public Property A
~~~~~~
BC30273: 'Private' is not valid on an interface property declaration.
Private Property B
~~~~~~~
BC30273: 'Protected' is not valid on an interface property declaration.
Protected Property C
~~~~~~~~~
BC30273: 'Friend' is not valid on an interface property declaration.
Friend Property D
~~~~~~
BC30273: 'Shared' is not valid on an interface property declaration.
Shared Property E
~~~~~~
BC30639: Properties cannot be declared 'MustInherit'.
MustInherit Property F
~~~~~~~~~~~
BC30639: Properties cannot be declared 'NotInheritable'.
NotInheritable Property G
~~~~~~~~~~~~~~
BC30273: 'Overrides' is not valid on an interface property declaration.
Overrides Property H
~~~~~~~~~
BC30273: 'NotOverridable' is not valid on an interface property declaration.
NotOverridable Property J
~~~~~~~~~~~~~~
BC30273: 'Overridable' is not valid on an interface property declaration.
Overridable Property K
~~~~~~~~~~~
BC30273: 'Iterator' is not valid on an interface property declaration.
Iterator Property Goo() as IEnumerator
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30275ERR_InterfaceCantUseEventSpecifier1()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceCantUseEventSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
'COMPILEERROR: BC30275, "friend"
Friend Event goo()
End Interface
Interface I2
'COMPILEERROR: BC30275, "protected"
Protected Event goo()
End Interface
Interface I3
'COMPILEERROR: BC30275, "Private"
Private Event goo()
End Interface
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InterfaceCantUseEventSpecifier1, "Friend").WithArguments("Friend"),
Diagnostic(ERRID.ERR_InterfaceCantUseEventSpecifier1, "Protected").WithArguments("Protected"),
Diagnostic(ERRID.ERR_InterfaceCantUseEventSpecifier1, "Private").WithArguments("Private"))
End Sub
<WorkItem(539943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539943")>
<Fact>
Public Sub BC30280ERR_BadEmptyEnum1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadEmptyEnum1">
<file name="a.vb"><![CDATA[
Enum SEX
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30280: Enum 'SEX' must contain at least one member.
Enum SEX
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30283ERR_CantOverrideConstructor()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverrideConstructor">
<file name="a.vb"><![CDATA[
Class Class2
Inherits Class1
Overrides Sub New()
End Sub
End Class
Class Class1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30283: 'Sub New' cannot be declared 'Overrides'.
Overrides Sub New()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30284ERR_OverrideNotNeeded3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideNotNeeded3">
<file name="a.vb"><![CDATA[
Imports System
Namespace NS30284
Public Class Class1
Dim xprop2, xprop3, xprop5
End Class
Public Class Class2
Inherits Class1
Interface interface1
ReadOnly Property prop1()
WriteOnly Property prop2()
WriteOnly Property prop3()
ReadOnly Property prop5()
End Interface
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal val As Short)
MyBase.New()
End Sub
'COMPILEERROR: BC30284, "prop1"
Overrides WriteOnly Property prop1() As String
Set(ByVal Value As String)
End Set
End Property
'COMPILEERROR: BC30284, "prop2"
Overrides ReadOnly Property prop2() As String
Get
Return "30284"
End Get
End Property
'COMPILEERROR: BC30284, "prop3"
Overrides Property prop3() As String
Get
Return "30284"
End Get
Set(ByVal Value As String)
End Set
End Property
'COMPILEERROR: BC30284, "prop5"
Overrides ReadOnly Property prop5()
Get
Return "30284"
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30284: property 'prop1' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides WriteOnly Property prop1() As String
~~~~~
BC30284: property 'prop2' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides ReadOnly Property prop2() As String
~~~~~
BC30284: property 'prop3' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides Property prop3() As String
~~~~~
BC30284: property 'prop5' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides ReadOnly Property prop5()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' <Fact()>
' Public Sub BC30293ERR_RecordEmbeds2()
' Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib(
' <compilation name="RecordEmbeds2">
' <file name="a.vb"><![CDATA[
' Class C1
' End Class
' Class C2
' Inherits C1
' Overrides WriteOnly Property prop1() As String
' Set(ByVal value As String)
' End Set
' End Property
' End Class
' ]]></file>
' </compilation>)
' Dim expectedErrors1 = <errors><![CDATA[
'BC30293: property 'prop1' cannot be declared 'Overrides' because it does not override a property in a base class.
' Overrides WriteOnly Property prop1() As String
' ~~~~~~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
' End Sub
<Fact>
Public Sub BC30294ERR_RecordCycle2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="RecordCycle2">
<file name="a.vb"><![CDATA[
Public Structure yyy
Dim a As yyy
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30294: Structure 'yyy' cannot contain an instance of itself:
'yyy' contains 'yyy' (variable 'a').
Dim a As yyy
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30296ERR_InterfaceCycle1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceCycle1">
<file name="a.vb"><![CDATA[
Public Class c0
Protected Class cls1
Public Interface I2
Interface I2
Inherits I2
End Interface
End Interface
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30296: Interface 'c0.cls1.I2.I2' cannot inherit from itself:
'c0.cls1.I2.I2' inherits from 'c0.cls1.I2.I2'.
Inherits I2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30299ERR_InheritsFromCantInherit3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsFromCantInherit3">
<file name="a.vb"><![CDATA[
Class c1
NotInheritable Class c1_1
Class c1_4
Inherits c1_1
End Class
End Class
Class c1_2
Inherits c1_1
End Class
End Class
Class c1_3
Inherits c1.c1_1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30299: 'c1_4' cannot inherit from class 'c1_1' because 'c1_1' is declared 'NotInheritable'.
Inherits c1_1
~~~~
BC30299: 'c1_2' cannot inherit from class 'c1_1' because 'c1_1' is declared 'NotInheritable'.
Inherits c1_1
~~~~
BC30299: 'c1_3' cannot inherit from class 'c1_1' because 'c1_1' is declared 'NotInheritable'.
Inherits c1.c1_1
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30300ERR_OverloadWithOptional2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithOptional2">
<file name="a.vb"><![CDATA[
Class Cla30300
'COMPILEERROR: BC30300, "goo"
Public Function goo(ByVal arg As ULong)
Return "BC30300"
End Function
Public Function goo(Optional ByVal arg As ULong = 1)
Return "BC30300"
End Function
'COMPILEERROR: BC30300, "goo1"
Public Function goo1()
Return "BC30300"
End Function
Public Function goo1(Optional ByVal arg As ULong = 1)
Return "BC30300"
End Function
'COMPILEERROR: BC30300, "goo2"
Public Function goo2(ByVal arg As Integer)
Return "BC30300"
End Function
Public Function goo2(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
Return "BC30300"
End Function
'COMPILEERROR: BC30300, "goo3"
Public Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
Return "BC30300"
End Function
Public Function goo3(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
Return "BC30300"
End Function
End Class
Interface Scen2_1
'COMPILEERROR: BC30300, "goo"
Function goo(ByVal arg As ULong)
Function goo(Optional ByVal arg As ULong = 1)
'COMPILEERROR: BC30300, "goo1"
Function goo1()
Function goo1(Optional ByVal arg As ULong = 1)
'COMPILEERROR: BC30300, "goo2"
Function goo2(ByVal arg As Integer)
Function goo2(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
'COMPILEERROR: BC30300, "goo3"
Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
Function goo3(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30300: 'Public Function goo(arg As ULong) As Object' and 'Public Function goo([arg As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Public Function goo(ByVal arg As ULong)
~~~
BC30300: 'Public Function goo3(arg As Integer, arg1 As ULong) As Object' and 'Public Function goo3(arg As Integer, [arg1 As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Public Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
~~~~
BC30300: 'Function goo(arg As ULong) As Object' and 'Function goo([arg As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Function goo(ByVal arg As ULong)
~~~
BC30300: 'Function goo3(arg As Integer, arg1 As ULong) As Object' and 'Function goo3(arg As Integer, [arg1 As ULong = 1]) As Object' cannot overload each other because they differ only by optional parameters.
Function goo3(ByVal arg As Integer, ByVal arg1 As ULong)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30301ERR_OverloadWithReturnType2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateProcDef1">
<file name="a.vb"><![CDATA[
Class C1
End Class
Class C2
End Class
Class C3
Public Function Goo1(x as Integer) as Boolean ' 1
return true
End Function
Public Function Goo1(x as Integer) as Boolean ' 2
return true
End Function
Public Function Goo1(x as Integer) as Boolean ' 3
return true
End Function
Public Function Goo1(x as Integer) as Decimal ' 4
return 2.2
End Function
Public Function Goo1(x as Integer) as String ' 5
return "42"
End Function
Public Function Goo2(Of T as C1)(x as Integer) as T ' 1
return nothing
End Function
Public Function Goo2(Of S as C2)(x as Integer) as S ' 2
return nothing
End Function
Public Function Goo3(x as Integer) as Boolean ' 1
return true
End Function
Public Function Goo3(x as Decimal) as Boolean ' 2
return true
End Function
Public Function Goo3(x as Integer) as Boolean ' 3
return true
End Function
Public Function Goo3(x as Integer) as Boolean ' 4
return true
End Function
Public Function Goo3(x as Integer) as String ' 5
return true
End Function
Public Shared Sub Main()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Public Function Goo1(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo1(x as Integer) as Boolean ' 1
~~~~
BC30269: 'Public Function Goo1(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo1(x as Integer) as Boolean ' 2
~~~~
BC30301: 'Public Function Goo1(x As Integer) As Boolean' and 'Public Function Goo1(x As Integer) As Decimal' cannot overload each other because they differ only by return types.
Public Function Goo1(x as Integer) as Boolean ' 3
~~~~
BC30301: 'Public Function Goo1(x As Integer) As Decimal' and 'Public Function Goo1(x As Integer) As String' cannot overload each other because they differ only by return types.
Public Function Goo1(x as Integer) as Decimal ' 4
~~~~
BC30269: 'Public Function Goo2(Of T As C1)(x As Integer) As T' has multiple definitions with identical signatures.
Public Function Goo2(Of T as C1)(x as Integer) as T ' 1
~~~~
BC30269: 'Public Function Goo3(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo3(x as Integer) as Boolean ' 1
~~~~
BC30269: 'Public Function Goo3(x As Integer) As Boolean' has multiple definitions with identical signatures.
Public Function Goo3(x as Integer) as Boolean ' 3
~~~~
BC30301: 'Public Function Goo3(x As Integer) As Boolean' and 'Public Function Goo3(x As Integer) As String' cannot overload each other because they differ only by return types.
Public Function Goo3(x as Integer) as Boolean ' 4
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30301ERR_OverloadWithReturnType2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithReturnType2">
<file name="a.vb"><![CDATA[
Class Cla30301
'COMPILEERROR: BC30301, "goo"
Public Function goo(ByVal arg As ULong)
Return "BC30301"
End Function
Public Function goo(ByVal arg As ULong) As String
Return "BC30301"
End Function
'COMPILEERROR: BC30301, "goo1"
Public Function goo1()
Return "BC30301"
End Function
Public Function goo1() As String
Return "BC30301"
End Function
End Class
Interface Interface30301
'COMPILEERROR: BC30301, "goo"
Function goo(ByVal arg As ULong)
Function goo(ByVal arg As ULong) As String
'COMPILEERROR: BC30301, "goo1"
Function goo1()
Function goo1() As String
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30301: 'Public Function goo(arg As ULong) As Object' and 'Public Function goo(arg As ULong) As String' cannot overload each other because they differ only by return types.
Public Function goo(ByVal arg As ULong)
~~~
BC30301: 'Public Function goo1() As Object' and 'Public Function goo1() As String' cannot overload each other because they differ only by return types.
Public Function goo1()
~~~~
BC30301: 'Function goo(arg As ULong) As Object' and 'Function goo(arg As ULong) As String' cannot overload each other because they differ only by return types.
Function goo(ByVal arg As ULong)
~~~
BC30301: 'Function goo1() As Object' and 'Function goo1() As String' cannot overload each other because they differ only by return types.
Function goo1()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_01()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Class C
Dim A% As Integer
Dim B& As Long
Dim C@ As Decimal
Dim D! As Single
Dim E# As Double
Dim F$ As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Dim A% As Integer
~~
BC30302: Type character '&' cannot be used in a declaration with an explicit type.
Dim B& As Long
~~
BC30302: Type character '@' cannot be used in a declaration with an explicit type.
Dim C@ As Decimal
~~
BC30302: Type character '!' cannot be used in a declaration with an explicit type.
Dim D! As Single
~~
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
Dim E# As Double
~~
BC30302: Type character '$' cannot be used in a declaration with an explicit type.
Dim F$ As String
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_02()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Class C
Property A% As Integer
Property B& As Long
Property C@ As Decimal
Property D! As Single
Property E# As Double
Property F$ As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Property A% As Integer
~~
BC30302: Type character '&' cannot be used in a declaration with an explicit type.
Property B& As Long
~~
BC30302: Type character '@' cannot be used in a declaration with an explicit type.
Property C@ As Decimal
~~
BC30302: Type character '!' cannot be used in a declaration with an explicit type.
Property D! As Single
~~
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
Property E# As Double
~~
BC30302: Type character '$' cannot be used in a declaration with an explicit type.
Property F$ As String
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_03()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Option Infer On
Class C
Shared Sub Main()
For Each x% In New Integer() {1, 1}
Next
For Each x& In New Long() {1, 1}
Next
For Each x! In New Double() {1, 1}
Next
For Each x# In New Double() {1, 1}
Next
For Each x@ In New Decimal() {1, 1}
Next
'COMPILEERROR: BC30302
For Each x% As Long In New Long() {1, 1, 1}
Next
For Each x# As Single In New Double() {1, 1, 1}
Next
For Each x@ As Decimal In New Decimal() {1, 1, 1}
Next
For Each x! As Object In New Long() {1, 1, 1}
Next
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
For Each x% As Long In New Long() {1, 1, 1}
~~
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
For Each x# As Single In New Double() {1, 1, 1}
~~
BC30302: Type character '@' cannot be used in a declaration with an explicit type.
For Each x@ As Decimal In New Decimal() {1, 1, 1}
~~
BC30302: Type character '!' cannot be used in a declaration with an explicit type.
For Each x! As Object In New Long() {1, 1, 1}
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30302ERR_TypeCharWithType1_04()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb"><![CDATA[
Option Infer On
Imports System
Module Module1
Sub Main()
Dim arr15#(,) As Double ' Invalid
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30302: Type character '#' cannot be used in a declaration with an explicit type.
Dim arr15#(,) As Double ' Invalid
~~~~~~
BC42024: Unused local variable: 'arr15'.
Dim arr15#(,) As Double ' Invalid
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30303ERR_TypeCharOnSub()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeCharOnSub">
<file name="a.vb"><![CDATA[
Interface I1
Sub x%()
Sub x#()
Sub x@()
Sub x!()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30269: 'Sub x()' has multiple definitions with identical signatures.
Sub x%()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x%()
~~
BC30269: 'Sub x()' has multiple definitions with identical signatures.
Sub x#()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x#()
~~
BC30269: 'Sub x()' has multiple definitions with identical signatures.
Sub x@()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x@()
~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Sub x!()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30305ERR_PartialMethodDefaultParameterValue2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
'COMPILEERROR: BC30305, "Goo6"
Partial Private Sub Goo6(Optional ByVal x As Integer = 1)
End Sub
Private Sub Goo6(Optional ByVal x As Integer = 2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC37203: Optional parameter of a method 'Private Sub Goo6([x As Integer = 2])' does not have the same default value as the corresponding parameter of the partial method 'Private Sub Goo6([x As Integer = 1])'.
Private Sub Goo6(Optional ByVal x As Integer = 2)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30305ERR_OverloadWithDefault2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
'COMPILEERROR: BC30305, "Goo6"
Partial Private Sub Goo6(Optional ByVal x As Integer = 1)
End Sub
Sub Goo6(Optional ByVal x As Integer = 2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31441: Method 'Goo6' must be declared 'Private' in order to implement partial method 'Goo6'.
Sub Goo6(Optional ByVal x As Integer = 2)
~~~~
BC37203: Optional parameter of a method 'Public Sub Goo6([x As Integer = 2])' does not have the same default value as the corresponding parameter of the partial method 'Private Sub Goo6([x As Integer = 1])'.
Sub Goo6(Optional ByVal x As Integer = 2)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(ParamArray x() As Integer)
End Sub
Private Sub Goo6(x() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC37204: Parameter of a method 'Private Sub Goo6(x As Integer())' differs by ParamArray modifier from the corresponding parameter of the partial method 'Private Sub Goo6(ParamArray x As Integer())'.
Private Sub Goo6(x() As Integer)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(x() As Integer)
End Sub
Private Sub Goo6(ParamArray x() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC37204: Parameter of a method 'Private Sub Goo6(ParamArray x As Integer())' differs by ParamArray modifier from the corresponding parameter of the partial method 'Private Sub Goo6(x As Integer())'.
Private Sub Goo6(ParamArray x() As Integer)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
''' <remarks>Only use with PEModuleSymbol and PEParameterSymbol</remarks>
Private Sub AssertHasExactlyOneParamArrayAttribute(m As ModuleSymbol, paramSymbol As ParameterSymbol)
Dim peModule = DirectCast(m, PEModuleSymbol).Module
Dim paramHandle = DirectCast(paramSymbol, PEParameterSymbol).Handle
Assert.Equal(1, peModule.GetParamArrayCountOrThrow(paramHandle))
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Private Sub Goo6(x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(x() As Integer)
End Sub
Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(ParamArray x() As Integer)
End Sub
Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Private Sub Goo6(ParamArray x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_7()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
Private Sub Goo6(<System.ParamArray()> x() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30663: Attribute 'ParamArrayAttribute' cannot be applied multiple times.
Private Sub Goo6(<System.ParamArray()> x() As Integer)
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_8()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(ParamArray x() As Integer)
End Sub
Private Sub Goo6(ParamArray x() As Integer)
End Sub
Sub Use()
Goo6()
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.True(GooParam.IsParamArray)
AssertHasExactlyOneParamArrayAttribute(m, GooParam)
End Sub)
End Sub
<Fact>
Public Sub ERR_PartialMethodParamArrayMismatch2_9()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Public Class Cls30305
Partial Private Sub Goo6(x() As Integer)
End Sub
Private Sub Goo6(x() As Integer)
End Sub
Sub Use()
Goo6(Nothing)
End Sub
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))
CompileAndVerify(compilation1,
symbolValidator:=Sub(m As ModuleSymbol)
Dim Cls30305 = m.GlobalNamespace.GetTypeMember("Cls30305")
Dim Goo6 = Cls30305.GetMember(Of MethodSymbol)("Goo6")
Dim GooParam = Goo6.Parameters(0)
Assert.Equal(0, GooParam.GetAttributes().Length)
Assert.False(GooParam.IsParamArray)
End Sub)
End Sub
<Fact()>
Public Sub BC30307ERR_OverrideWithDefault2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverloadWithDefault2">
<file name="a.vb"><![CDATA[
Module mod30307
Class Class1
Overridable Sub Scen1(Optional ByVal x As String = "bob")
End Sub
Overridable Sub Scen2(Optional ByVal x As Object = "bob")
End Sub
Overridable Function Scen3(Optional ByVal x As Integer = 3)
End Function
Overridable Function Scen4(Optional ByVal x As Integer = 3)
End Function
End Class
Class class2
Inherits Class1
'COMPILEERROR: BC30307, "Scen1"
Overrides Sub Scen1(Optional ByVal x As String = "BOB")
End Sub
'COMPILEERROR: BC30307, "Scen2"
Overrides Sub Scen2(Optional ByVal x As Object = "BOB")
End Sub
Overrides Function Scen3(Optional ByVal x As Integer = 2 + 1)
End Function
'COMPILEERROR: BC30307, "Scen4"
Overrides Function Scen4(Optional ByVal x As Integer = 4)
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30307: 'Public Overrides Sub Scen1([x As String = "BOB"])' cannot override 'Public Overridable Sub Scen1([x As String = "bob"])' because they differ by the default values of optional parameters.
Overrides Sub Scen1(Optional ByVal x As String = "BOB")
~~~~~
BC30307: 'Public Overrides Sub Scen2([x As Object = "BOB"])' cannot override 'Public Overridable Sub Scen2([x As Object = "bob"])' because they differ by the default values of optional parameters.
Overrides Sub Scen2(Optional ByVal x As Object = "BOB")
~~~~~
BC30307: 'Public Overrides Function Scen4([x As Integer = 4]) As Object' cannot override 'Public Overridable Function Scen4([x As Integer = 3]) As Object' because they differ by the default values of optional parameters.
Overrides Function Scen4(Optional ByVal x As Integer = 4)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30308ERR_OverrideWithOptional2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverrideWithOptional2">
<file name="a.vb"><![CDATA[
Module mod30308
Class Class1
Overridable Sub Scen1(Optional ByVal x As String = "bob")
End Sub
Overridable Sub Scen2(Optional ByVal x As Object = "bob")
End Sub
Overridable Function Scen3(Optional ByVal x As Integer = 3)
End Function
Overridable Function Scen4(Optional ByVal x As Integer = 3)
End Function
End Class
Class class2
Inherits Class1
'COMPILEERROR: BC30308, "Scen1"
Overrides Sub Scen1(ByVal x As String)
End Sub
'COMPILEERROR: BC30308, "Scen2"
Overrides Sub Scen2(ByVal x As Object)
End Sub
Overrides Function Scen3(ByVal x As Integer)
End Function
'COMPILEERROR: BC30308, "Scen4"
Overrides Function Scen4(ByVal x As Integer)
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30308: 'Public Overrides Sub Scen1(x As String)' cannot override 'Public Overridable Sub Scen1([x As String = "bob"])' because they differ by optional parameters.
Overrides Sub Scen1(ByVal x As String)
~~~~~
BC30308: 'Public Overrides Sub Scen2(x As Object)' cannot override 'Public Overridable Sub Scen2([x As Object = "bob"])' because they differ by optional parameters.
Overrides Sub Scen2(ByVal x As Object)
~~~~~
BC30308: 'Public Overrides Function Scen3(x As Integer) As Object' cannot override 'Public Overridable Function Scen3([x As Integer = 3]) As Object' because they differ by optional parameters.
Overrides Function Scen3(ByVal x As Integer)
~~~~~
BC30308: 'Public Overrides Function Scen4(x As Integer) As Object' cannot override 'Public Overridable Function Scen4([x As Integer = 3]) As Object' because they differ by optional parameters.
Overrides Function Scen4(ByVal x As Integer)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30345ERR_OverloadWithByref2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithByref2">
<file name="a.vb"><![CDATA[
Public Class Cls30345
Public overloads Sub Goo1(ByVal x as Integer) ' 1
End Sub
Public overloads Sub Goo1(ByRef x as Integer) ' 2
End Sub
Public overloads Function Goo2(ByVal x as Integer) as Integer' 1
return 1
End Function
Public overloads Function Goo2(ByRef x as Integer) as Decimal' 2
return 2.2
End Function
Public Shared Sub Main()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30345: 'Public Overloads Sub Goo1(x As Integer)' and 'Public Overloads Sub Goo1(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Public overloads Sub Goo1(ByVal x as Integer) ' 1
~~~~
BC30301: 'Public Overloads Function Goo2(x As Integer) As Integer' and 'Public Overloads Function Goo2(ByRef x As Integer) As Decimal' cannot overload each other because they differ only by return types.
Public overloads Function Goo2(ByVal x as Integer) as Integer' 1
~~~~
BC30345: 'Public Overloads Function Goo2(x As Integer) As Integer' and 'Public Overloads Function Goo2(ByRef x As Integer) As Decimal' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Public overloads Function Goo2(ByVal x as Integer) as Integer' 1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30345ERR_OverloadWithByref2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithByref2">
<file name="a.vb"><![CDATA[
Public Class Cls30345
'COMPILEERROR: BC30345, "Goo"
Partial Private Sub Goo(Optional ByVal x As Integer = 2)
End Sub
Sub Goo(Optional ByRef x As Integer = 2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30345: 'Private Sub Goo([x As Integer = 2])' and 'Public Sub Goo([ByRef x As Integer = 2])' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Partial Private Sub Goo(Optional ByVal x As Integer = 2)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30354ERR_InheritsFromNonInterface()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InheritsFromNonInterface">
<file name="a.vb"><![CDATA[
Module M1
Interface I1
Inherits System.Enum
End Interface
Interface I2
Inherits Scen1
End Interface
Interface I3
Inherits System.Exception
End Interface
NotInheritable Class Scen1
End Class
END Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30354: Interface can inherit only from another interface.
Inherits System.Enum
~~~~~~~~~~~
BC30354: Interface can inherit only from another interface.
Inherits Scen1
~~~~~
BC30354: Interface can inherit only from another interface.
Inherits System.Exception
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30359ERR_DuplicateDefaultProps1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
Default Property P(o)
ReadOnly Property Q(o)
Default WriteOnly Property R(o) ' BC30359
Default Property P(x, y)
Default Property Q(x, y) ' BC30359
Property R(x, y)
End Interface
Class C
Default Property P(o)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
ReadOnly Property Q(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property R(o) ' BC30359
Set(value)
End Set
End Property
Default Property P(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Default Property Q(x, y) ' BC30359
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
Structure S
Default Property P(o)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
ReadOnly Property Q(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property R(o) ' BC30359
Set(value)
End Set
End Property
Default Property P(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Default Property Q(x, y) ' BC30359
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R(x, y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
compilation1.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC30359: 'Default' can be applied to only one property name in a interface.
Default WriteOnly Property R(o) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a interface.
Default Property Q(x, y) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a class.
Default WriteOnly Property R(o) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a class.
Default Property Q(x, y) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a structure.
Default WriteOnly Property R(o) ' BC30359
~
BC30359: 'Default' can be applied to only one property name in a structure.
Default Property Q(x, y) ' BC30359
~
]]></errors>)
End Sub
' Property names with different case.
<Fact>
Public Sub BC30359ERR_DuplicateDefaultProps1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
Default ReadOnly Property P(o)
Default WriteOnly Property p(x, y)
End Interface
Class C
Default ReadOnly Property q(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property Q(x, y)
Set(value)
End Set
End Property
End Class
Structure S
Default ReadOnly Property R(o)
Get
Return Nothing
End Get
End Property
Default WriteOnly Property r(x, y)
Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
compilation1.AssertNoErrors()
End Sub
<Fact>
Public Sub BC30361ERR_DefaultMissingFromProperty2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DefaultMissingFromProperty2">
<file name="a.vb"><![CDATA[
MustInherit Class C
Default Overridable Overloads ReadOnly Property P(x, y)
Get
Return Nothing
End Get
End Property
MustOverride Overloads Property P
End Class
Interface I
Overloads WriteOnly Property Q(o)
Overloads ReadOnly Property Q
Default Overloads Property Q(x, y)
End Interface
Structure S
ReadOnly Property R(x)
Get
Return Nothing
End Get
End Property
Default ReadOnly Property R(x, y)
Get
Return Nothing
End Get
End Property
Default ReadOnly Property R(x, y, z)
Get
Return Nothing
End Get
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30361: 'Public Overridable Overloads ReadOnly Default Property P(x As Object, y As Object) As Object' and 'Public MustOverride Overloads Property P As Object' cannot overload each other because only one is declared 'Default'.
MustOverride Overloads Property P
~
BC30361: 'Default Property Q(x As Object, y As Object) As Object' and 'WriteOnly Property Q(o As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads WriteOnly Property Q(o)
~
BC30361: 'Default Property Q(x As Object, y As Object) As Object' and 'ReadOnly Property Q As Object' cannot overload each other because only one is declared 'Default'.
Overloads ReadOnly Property Q
~
BC30361: 'Public ReadOnly Default Property R(x As Object, y As Object) As Object' and 'Public ReadOnly Property R(x As Object) As Object' cannot overload each other because only one is declared 'Default'.
ReadOnly Property R(x)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Property names with different case.
<Fact>
Public Sub BC30361ERR_DefaultMissingFromProperty2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DefaultMissingFromProperty2">
<file name="a.vb"><![CDATA[
Interface I
Default Overloads ReadOnly Property P(o)
Overloads WriteOnly Property p(x, y)
End Interface
Class C
Overloads ReadOnly Property q(o)
Get
Return Nothing
End Get
End Property
Default Overloads WriteOnly Property Q(x, y)
Set(value)
End Set
End Property
End Class
Structure S
Overloads ReadOnly Property R(o)
Get
Return Nothing
End Get
End Property
Default Overloads WriteOnly Property r(x, y)
Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
compilation1.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC30361: 'ReadOnly Default Property P(o As Object) As Object' and 'WriteOnly Property p(x As Object, y As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads WriteOnly Property p(x, y)
~
BC30361: 'Public Overloads WriteOnly Default Property Q(x As Object, y As Object) As Object' and 'Public Overloads ReadOnly Property q(o As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads ReadOnly Property q(o)
~
BC30361: 'Public Overloads WriteOnly Default Property r(x As Object, y As Object) As Object' and 'Public Overloads ReadOnly Property R(o As Object) As Object' cannot overload each other because only one is declared 'Default'.
Overloads ReadOnly Property R(o)
~
]]></errors>)
End Sub
<Fact>
Public Sub BC30362ERR_OverridingPropertyKind2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverridingPropertyKind2">
<file name="a.vb"><![CDATA[
Public Class Class1
Dim xprop11, xprop12
Public Overridable ReadOnly Property prop10()
Get
Return "Class1 prop10"
End Get
End Property
Public Overridable WriteOnly Property prop11()
Set(ByVal Value)
xprop11 = Value
End Set
End Property
Public Overridable Property prop12()
Get
prop12 = xprop12
End Get
Set(ByVal Value)
xprop12 = Value
End Set
End Property
End Class
Public Class Class2
Inherits Class1
'COMPILEERROR: BC30362, "prop10"
Overrides WriteOnly Property prop10()
Set(ByVal Value)
End Set
End Property
'COMPILEERROR: BC30362, "prop11"
Overrides ReadOnly Property prop11()
Get
End Get
End Property
'COMPILEERROR: BC30362, "prop12"
Overrides ReadOnly Property prop12()
Get
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30362: 'Public Overrides WriteOnly Property prop10 As Object' cannot override 'Public Overridable ReadOnly Property prop10 As Object' because they differ by 'ReadOnly' or 'WriteOnly'.
Overrides WriteOnly Property prop10()
~~~~~~
BC30362: 'Public Overrides ReadOnly Property prop11 As Object' cannot override 'Public Overridable WriteOnly Property prop11 As Object' because they differ by 'ReadOnly' or 'WriteOnly'.
Overrides ReadOnly Property prop11()
~~~~~~
BC30362: 'Public Overrides ReadOnly Property prop12 As Object' cannot override 'Public Overridable Property prop12 As Object' because they differ by 'ReadOnly' or 'WriteOnly'.
Overrides ReadOnly Property prop12()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30362ERR_OverridingPropertyKind3()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="OverridingPropertyKind3">
<file name="a.vb"><![CDATA[
Class D3
Inherits D2
Public Overrides Property P_rw_rw_r As Integer
Get
Return MyBase.P_rw_rw_r
End Get
Set(value As Integer)
MyBase.P_rw_r_w = value
End Set
End Property
Public Overrides Property P_rw_rw_w As Integer
Get
Return MyBase.P_rw_rw_r
End Get
Set(value As Integer)
MyBase.P_rw_rw_w = value
End Set
End Property
End Class
]]></file>
</compilation>, ClassesWithReadWriteProperties)
Dim expectedErrors1 = <errors><![CDATA[
BC30362: 'Public Overrides Property P_rw_rw_r As Integer' cannot override 'Public Overrides ReadOnly Property P_rw_rw_r As Integer' because they differ by 'ReadOnly' or 'WriteOnly'.
Public Overrides Property P_rw_rw_r As Integer
~~~~~~~~~
BC30362: 'Public Overrides Property P_rw_rw_w As Integer' cannot override 'Public Overrides WriteOnly Property P_rw_rw_w As Integer' because they differ by 'ReadOnly' or 'WriteOnly'.
Public Overrides Property P_rw_rw_w As Integer
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30364ERR_BadFlagsOnNew1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadFlagsOnNew1">
<file name="a.vb"><![CDATA[
Class S1
overridable SUB NEW()
end sub
End Class
Class S2
Shadows SUB NEW()
end sub
End Class
Class S3
MustOverride SUB NEW()
End Class
Class S4
notoverridable SUB NEW()
end sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30364: 'Sub New' cannot be declared 'overridable'.
overridable SUB NEW()
~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'Shadows'.
Shadows SUB NEW()
~~~~~~~
BC30364: 'Sub New' cannot be declared 'MustOverride'.
MustOverride SUB NEW()
~~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'notoverridable'.
notoverridable SUB NEW()
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30366ERR_OverloadingPropertyKind2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadingPropertyKind2">
<file name="a.vb"><![CDATA[
Class Cls30366(Of T)
' COMPILEERROR: BC30366, "P1"
ReadOnly Property P1() As T
Get
End Get
End Property
' COMPILEERROR: BC30366, "P2"
WriteOnly Property P2() As T
Set(ByVal Value As T)
End Set
End Property
Default Property P3(ByVal i As Integer) As T
Get
End Get
Set(ByVal Value As T)
End Set
End Property
End Class
Partial Class Cls30366(Of T)
WriteOnly Property P1() As T
Set(ByVal Value As T)
End Set
End Property
ReadOnly Property P2() As T
Get
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30366: 'Public ReadOnly Property P1 As T' and 'Public WriteOnly Property P1 As T' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
ReadOnly Property P1() As T
~~
BC30366: 'Public WriteOnly Property P2 As T' and 'Public ReadOnly Property P2 As T' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.
WriteOnly Property P2() As T
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30368ERR_OverloadWithArrayVsParamArray2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithArrayVsParamArray2">
<file name="a.vb"><![CDATA[
Class Cls30368_1(Of T)
Sub goo(ByVal p() As String)
End Sub
Sub goo(ByVal ParamArray v() As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30368: 'Public Sub goo(p As String())' and 'Public Sub goo(ParamArray v As String())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Sub goo(ByVal p() As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30368ERR_OverloadWithArrayVsParamArray2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithArrayVsParamArray2">
<file name="a.vb"><![CDATA[
Class Cls30368_1(Of T)
Sub goo(ByVal p() As String)
End Sub
Sub goo(ByVal ParamArray v() As String)
End Sub
End Class
Class Cls30368(Of T)
Overloads Property Goo1(ByVal x()) As String
Get
Goo1 = "get: VariantArray"
End Get
Set(ByVal Value As String)
End Set
End Property
Overloads Property Goo1(ByVal ParamArray x()) As String
Get
Goo1 = "get: ParamArray"
End Get
Set(ByVal Value As String)
End Set
End Property
Overloads Property Goo2(ByVal x()) As String
Get
Goo2 = "get: FixedArray"
End Get
Set(ByVal Value As String)
End Set
End Property
Overloads Property Goo2(ByVal ParamArray x()) As String
Get
Goo2 = "get: ParamArray"
End Get
Set(ByVal Value As String)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30368: 'Public Sub goo(p As String())' and 'Public Sub goo(ParamArray v As String())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Sub goo(ByVal p() As String)
~~~
BC30368: 'Public Overloads Property Goo1(x As Object()) As String' and 'Public Overloads Property Goo1(ParamArray x As Object()) As String' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Overloads Property Goo1(ByVal x()) As String
~~~~
BC30368: 'Public Overloads Property Goo2(x As Object()) As String' and 'Public Overloads Property Goo2(ParamArray x As Object()) As String' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Overloads Property Goo2(ByVal x()) As String
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30371ERR_ModuleAsType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
End Module
Module M2
End Module
Module M3
End Module
Interface IA(Of T As M1)
End Interface
Interface IB
Sub M(Of T As M2)()
End Interface
Interface IC(Of T)
End Interface
Class C
Shared Sub M(o As IC(Of M3))
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30371: Module 'M1' cannot be used as a type.
Interface IA(Of T As M1)
~~
BC30371: Module 'M2' cannot be used as a type.
Sub M(Of T As M2)()
~~
BC30371: Module 'M3' cannot be used as a type.
Shared Sub M(o As IC(Of M3))
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30371ERR_ModuleAsType1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
Class C1
Function goo As M1
Return Nothing
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30371: Module 'M1' cannot be used as a type.
Function goo As M1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30385ERR_BadDelegateFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadDelegateFlags1">
<file name="a.vb"><![CDATA[
Class C1
MustOverride Delegate Sub Del1()
NotOverridable Delegate Sub Del2()
Shared Delegate Sub Del3()
Overrides Delegate Sub Del4()
Overloads Delegate Sub Del5(ByRef y As Integer)
Partial Delegate Sub Del6()
Default Delegate Sub Del7()
ReadOnly Delegate Sub Del8()
WriteOnly Delegate Sub Del9()
MustInherit Delegate Sub Del10()
NotInheritable Delegate Sub Del11()
Widening Delegate Sub Del12()
Narrowing Delegate Sub Del13()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30385: 'MustOverride' is not valid on a Delegate declaration.
MustOverride Delegate Sub Del1()
~~~~~~~~~~~~
BC30385: 'NotOverridable' is not valid on a Delegate declaration.
NotOverridable Delegate Sub Del2()
~~~~~~~~~~~~~~
BC30385: 'Shared' is not valid on a Delegate declaration.
Shared Delegate Sub Del3()
~~~~~~
BC30385: 'Overrides' is not valid on a Delegate declaration.
Overrides Delegate Sub Del4()
~~~~~~~~~
BC30385: 'Overloads' is not valid on a Delegate declaration.
Overloads Delegate Sub Del5(ByRef y As Integer)
~~~~~~~~~
BC30385: 'Partial' is not valid on a Delegate declaration.
Partial Delegate Sub Del6()
~~~~~~~
BC30385: 'Default' is not valid on a Delegate declaration.
Default Delegate Sub Del7()
~~~~~~~
BC30385: 'ReadOnly' is not valid on a Delegate declaration.
ReadOnly Delegate Sub Del8()
~~~~~~~~
BC30385: 'WriteOnly' is not valid on a Delegate declaration.
WriteOnly Delegate Sub Del9()
~~~~~~~~~
BC30385: 'MustInherit' is not valid on a Delegate declaration.
MustInherit Delegate Sub Del10()
~~~~~~~~~~~
BC30385: 'NotInheritable' is not valid on a Delegate declaration.
NotInheritable Delegate Sub Del11()
~~~~~~~~~~~~~~
BC30385: 'Widening' is not valid on a Delegate declaration.
Widening Delegate Sub Del12()
~~~~~~~~
BC30385: 'Narrowing' is not valid on a Delegate declaration.
Narrowing Delegate Sub Del13()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538884")>
<Fact>
Public Sub BC30385ERR_BadDelegateFlags1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadDelegateFlags1">
<file name="a.vb"><![CDATA[
Structure S1
MustOverride Delegate Sub Del1()
NotOverridable Delegate Sub Del1()
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30385: 'MustOverride' is not valid on a Delegate declaration.
MustOverride Delegate Sub Del1()
~~~~~~~~~~~~
BC30385: 'NotOverridable' is not valid on a Delegate declaration.
NotOverridable Delegate Sub Del1()
~~~~~~~~~~~~~~
BC30179: delegate Class 'Del1' and delegate Class 'Del1' conflict in structure 'S1'.
NotOverridable Delegate Sub Del1()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30389ERR_InaccessibleSymbol2_AccessCheckCrossAssemblyDerived()
Dim other As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AccessCheckCrossAssemblyDerived1">
<file name="a.vb"><![CDATA[
Public Class C
Public Shared c_pub As Integer
Friend Shared c_int As Integer
Protected Shared c_pro As Integer
Protected Friend Shared c_intpro As Integer
Private Shared c_priv As Integer
End Class
Friend Class D
Public Shared d_pub As Integer
End Class
]]></file>
</compilation>)
CompilationUtils.AssertNoErrors(other)
Dim comp As VisualBasicCompilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="AccessCheckCrossAssemblyDerived2">
<file name="a.vb"><![CDATA[
Public Class A
Inherits C
Public Sub m()
Dim aa As Integer = C.c_pub
Dim bb As Integer = C.c_int
Dim cc As Integer = C.c_pro
Dim dd As Integer = C.c_intpro
Dim ee As Integer = C.c_priv
Dim ff As Integer = D.d_pub
End Sub
End Class
]]></file>
</compilation>,
{New VisualBasicCompilationReference(other)})
'BC30389: 'C.c_int' is not accessible in this context because it is 'Friend'.
' Dim bb As Integer = C.c_int
' ~~~~~~~
'BC30389: 'C.c_priv' is not accessible in this context because it is 'Private'.
' Dim ee As Integer = C.c_priv
' ~~~~~~~~
'BC30389: 'D' is not accessible in this context because it is 'Friend'.
' Dim ff As Integer = D.d_pub
' ~
comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleSymbol2, "C.c_int").WithArguments("C.c_int", "Friend"),
Diagnostic(ERRID.ERR_InaccessibleSymbol2, "C.c_priv").WithArguments("C.c_priv", "Private"),
Diagnostic(ERRID.ERR_InaccessibleSymbol2, "D").WithArguments("D", "Friend"))
End Sub
<Fact>
Public Sub BC30395ERR_BadRecordFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ERR_BadRecordFlags1">
<file name="a.vb"><![CDATA[
MustOverride Structure Del1
End Structure
NotOverridable Structure Del2
End Structure
Shared Structure Del3
End Structure
Overrides Structure Del4
End Structure
Overloads Structure Del5
End Structure
Partial Structure Del6
End Structure
Default Structure Del7
End Structure
ReadOnly Structure Del8
End Structure
WriteOnly Structure Del9
End Structure
Widening Structure Del12
End Structure
Narrowing Structure Del13
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30395: 'MustOverride' is not valid on a Structure declaration.
MustOverride Structure Del1
~~~~~~~~~~~~
BC30395: 'NotOverridable' is not valid on a Structure declaration.
NotOverridable Structure Del2
~~~~~~~~~~~~~~
BC30395: 'Shared' is not valid on a Structure declaration.
Shared Structure Del3
~~~~~~
BC30395: 'Overrides' is not valid on a Structure declaration.
Overrides Structure Del4
~~~~~~~~~
BC30395: 'Overloads' is not valid on a Structure declaration.
Overloads Structure Del5
~~~~~~~~~
BC30395: 'Default' is not valid on a Structure declaration.
Default Structure Del7
~~~~~~~
BC30395: 'ReadOnly' is not valid on a Structure declaration.
ReadOnly Structure Del8
~~~~~~~~
BC30395: 'WriteOnly' is not valid on a Structure declaration.
WriteOnly Structure Del9
~~~~~~~~~
BC30395: 'Widening' is not valid on a Structure declaration.
Widening Structure Del12
~~~~~~~~
BC30395: 'Narrowing' is not valid on a Structure declaration.
Narrowing Structure Del13
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30396ERR_BadEnumFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadEnumFlags1">
<file name="a.vb"><![CDATA[
MustOverride enum Del1
male
End enum
NotOverridable enum Del2
male
End enum
Shared enum Del3
male
End enum
Overrides enum Del4
male
End enum
Overloads enum Del5
male
End enum
Partial enum Del6
male
End enum
Default enum Del7
male
End enum
ReadOnly enum Del8
male
End enum
WriteOnly enum Del9
male
End enum
Widening enum Del12
male
End enum
Narrowing enum Del13
male
End enum
MustInherit Enum Del14
male
End Enum
NotInheritable Enum Del15
male
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30396: 'MustOverride' is not valid on an Enum declaration.
MustOverride enum Del1
~~~~~~~~~~~~
BC30396: 'NotOverridable' is not valid on an Enum declaration.
NotOverridable enum Del2
~~~~~~~~~~~~~~
BC30396: 'Shared' is not valid on an Enum declaration.
Shared enum Del3
~~~~~~
BC30396: 'Overrides' is not valid on an Enum declaration.
Overrides enum Del4
~~~~~~~~~
BC30396: 'Overloads' is not valid on an Enum declaration.
Overloads enum Del5
~~~~~~~~~
BC30396: 'Partial' is not valid on an Enum declaration.
Partial enum Del6
~~~~~~~
BC30396: 'Default' is not valid on an Enum declaration.
Default enum Del7
~~~~~~~
BC30396: 'ReadOnly' is not valid on an Enum declaration.
ReadOnly enum Del8
~~~~~~~~
BC30396: 'WriteOnly' is not valid on an Enum declaration.
WriteOnly enum Del9
~~~~~~~~~
BC30396: 'Widening' is not valid on an Enum declaration.
Widening enum Del12
~~~~~~~~
BC30396: 'Narrowing' is not valid on an Enum declaration.
Narrowing enum Del13
~~~~~~~~~
BC30396: 'MustInherit' is not valid on an Enum declaration.
MustInherit Enum Del14
~~~~~~~~~~~
BC30396: 'NotInheritable' is not valid on an Enum declaration.
NotInheritable Enum Del15
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30397ERR_BadInterfaceFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceFlags1">
<file name="a.vb"><![CDATA[
Class C1
MustOverride Interface Del1
End Interface
NotOverridable Interface Del2
End Interface
Shared Interface Del3
End Interface
Overrides Interface Del4
End Interface
Overloads Interface Del5
End Interface
Default Interface Del7
End Interface
ReadOnly Interface Del8
End Interface
WriteOnly Interface Del9
End Interface
Widening Interface Del12
End Interface
Narrowing Interface Del13
End Interface
MustInherit Interface Del14
End Interface
NotInheritable Interface Del15
End Interface
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30397: 'MustOverride' is not valid on an Interface declaration.
MustOverride Interface Del1
~~~~~~~~~~~~
BC30397: 'NotOverridable' is not valid on an Interface declaration.
NotOverridable Interface Del2
~~~~~~~~~~~~~~
BC30397: 'Shared' is not valid on an Interface declaration.
Shared Interface Del3
~~~~~~
BC30397: 'Overrides' is not valid on an Interface declaration.
Overrides Interface Del4
~~~~~~~~~
BC30397: 'Overloads' is not valid on an Interface declaration.
Overloads Interface Del5
~~~~~~~~~
BC30397: 'Default' is not valid on an Interface declaration.
Default Interface Del7
~~~~~~~
BC30397: 'ReadOnly' is not valid on an Interface declaration.
ReadOnly Interface Del8
~~~~~~~~
BC30397: 'WriteOnly' is not valid on an Interface declaration.
WriteOnly Interface Del9
~~~~~~~~~
BC30397: 'Widening' is not valid on an Interface declaration.
Widening Interface Del12
~~~~~~~~
BC30397: 'Narrowing' is not valid on an Interface declaration.
Narrowing Interface Del13
~~~~~~~~~
BC30397: 'MustInherit' is not valid on an Interface declaration.
MustInherit Interface Del14
~~~~~~~~~~~
BC30397: 'NotInheritable' is not valid on an Interface declaration.
NotInheritable Interface Del15
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30398ERR_OverrideWithByref2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverrideWithByref2">
<file name="a.vb"><![CDATA[
Module mod30398
Class Class1
Overridable Sub Scen1(ByRef x As String)
End Sub
Overridable Sub Scen2(ByRef x As Object)
End Sub
Overridable Function Scen3(ByRef x As Integer)
End Function
Overridable Function Scen4(ByRef x As Integer)
End Function
End Class
Class class2
Inherits Class1
'COMPILEERROR: BC30398, "Scen1"
Overrides Sub Scen1(ByVal x As String)
End Sub
'COMPILEERROR: BC30398, "Scen2"
Overrides Sub Scen2(ByVal x As Object)
End Sub
Overrides Function Scen3(ByVal x As Integer)
End Function
'COMPILEERROR: BC30398, "Scen4"
Overrides Function Scen4(ByVal x As Integer)
End Function
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30398: 'Public Overrides Sub Scen1(x As String)' cannot override 'Public Overridable Sub Scen1(ByRef x As String)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Sub Scen1(ByVal x As String)
~~~~~
BC30398: 'Public Overrides Sub Scen2(x As Object)' cannot override 'Public Overridable Sub Scen2(ByRef x As Object)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Sub Scen2(ByVal x As Object)
~~~~~
BC30398: 'Public Overrides Function Scen3(x As Integer) As Object' cannot override 'Public Overridable Function Scen3(ByRef x As Integer) As Object' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Function Scen3(ByVal x As Integer)
~~~~~
BC30398: 'Public Overrides Function Scen4(x As Integer) As Object' cannot override 'Public Overridable Function Scen4(ByRef x As Integer) As Object' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.
Overrides Function Scen4(ByVal x As Integer)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30401ERR_IdentNotMemberOfInterface4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IdentNotMemberOfInterface4">
<file name="a.vb"><![CDATA[
Interface IA
Function F() As Integer
Property P As Object
End Interface
Interface IB
End Interface
Class A
Implements IA
Public Function F(o As Object) As Integer Implements IA.F
Return Nothing
End Function
Public Property P As Boolean Implements IA.P
End Class
Class B
Implements IB
Public Function F() As Integer Implements IB.F
Return Nothing
End Function
Public Property P As Boolean Implements IB.P
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'A' must implement 'Function F() As Integer' for interface 'IA'.
Implements IA
~~
BC30149: Class 'A' must implement 'Property P As Object' for interface 'IA'.
Implements IA
~~
BC30401: 'F' cannot implement 'F' because there is no matching function on interface 'IA'.
Public Function F(o As Object) As Integer Implements IA.F
~~~~
BC30401: 'P' cannot implement 'P' because there is no matching property on interface 'IA'.
Public Property P As Boolean Implements IA.P
~~~~
BC30401: 'F' cannot implement 'F' because there is no matching function on interface 'IB'.
Public Function F() As Integer Implements IB.F
~~~~
BC30401: 'P' cannot implement 'P' because there is no matching property on interface 'IB'.
Public Property P As Boolean Implements IB.P
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30412ERR_WithEventsRequiresClass()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="WithEventsRequiresClass">
<file name="a.vb"><![CDATA[
Class ClsTest30412
'COMPILEERROR: BC30412, "Field003WithEvents"
Public WithEvents Field003WithEvents = {1, 2, 3}
End Class
Class ClsTest30412_2
'COMPILEERROR: BC30412, "Field002WithEvents"
Public WithEvents Field002WithEvents = New List(Of Integer) From {1, 2, 3}
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30412: 'WithEvents' variables must have an 'As' clause.
Public WithEvents Field003WithEvents = {1, 2, 3}
~~~~~~~~~~~~~~~~~~
BC30412: 'WithEvents' variables must have an 'As' clause.
Public WithEvents Field002WithEvents = New List(Of Integer) From {1, 2, 3}
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30413ERR_WithEventsAsStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="WithEventsAsStruct">
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Structure S
End Structure
Class C(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U)
WithEvents _i As I
WithEvents _a As A
WithEvents _s As S
WithEvents _1 As T1
WithEvents _2 As T2
WithEvents _3 As T3
WithEvents _4 As T4
WithEvents _5 As T5
WithEvents _6 As T6
WithEvents _7 As T7
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _s As S
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _1 As T1
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _3 As T3
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _4 As T4
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _5 As T5
~~
BC30413: 'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.
WithEvents _7 As T7
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30433ERR_ModuleCantUseMethodSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Protected Sub M()
End Sub
Shared Sub N()
End Sub
MustOverride Sub O()
Overridable Sub P()
End Sub
Overrides Sub Q()
End Sub
Shadows Sub R()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30433: Methods in a Module cannot be declared 'Protected'.
Protected Sub M()
~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Shared'.
Shared Sub N()
~~~~~~
BC30433: Methods in a Module cannot be declared 'MustOverride'.
MustOverride Sub O()
~~~~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Overridable'.
Overridable Sub P()
~~~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Overrides'.
Overrides Sub Q()
~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Shadows'.
Shadows Sub R()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30434ERR_ModuleCantUseEventSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseEventSpecifier1">
<file name="a.vb"><![CDATA[
Module Shdmod
'COMPILEERROR: BC30434, "Shadows"
Shadows Event testx()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30434: Events in a Module cannot be declared 'Shadows'.
Shadows Event testx()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure S
Protected F
Protected Property P
Property Q
Protected Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R
Get
Return Nothing
End Get
Protected Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected F
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Property P
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Get
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Set(value)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure S
Protected Friend F
Protected Friend Property P
Property Q
Protected Friend Get
Return Nothing
End Get
Set(value)
End Set
End Property
Property R
Get
Return Nothing
End Get
Protected Friend Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend F
~~~~~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Property P
~~~~~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Get
~~~~~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Set(value)
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure S
Property P
Protected Get
Return Nothing
End Get
Protected Friend Set(value)
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Protected'.
Protected Get
~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Protected Friend'.
Protected Friend Set(value)
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(531467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531467")>
<Fact>
Public Sub BC30435ERR_StructCantUseVarSpecifier1_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Structure ms
Dim s As Integer
Public Overridable Property p1()
Get
Return Nothing
End Get
Friend Set(ByVal Value)
End Set
End Property
Public NotOverridable Property p2()
Get
Return Nothing
End Get
Friend Set(ByVal Value)
End Set
End Property
Public MustOverride Property p3()
Public Overridable Sub T1()
End Sub
Public NotOverridable Sub T2()
End Sub
Public MustOverride Sub T3()
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30435: Members in a Structure cannot be declared 'Overridable'.
Public Overridable Property p1()
~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'NotOverridable'.
Public NotOverridable Property p2()
~~~~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Public NotOverridable Property p2()
~~
BC30435: Members in a Structure cannot be declared 'MustOverride'.
Public MustOverride Property p3()
~~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'Overridable'.
Public Overridable Sub T1()
~~~~~~~~~~~
BC30435: Members in a Structure cannot be declared 'NotOverridable'.
Public NotOverridable Sub T2()
~~~~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Public NotOverridable Sub T2()
~~
BC30435: Members in a Structure cannot be declared 'MustOverride'.
Public MustOverride Sub T3()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30436ERR_ModuleCantUseMemberSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseMemberSpecifier1">
<file name="a.vb"><![CDATA[
Module m1
Protected Enum myenum As Integer
one
End Enum
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30735: Type in a Module cannot be declared 'Protected'.
Protected Enum myenum As Integer
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30437ERR_InvalidOverrideDueToReturn2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class base(Of t)
'COMPILEERROR: BC30437, "toString"
Overrides Function tostring() As t
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30437: 'Public Overrides Function tostring() As t' cannot override 'Public Overridable Overloads Function ToString() As String' because they differ by their return types.
Overrides Function tostring() As t
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30438ERR_ConstantWithNoValue()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Namespace NS30438
Class c1
'COMPILEERROR: BC30438,"c1"
Const c1 As UInt16
End Class
Structure s1
'COMPILEERROR: BC30438,"c1"
Const c1 As UInt16
End Structure
Friend Module USign_001mod
'COMPILEERROR: BC30438,"c1"
Const c1 As UInt16
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30438: Constants must have a value.
Const c1 As UInt16
~~
BC30438: Constants must have a value.
Const c1 As UInt16
~~
BC30438: Constants must have a value.
Const c1 As UInt16
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(542127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542127")>
<Fact>
Public Sub BC30438ERR_ConstantWithNoValue02()
Dim source =
<compilation name="delegates">
<file name="a.vb"><![CDATA[
Option strict on
imports system
Class C1
Sub GOO()
'COMPILEERROR: BC30438
Const l6 As UInt16
Const l7 as new UInt16
End Sub
End Class
]]></file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected><![CDATA[
BC30438: Constants must have a value.
Const l6 As UInt16
~~
BC30438: Constants must have a value.
Const l7 as new UInt16
~~
BC30246: 'new' is not valid on a local constant declaration.
Const l7 as new UInt16
~~~
]]></expected>)
End Sub
<Fact>
Public Sub BC30443ERR_DuplicatePropertyGet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicatePropertyGet">
<file name="a.vb"><![CDATA[
Class C
Property P
Get
Return Nothing
End Get
Get
Return Nothing
End Get
Set
End Set
Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30443: 'Get' is already declared.
Get
~~~
BC30443: 'Get' is already declared.
Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30444ERR_DuplicatePropertySet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicatePropertySet">
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P
Set
End Set
Set
End Set
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30444: 'Set' is already declared.
Set
~~~
BC30444: 'Set' is already declared.
Set
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' <Fact()>
' Public Sub BC30445ERR_ConstAggregate()
' Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib(
'<compilation name="DuplicatePropertySet">
' <file name="a.vb"><![CDATA[
' Module Constant
' Const d() As Long = {1, 2}, e() As Long = {1, 2}
' Sub main()
' End Sub
' End Module
' ]]></file>
'</compilation>)
' Dim expectedErrors1 = <errors><![CDATA[
' BC30445: 'Set' is already declared.
' Set(ByRef value)
' ~~~~~~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
' End Sub
<Fact>
Public Sub BC30461ERR_BadClassFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadClassFlags1">
<file name="a.vb"><![CDATA[
NotOverridable class C1
End class
Shared class C2
End class
Overrides class C3
End class
Overloads class C4
End class
Partial class C5
End class
Default class C6
End class
ReadOnly class C7
End class
WriteOnly class C8
End class
Widening class C9
End class
Narrowing class C10
End class
MustInherit class C11
End class
NotInheritable class C12
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30461: Classes cannot be declared 'NotOverridable'.
NotOverridable class C1
~~~~~~~~~~~~~~
BC30461: Classes cannot be declared 'Shared'.
Shared class C2
~~~~~~
BC30461: Classes cannot be declared 'Overrides'.
Overrides class C3
~~~~~~~~~
BC30461: Classes cannot be declared 'Overloads'.
Overloads class C4
~~~~~~~~~
BC30461: Classes cannot be declared 'Default'.
Default class C6
~~~~~~~
BC30461: Classes cannot be declared 'ReadOnly'.
ReadOnly class C7
~~~~~~~~
BC30461: Classes cannot be declared 'WriteOnly'.
WriteOnly class C8
~~~~~~~~~
BC30461: Classes cannot be declared 'Widening'.
Widening class C9
~~~~~~~~
BC30461: Classes cannot be declared 'Narrowing'.
Narrowing class C10
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30467ERR_NonNamespaceOrClassOnImport2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicatePropertySet">
<file name="a.vb"><![CDATA[
'COMPILEERROR: BC30467, "ns1.intfc1"
Imports ns1.Intfc1
'COMPILEERROR: BC30467, "ns1.intfc2(Of String)"
Imports ns1.Intfc2(Of String)
Namespace ns1
Public Interface Intfc1
Sub Intfc1goo()
End Interface
Public Interface Intfc2(Of t)
Inherits Intfc1
Sub intfc2goo()
End Interface
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30467: 'Intfc1' for the Imports 'Intfc1' does not refer to a Namespace, Class, Structure, Enum or Module.
Imports ns1.Intfc1
~~~~~~~~~~
BC30467: 'Intfc2' for the Imports 'Intfc2(Of String)' does not refer to a Namespace, Class, Structure, Enum or Module.
Imports ns1.Intfc2(Of String)
~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30468ERR_TypecharNotallowed()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="TypecharNotallowed">
<file name="a.vb"><![CDATA[
Module M1
Function scen1() as System.Datetime@
End Function
End Module
Structure S1
Function scen1() as System.sTRING#
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30468: Type declaration characters are not valid in this context.
Function scen1() as System.Datetime@
~~~~~~~~~
BC30468: Type declaration characters are not valid in this context.
Function scen1() as System.sTRING#
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30476ERR_EventSourceIsArray()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventSourceIsArray">
<file name="a.vb"><![CDATA[
Public Class Class1
Class Class2
Event Goo()
End Class
'COMPILEERROR: BC30591, "h(3)",BC30476, "Class2"
Dim WithEvents h(3) As Class2
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30476: 'WithEvents' variables cannot be typed as arrays.
Dim WithEvents h(3) As Class2
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30479ERR_SharedConstructorWithParams()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedConstructorWithParams">
<file name="a.vb"><![CDATA[
Structure Struct1
Shared Sub new(ByVal x As Integer)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30479: Shared 'Sub New' cannot have any parameters.
Shared Sub new(ByVal x As Integer)
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30480ERR_SharedConstructorIllegalSpec1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedConstructorIllegalSpec1">
<file name="a.vb"><![CDATA[
Structure Struct1
Shared public Sub new()
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30480: Shared 'Sub New' cannot be declared 'public'.
Shared public Sub new()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30490ERR_BadFlagsWithDefault1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadFlagsWithDefault1">
<file name="a.vb"><![CDATA[
Class A
Default Private Property P(o)
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
Class B
Private ReadOnly Default Property Q(x, y)
Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30490: 'Default' cannot be combined with 'Private'.
Default Private Property P(o)
~~~~~~~
BC30490: 'Default' cannot be combined with 'Private'.
Private ReadOnly Default Property Q(x, y)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30497ERR_NewCannotHandleEvents()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NewCannotHandleEvents">
<file name="a.vb"><![CDATA[
Class Cla30497
'COMPILEERROR: BC30497, "New"
Sub New() Handles var1.event1
End Sub
End Class
Class Cla30497_1
'COMPILEERROR: BC30497, "New"
Shared Sub New() Handles var1.event1
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30497: 'Sub New' cannot handle events.
Sub New() Handles var1.event1
~~~
BC30497: 'Sub New' cannot handle events.
Shared Sub New() Handles var1.event1
~~~
]]></errors>
CompilationUtils.AssertTheseParseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30501ERR_BadFlagsOnSharedMeth1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class C
Shared NotOverridable Function F()
Return Nothing
End Function
Shared Overrides Function G()
Return Nothing
End Function
Overridable Shared Sub M()
End Sub
MustOverride Shared Sub N()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30501: 'Shared' cannot be combined with 'NotOverridable' on a method declaration.
Shared NotOverridable Function F()
~~~~~~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'Overrides' on a method declaration.
Shared Overrides Function G()
~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'Overridable' on a method declaration.
Overridable Shared Sub M()
~~~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'MustOverride' on a method declaration.
MustOverride Shared Sub N()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528324")>
<Fact>
Public Sub BC30501ERR_BadFlagsOnSharedMeth2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class A
Public Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
MustInherit Class B
Inherits A
Public Overrides Shared Sub G()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30501: 'Shared' cannot be combined with 'Overrides' on a method declaration.
Public Overrides Shared Sub G()
~~~~~~~~~
BC40005: sub 'G' shadows an overridable method in the base class 'A'. To override the base method, this method must be declared 'Overrides'.
Public Overrides Shared Sub G()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30502ERR_BadFlagsOnSharedProperty1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class C
NotOverridable Shared Property P
Overrides Shared Property Q
Overridable Shared Property R
Shared MustOverride Property S
Default Shared Property T(ByVal v)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30502: 'Shared' cannot be combined with 'NotOverridable' on a property declaration.
NotOverridable Shared Property P
~~~~~~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'Overrides' on a property declaration.
Overrides Shared Property Q
~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'Overridable' on a property declaration.
Overridable Shared Property R
~~~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'MustOverride' on a property declaration.
Shared MustOverride Property S
~~~~~~~~~~~~
BC30502: 'Shared' cannot be combined with 'Default' on a property declaration.
Default Shared Property T(ByVal v)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30503ERR_BadFlagsOnStdModuleProperty1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadFlagsOnStdModuleProperty1">
<file name="a.vb"><![CDATA[
Module M
Protected Property P
Shared Property Q
MustOverride Property R
Overridable Property S
Overrides Property T
Shadows Property U
Default Property V(o)
Get
Return Nothing
End Get
Set
End Set
End Property
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30503: Properties in a Module cannot be declared 'Protected'.
Protected Property P
~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Shared'.
Shared Property Q
~~~~~~
BC30503: Properties in a Module cannot be declared 'MustOverride'.
MustOverride Property R
~~~~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Overridable'.
Overridable Property S
~~~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Overrides'.
Overrides Property T
~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Shadows'.
Shadows Property U
~~~~~~~
BC30503: Properties in a Module cannot be declared 'Default'.
Default Property V(o)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30505ERR_SharedOnProcThatImpl()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedOnProcThatImpl">
<file name="a.vb"><![CDATA[
Delegate Sub D()
Interface I
Sub M()
Property P As Object
Event E As D
End Interface
Class C
Implements I
Shared Sub M() Implements I.M
End Sub
Shared Property P As Object Implements I.P
Shared Event E() Implements I.E
End Class
]]></file>
</compilation>)
compilation1.AssertTheseDiagnostics(<errors><![CDATA[
BC30149: Class 'C' must implement 'Event E As D' for interface 'I'.
Implements I
~
BC30149: Class 'C' must implement 'Property P As Object' for interface 'I'.
Implements I
~
BC30149: Class 'C' must implement 'Sub M()' for interface 'I'.
Implements I
~
BC30505: Methods or events that implement interface members cannot be declared 'Shared'.
Shared Sub M() Implements I.M
~~~~~~
BC30505: Methods or events that implement interface members cannot be declared 'Shared'.
Shared Property P As Object Implements I.P
~~~~~~
BC30505: Methods or events that implement interface members cannot be declared 'Shared'.
Shared Event E() Implements I.E
~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30506ERR_NoWithEventsVarOnHandlesList()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoWithEventsVarOnHandlesList">
<file name="a.vb"><![CDATA[
Module mod30506
'COMPILEERROR: BC30506, "clsEventError1"
Sub scenario1() Handles clsEventError1.Event1
End Sub
'COMPILEERROR: BC30506, "I1"
Sub scenario2() Handles I1.goo
End Sub
'COMPILEERROR: BC30506, "button1"
Sub scenario3() Handles button1.click
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub scenario1() Handles clsEventError1.Event1
~~~~~~~~~~~~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub scenario2() Handles I1.goo
~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub scenario3() Handles button1.click
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub HandlesHiddenEvent()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoWithEventsVarOnHandlesList">
<file name="a.vb"><![CDATA[
Imports System
Class HasEvents
Event E1()
End Class
Class HasWithEvents
Public WithEvents WE0 As HasEvents
Public WithEvents WE1 As HasEvents
Public WithEvents WE2 As HasEvents
Public WithEvents _WE3 As HasEvents
End Class
Class HasWithEventsDerived
Inherits HasWithEvents
Overrides Property WE0() As HasEvents
Get
Return Nothing
End Get
Set(value As HasEvents)
End Set
End Property
Overloads Property WE1(x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Property WE2(x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Property WE3 As Integer
Shared Sub goo0() Handles WE0.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo1() Handles WE1.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo2() Handles WE2.E2
Console.WriteLine("handled2")
End Sub
Shared Sub goo3() Handles WE3.E3
Console.WriteLine("handled2")
End Sub
End Class
Class Program
Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30284: property 'WE0' cannot be declared 'Overrides' because it does not override a property in a base class.
Overrides Property WE0() As HasEvents
~~~
BC40004: property 'WE0' conflicts with WithEvents variable 'WE0' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Overrides Property WE0() As HasEvents
~~~
BC40004: property 'WE1' conflicts with WithEvents variable 'WE1' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Overloads Property WE1(x As Integer) As Integer
~~~
BC40004: property 'WE2' conflicts with WithEvents variable 'WE2' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Property WE2(x As Integer) As Integer
~~~
BC40012: property 'WE3' implicitly declares '_WE3', which conflicts with a member in the base class 'HasWithEvents', and so the property should be declared 'Shadows'.
Property WE3 As Integer
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo0() Handles WE0.E1
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo1() Handles WE1.E1
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo2() Handles WE2.E2
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Shared Sub goo3() Handles WE3.E3
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub HandlesProperty001()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="HandlesProperty001">
<file name="a.vb"><![CDATA[
Imports System
Imports System.ComponentModel
Namespace Project1
Module m1
Public Sub main()
Dim c = New Sink
Dim s = New OuterClass
c.x = s
s.Test()
End Sub
End Module
Class EventSource
Public Event MyEvent()
Sub test()
RaiseEvent MyEvent()
End Sub
End Class
Class SomeBase
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Public Property SomePropertyInBase() As EventSource
Get
Console.Write("#Get#")
Return Nothing
End Get
Set(value As EventSource)
End Set
End Property
End Class
Class OuterClass
Inherits SomeBase
Private Shared SubObject As New EventSource
<DesignOnly(True)>
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)>
Public Shared Property SomePropertyWrongValue() As EventSource
Get
Console.Write("#Get#")
Return SubObject
End Get
Set(value As EventSource)
End Set
End Property
Public Property SomePropertyNoAttribute() As EventSource
Get
Console.Write("#Get#")
Return SubObject
End Get
Set(value As EventSource)
End Set
End Property
Public Shared Property SomePropertyWriteOnly() As EventSource
Get
Console.Write("#Get#")
Return SubObject
End Get
Set(value As EventSource)
End Set
End Property
Sub Test()
SubObject.test()
End Sub
End Class
Class Sink
Public WithEvents x As OuterClass
Sub goo1() Handles x.SomePropertyWrongValue.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub goo2() Handles x.SomePropertyNoAttribute.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub goo3() Handles x.SomePropertyWriteonly.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub goo4() Handles x.SomePropertyInBase.MyEvent
Console.Write("Handled Event On SubObject!")
End Sub
Sub test()
x.Test()
End Sub
Sub New()
x = New OuterClass
End Sub
End Class
'.....
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo1() Handles x.SomePropertyWrongValue.MyEvent
~~~~~~~~~~~~~~~~~~~~~~~~
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo2() Handles x.SomePropertyNoAttribute.MyEvent
~~~~~~~~~~~~~~~~~~~~~~~~~
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo3() Handles x.SomePropertyWriteonly.MyEvent
~~~~~~~~~~~~~~~~~~~~~~~
BC31412: 'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.
Sub goo4() Handles x.SomePropertyInBase.MyEvent
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub WithEventsHides()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="WithEventsHides">
<file name="a.vb"><![CDATA[
Imports System
Class HasEvents
Event E1()
End Class
Class HasWithEvents
Public WithEvents WE0 As HasEvents
Public WithEvents WE1 As HasEvents
Public Property WE2 As HasEvents
Public Property WE3 As HasEvents
End Class
Class HasWithEventsDerived
Inherits HasWithEvents
Public WithEvents WE0 As HasEvents
' no warnings
Public Shadows WithEvents WE1 As HasEvents
Public WithEvents WE2 As HasEvents
' no warnings
Public Shadows WithEvents WE3 As HasEvents
Shared Sub goo0() Handles WE0.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo1() Handles WE1.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo2() Handles WE2.E1
Console.WriteLine("handled2")
End Sub
Shared Sub goo3() Handles WE3.E1
Console.WriteLine("handled2")
End Sub
End Class
Class Program
Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40004: WithEvents variable 'WE0' conflicts with WithEvents variable 'WE0' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Public WithEvents WE0 As HasEvents
~~~
BC40004: WithEvents variable 'WE2' conflicts with property 'WE2' in the base class 'HasWithEvents' and should be declared 'Shadows'.
Public WithEvents WE2 As HasEvents
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub WithEventsOverloads()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="WithEventsOverloads">
<file name="a.vb"><![CDATA[
Imports System
Class HasEvents
Event E1()
End Class
Class HasWithEventsDerived
Public WithEvents _WE1 As HasEvents
Public Property WE0(x As Integer) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Public Overloads Property WE2(x As Integer, y As Long) As Integer
Get
Return 1
End Get
Set(value As Integer)
End Set
End Property
Public WithEvents WE0 As HasEvents
Public Property WE1
Public WithEvents WE2 As HasEvents
End Class
Class Program
Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: WithEvents variable '_WE1' conflicts with a member implicitly declared for property 'WE1' in class 'HasWithEventsDerived'.
Public WithEvents _WE1 As HasEvents
~~~~
BC30260: 'WE0' is already declared as 'Public Property WE0(x As Integer) As Integer' in this class.
Public WithEvents WE0 As HasEvents
~~~
BC30260: 'WE2' is already declared as 'Public Overloads Property WE2(x As Integer, y As Long) As Integer' in this class.
Public WithEvents WE2 As HasEvents
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30508ERR_AccessMismatch6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Class A
Protected Class C
End Class
Protected Structure S
End Structure
Private Interface I
End Interface
Public F As I
Friend Function M() As C
Return Nothing
End Function
End Class
Public Class B
Inherits A
Public G As C
Friend ReadOnly H As S
Public Function N(x As C) As S
Return Nothing
End Function
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'F' cannot expose type 'A.I' in namespace 'N' through class 'A'.
Public F As I
~
BC30508: 'M' cannot expose type 'A.C' in namespace 'N' through class 'A'.
Friend Function M() As C
~
BC30508: 'G' cannot expose type 'A.C' in namespace 'N' through class 'B'.
Public G As C
~
BC30508: 'H' cannot expose type 'A.S' in namespace 'N' through class 'B'.
Friend ReadOnly H As S
~
BC30508: 'x' cannot expose type 'A.C' in namespace 'N' through class 'B'.
Public Function N(x As C) As S
~
BC30508: 'N' cannot expose type 'A.S' in namespace 'N' through class 'B'.
Public Function N(x As C) As S
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30508ERR_AccessMismatch6_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace NS30508
Interface i1
End Interface
Interface i2
End Interface
Class C1(Of v)
Implements i1
End Class
Class c2
Implements i1
Implements i2
'COMPILEERROR: BC30508, "ProtectedClass"
Function fiveB(Of t As ProtectedClass)() As String
Return "In fiveB"
End Function
'COMPILEERROR: BC30508, "Privateclass"
Function fiveC(Of t As Privateclass)() As String
Return "In fiveC"
End Function
Protected Function fiveD(Of t As ProtectedClass)() As String
Return "In fiveB"
End Function
Private Function fiveE(Of t As Privateclass)() As String
Return "In fiveC"
End Function
Protected Class ProtectedClass
End Class
Private Class Privateclass
End Class
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'fiveB' cannot expose type 'c2.ProtectedClass' in namespace 'NS30508' through class 'c2'.
Function fiveB(Of t As ProtectedClass)() As String
~~~~~~~~~~~~~~
BC30508: 'fiveC' cannot expose type 'c2.Privateclass' in namespace 'NS30508' through class 'c2'.
Function fiveC(Of t As Privateclass)() As String
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30508ERR_AccessMismatch6_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Class A
Protected Class C
End Class
Protected Structure S
End Structure
Private Interface I
End Interface
Protected Enum E
A
End Enum
Property P As I
End Class
Public Class B
Inherits A
Property Q As C
Friend ReadOnly Property R(x As E) As S
Get
Return Nothing
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'P' cannot expose type 'A.I' in namespace 'N' through class 'A'.
Property P As I
~
BC30508: 'Q' cannot expose type 'A.C' in namespace 'N' through class 'B'.
Property Q As C
~
BC30508: 'x' cannot expose type 'A.E' in namespace 'N' through class 'B'.
Friend ReadOnly Property R(x As E) As S
~
BC30508: 'R' cannot expose type 'A.S' in namespace 'N' through class 'B'.
Friend ReadOnly Property R(x As E) As S
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528153")>
<Fact()>
Public Sub BC30508ERR_AccessMismatch6_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Class A
Protected Class B
End Class
Public Class C
Function F() As B
Return Nothing
End Function
Public Class D
Sub M(o As B)
End Sub
End Class
End Class
End Class
Public Class E
Inherits A
Function F() As B
Return Nothing
End Function
End Class
End Namespace
Public Class F
Inherits N.A
Sub M(o As B)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30508: 'F' cannot expose type 'A.B' in namespace 'N' through class 'C'.
Function F() As B
~
BC30508: 'o' cannot expose type 'A.B' in namespace 'N' through class 'D'.
Sub M(o As B)
~
BC30508: 'F' cannot expose type 'A.B' in namespace 'N' through class 'E'.
Function F() As B
~
BC30508: 'o' cannot expose type 'A.B' in namespace '<Default>' through class 'F'.
Sub M(o As B)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30509ERR_InheritanceAccessMismatch5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InheritanceAccessMismatch5">
<file name="a.vb"><![CDATA[
Module Module1
Private Class C1
End Class
Class C2
Inherits C1
End Class
Class C3
Protected Class C4
End Class
Class C5
Inherits C4
End Class
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30509: 'C2' cannot inherit from class 'Module1.C1' because it expands the access of the base class to namespace '<Default>'.
Inherits C1
~~
BC30509: 'C5' cannot inherit from class 'Module1.C3.C4' because it expands the access of the base class to namespace '<Default>'.
Inherits C4
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30529ERR_ParamTypingInconsistency()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamTypingInconsistency">
<file name="a.vb"><![CDATA[
class M1
Sub Goo(ByVal [a], ByRef [continue], ByVal c As Single)
End Sub
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Sub Goo(ByVal [a], ByRef [continue], ByVal c As Single)
~~~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Sub Goo(ByVal [a], ByRef [continue], ByVal c As Single)
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30530ERR_ParamNameFunctionNameCollision_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
class M1
Function Goo(Of Goo)(ByVal Goo As Goo)
End Function
End class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32090: Type parameter cannot have the same name as its defining function.
Function Goo(Of Goo)(ByVal Goo As Goo)
~~~
BC30530: Parameter cannot have the same name as its defining function.
Function Goo(Of Goo)(ByVal Goo As Goo)
~~~
BC32089: 'Goo' is already declared as a type parameter of this method.
Function Goo(Of Goo)(ByVal Goo As Goo)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30530ERR_ParamNameFunctionNameCollision_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P(p, q)
Set(value)
End Set
End Property
Private _q
WriteOnly Property Q
Set(Q) ' No error
_q = Q
End Set
End Property
Property R
Get
Return Nothing
End Get
Set(get_R) ' No error
End Set
End Property
WriteOnly Property S
Set(set_S) ' No error
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30530: Parameter cannot have the same name as its defining function.
WriteOnly Property P(p, q)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540629")>
<Fact>
Public Sub BC30548ERR_InvalidAssemblyAttribute1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidAssemblyAttribute1">
<file name="a.vb"><![CDATA[
Imports System
'COMPILEERROR: BC30548, "Assembly: c1()"
<Assembly: c1()>
'COMPILEERROR: BC30549, "Module: c1()"
<Module: c1()>
<AttributeUsageAttribute(AttributeTargets.Class, Inherited:=False)>
NotInheritable Class c1Attribute
Inherits Attribute
End Class
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_InvalidAssemblyAttribute1, "c1").WithArguments("c1Attribute"),
Diagnostic(ERRID.ERR_InvalidModuleAttribute1, "c1").WithArguments("c1Attribute"))
End Sub
<WorkItem(540629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540629")>
<Fact>
Public Sub BC30549ERR_InvalidModuleAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidModuleAttribute1">
<file name="a.vb"><![CDATA[
Imports System
<Module: InternalsVisibleTo()>
<AttributeUsageAttribute(AttributeTargets.Delegate)>
Class InternalsVisibleTo
Inherits Attribute
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidModuleAttribute1, "InternalsVisibleTo").WithArguments("InternalsVisibleTo"))
End Sub
<Fact>
Public Sub BC30561ERR_AmbiguousInImports2()
Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"N1", "N2"}))
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousInImports2">
<file name="a.vb"><![CDATA[
Public Class Cls2
Implements i1
End Class
]]></file>
<file name="b.vb"><![CDATA[
Namespace N1
Interface I1
End Interface
End Namespace
Namespace N2
Interface I1
End Interface
End Namespace
]]></file>
</compilation>, options:=options)
Dim expectedErrors1 = <errors><![CDATA[
BC30561: 'I1' is ambiguous, imported from the namespaces or types 'N1, N2'.
Implements i1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30562ERR_AmbiguousInModules2()
Dim options = TestOptions.ReleaseExe.WithGlobalImports(GlobalImport.Parse({"N1", "N2"}))
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AmbiguousInModules2">
<file name="a.vb"><![CDATA[
Public Class Cls2
Implements i1
End Class
]]></file>
<file name="b.vb"><![CDATA[
Module N1
Interface I1
End Interface
End Module
Module N2
Interface I1
End Interface
End Module
]]></file>
</compilation>, options)
Dim expectedErrors1 = <errors><![CDATA[
BC30562: 'I1' is ambiguous between declarations in Modules 'N1, N2'.
Implements i1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30572ERR_DuplicateNamedImportAlias1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BC30572ERR_DuplicateNamedImportAlias1">
<file name="a.vb"><![CDATA[
Imports Alias1 = N1.C1(of String)
Imports Alias1 = N1.C1(of String)
]]></file>
<file name="b.vb"><![CDATA[
Module N1
Class C1(of T)
End class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30572: Alias 'Alias1' is already declared.
Imports Alias1 = N1.C1(of String)
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30573ERR_DuplicatePrefix()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Xml.Linq
Imports <xmlns="default1">
Imports <xmlns="default2">
Imports <xmlns:p="p1">
Imports <xmlns:q="q">
Imports <xmlns:p="p2">
Class C
Private F As XElement = <p:a xmlns:p="p3" xmlns:q="q"/>
End Class
]]></file>
</compilation>, references:=XmlReferences)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30573: XML namespace prefix '' is already declared.
Imports <xmlns="default2">
~~~~~~~~~~~~~~~~~~
BC30573: XML namespace prefix 'p' is already declared.
Imports <xmlns:p="p2">
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30573ERR_DuplicatePrefix_1()
Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"<xmlns=""default1"">", "<xmlns=""default2"">", "<xmlns:p=""p1"">", "<xmlns:q=""q"">", "<xmlns:p=""p2"">"}))
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="c.vb"><![CDATA[
Imports <xmlns="default">
Imports <xmlns:p="p">
Imports <xmlns:q="q">
Class C
End Class
]]></file>
</compilation>, references:=XmlReferences, options:=options)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30573: Error in project-level import '<xmlns:p="p2">' at '<xmlns:p="p2">' : XML namespace prefix 'p' is already declared.
BC30573: Error in project-level import '<xmlns="default2">' at '<xmlns="default2">' : XML namespace prefix '' is already declared.
]]></errors>)
Dim embedded = compilation.GetTypeByMetadataName("Microsoft.VisualBasic.Embedded")
Assert.IsType(Of EmbeddedSymbolManager.EmbeddedNamedTypeSymbol)(embedded)
Assert.False(DirectCast(embedded, INamedTypeSymbol).IsSerializable)
End Sub
<Fact>
Public Sub BC30583ERR_MethodAlreadyImplemented2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MethodAlreadyImplemented2">
<file name="a.vb"><![CDATA[
Namespace NS1
Interface i1
Sub goo()
End Interface
Interface i2
Inherits i1
End Interface
Interface i3
Inherits i1
End Interface
Class cls1
Implements i2, i3
Sub i2goo() Implements i2.goo
Console.WriteLine("in i1, goo")
End Sub
'COMPILEERROR: BC30583, "i3.goo"
Sub i3goo() Implements i3.goo
Console.WriteLine("in i3, goo")
End Sub
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30583: 'i1.goo' cannot be implemented more than once.
Sub i3goo() Implements i3.goo
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30584ERR_DuplicateInInherits1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateInInherits1">
<file name="a.vb"><![CDATA[
Interface sce(Of T)
End Interface
Interface sce1
Inherits sce(Of Integer)
Inherits sce(Of Integer)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30584: 'sce(Of Integer)' cannot be inherited more than once.
Inherits sce(Of Integer)
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30584ERR_DuplicateInInherits1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateInInherits1">
<file name="a.vb"><![CDATA[
interface I1
End interface
Structure s1
Interface sce1
Inherits I1
Inherits I1
End Interface
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30584: 'I1' cannot be inherited more than once.
Inherits I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30590ERR_EventNotFound1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="EventNotFound1">
<file name="a.vb"><![CDATA[
Friend Module mod30590
Class cls1
Event Ev2()
End Class
Class cls2 : Inherits cls1
Public WithEvents o As cls2
Private Shadows Sub Ev2()
End Sub
'COMPILEERROR: BC30590, "Ev2"
Private Sub o_Ev2() Handles o.Ev2
End Sub
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30590: Event 'Ev2' cannot be found.
Private Sub o_Ev2() Handles o.Ev2
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30593ERR_ModuleCantUseVariableSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseVariableSpecifier1">
<file name="a.vb"><![CDATA[
Class class1
End Class
Structure struct1
End Structure
Friend Module ObjInit14mod
'COMPILEERROR: BC30593, "Shared"
Shared cls As New class1()
'COMPILEERROR: BC30593, "Shared"
Shared xint As New Integer()
'COMPILEERROR: BC30593, "Shared"
Shared xdec As New Decimal(40@)
'COMPILEERROR: BC30593, "Shared"
Shared xstrct As New struct1()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared cls As New class1()
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared xint As New Integer()
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared xdec As New Decimal(40@)
~~~~~~
BC30593: Variables in Modules cannot be declared 'Shared'.
Shared xstrct As New struct1()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30594ERR_SharedEventNeedsSharedHandler()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SharedEventNeedsSharedHandler">
<file name="a.vb"><![CDATA[
Module M1
Class myCls
Event Event1()
End Class
Class myClass1
Shared WithEvents x As myCls
Public Sub EventHandler() Handles x.Event1
End Sub
Private Sub EventHandler1() Handles x.Event1
End Sub
Protected Sub EventHandler2() Handles x.Event1
End Sub
Friend Sub EventHandler3() Handles x.Event1
End Sub
End Class
Class myClass2
Shared WithEvents x As myCls
Overridable Sub EventHandler() Handles x.Event1
End Sub
End Class
MustInherit Class myClass3
Shared WithEvents x As myCls
MustOverride Sub EventHandler() Handles x.Event1
End Class
Class myClass4
Overridable Sub EventHandler()
End Sub
End Class
Class myClass7
Inherits myClass4
Shared WithEvents x As myCls
NotOverridable Overrides Sub EventHandler() Handles x.Event1
End Sub
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Public Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
Public Sub EventHandler() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Private Sub EventHandler1() Handles x.Event1
~
BC31029: Method 'EventHandler1' cannot handle event 'Event1' because they do not have a compatible signature.
Private Sub EventHandler1() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Protected Sub EventHandler2() Handles x.Event1
~
BC31029: Method 'EventHandler2' cannot handle event 'Event1' because they do not have a compatible signature.
Protected Sub EventHandler2() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Friend Sub EventHandler3() Handles x.Event1
~
BC31029: Method 'EventHandler3' cannot handle event 'Event1' because they do not have a compatible signature.
Friend Sub EventHandler3() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Overridable Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
Overridable Sub EventHandler() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
MustOverride Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
MustOverride Sub EventHandler() Handles x.Event1
~~~~~~
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
NotOverridable Overrides Sub EventHandler() Handles x.Event1
~
BC31029: Method 'EventHandler' cannot handle event 'Event1' because they do not have a compatible signature.
NotOverridable Overrides Sub EventHandler() Handles x.Event1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
CompilationUtils.AssertTheseEmitDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30927ERR_MustOverOnNotInheritPartClsMem1_1()
CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class Test
NotInheritable Class C
End Class
Partial Class C
'COMPILEERROR: BC30927, "goo"
MustOverride Function goo() As Integer
End Class
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MustOverOnNotInheritPartClsMem1, "MustOverride").WithArguments("MustOverride"))
End Sub
<Fact>
Public Sub NotInheritableInOtherPartial()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class B
Overridable Sub f()
End Sub
Overridable Property p As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
NotInheritable Class C
Inherits B
End Class
Partial Class C
MustOverride Sub f1()
MustOverride Property p1 As Integer
Overridable Sub f2()
End Sub
Overridable Property p2 As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
NotOverridable Overrides Sub f()
End Sub
NotOverridable Overrides Property p As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30927: 'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.
MustOverride Sub f1()
~~~~~~~~~~~~
BC30927: 'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.
MustOverride Property p1 As Integer
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30607ERR_BadFlagsInNotInheritableClass1_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
MustOverride Sub O()
MustOverride Property R
End Class
NotInheritable Class B
Inherits A
Overridable Sub M()
End Sub
MustOverride Sub N()
NotOverridable Overrides Sub O()
End Sub
Overridable Property P
MustOverride Property Q
NotOverridable Overrides Property R
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Sub M()
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Sub N()
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Overrides Sub O()
~~~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Property P
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Property Q
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Overrides Property R
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<WorkItem(540594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540594")>
<Fact>
Public Sub BC30610ERR_BaseOnlyClassesMustBeExplicit2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseOnlyClassesMustBeExplicit2">
<file name="a.vb"><![CDATA[
MustInherit Class Cls1
MustOverride Sub Goo(ByVal Arg As Integer)
MustOverride Sub Goo(ByVal Arg As Double)
End Class
'COMPILEERROR: BC30610, "cls2"
Class cls2
Inherits Cls1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30610: Class 'cls2' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
Cls1: Public MustOverride Sub Goo(Arg As Integer)
Cls1: Public MustOverride Sub Goo(Arg As Double).
Class cls2
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(541026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541026")>
<Fact()>
Public Sub BC30610ERR_BaseOnlyClassesMustBeExplicit2WithBC31411()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseOnlyClassesMustBeExplicit2">
<file name="a.vb"><![CDATA[
MustInherit Class Cls1
MustOverride Sub Goo(ByVal Arg As Integer)
MustOverride Sub Goo(ByVal Arg As Double)
End Class
'COMPILEERROR: BC30610, "cls2"
Class cls2
Inherits Cls1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30610: Class 'cls2' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
Cls1: Public MustOverride Sub Goo(Arg As Integer)
Cls1: Public MustOverride Sub Goo(Arg As Double).
Class cls2
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30628ERR_StructCantInherit()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructCantInherit">
<file name="a.vb"><![CDATA[
Structure S1
Structure S2
Inherits s1
End Structure
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30628: Structures cannot have 'Inherits' statements.
Inherits s1
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30629ERR_NewInStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NewInStruct">
<file name="a.vb"><![CDATA[
Module mod30629
Structure Struct1
'COMPILEERROR:BC30629,"new"
Public Sub New()
End Sub
End Structure
End Module
]]></file>
</compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic12))
Dim expectedErrors1 = <errors><![CDATA[
BC30629: Structures cannot declare a non-shared 'Sub New' with no parameters.
Public Sub New()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC37240ERR_StructParameterlessInstanceCtorMustBePublic()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NewInStruct">
<file name="a.vb"><![CDATA[
Module mod37240
Structure Struct1
'COMPILEERROR:BC37240,"new"
Private Sub New()
End Sub
End Structure
sub Main
end sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30629: Structures cannot declare a non-shared 'Sub New' with no parameters.
Private Sub New()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30639ERR_BadPropertyFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyFlags1">
<file name="a.vb"><![CDATA[
Interface I
NotInheritable Property P
MustInherit ReadOnly Property Q
WriteOnly Const Property R(o)
Partial Property S
End Interface
Class C
NotInheritable Property T
MustInherit ReadOnly Property U
Get
Return Nothing
End Get
End Property
WriteOnly Const Property V(o)
Set(value)
End Set
End Property
Partial Property W
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30639: Properties cannot be declared 'NotInheritable'.
NotInheritable Property P
~~~~~~~~~~~~~~
BC30639: Properties cannot be declared 'MustInherit'.
MustInherit ReadOnly Property Q
~~~~~~~~~~~
BC30639: Properties cannot be declared 'Const'.
WriteOnly Const Property R(o)
~~~~~
BC30639: Properties cannot be declared 'Partial'.
Partial Property S
~~~~~~~
BC30639: Properties cannot be declared 'NotInheritable'.
NotInheritable Property T
~~~~~~~~~~~~~~
BC30639: Properties cannot be declared 'MustInherit'.
MustInherit ReadOnly Property U
~~~~~~~~~~~
BC30639: Properties cannot be declared 'Const'.
WriteOnly Const Property V(o)
~~~~~
BC30639: Properties cannot be declared 'Partial'.
Partial Property W
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30645ERR_InvalidOptionalParameterUsage1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidOptionalParameterUsage1">
<file name="a.vb"><![CDATA[
Module M1
<System.Web.Services.WebMethod(True)>
Public Function HelloWorld(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(Net451.SystemWebServices)
Dim expectedErrors1 = <errors><![CDATA[
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld(Optional ByVal n As String = "e") As String
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30645ERR_InvalidOptionalParameterUsage1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidOptionalParameterUsage1a">
<file name="a.vb"><![CDATA[
Module M1
<System.Web.Services.WebMethod(True)>
<System.Web.Services.WebMethod(False)>
Public Function HelloWorld(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(Net451.SystemWebServices)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30663: Attribute 'WebMethodAttribute' cannot be applied multiple times.
<System.Web.Services.WebMethod(False)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld(Optional ByVal n As String = "e") As String
~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30645ERR_InvalidOptionalParameterUsage1b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidOptionalParameterUsage1b">
<file name="a.vb"><![CDATA[
Module M1
<System.Web.Services.WebMethod()>
Public Function HelloWorld1(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled)>
Public Function HelloWorld2(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1)>
Public Function HelloWorld3(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1, True)>
Public Function HelloWorld4(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1, True, 123)>
Public Function HelloWorld5(Optional ByVal n As String = "e") As String
Return "Hello World"
End Function
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(Net451.SystemWebServices,
Net451.SystemEnterpriseServices)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<errors><![CDATA[
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld1(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld2(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld3(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30645: Attribute 'WebMethod' cannot be applied to a method with optional parameters.
Public Function HelloWorld4(Optional ByVal n As String = "e") As String
~~~~~~~~~~~
BC30516: Overload resolution failed because no accessible 'New' accepts this number of arguments.
<System.Web.Services.WebMethod(True, System.EnterpriseServices.TransactionOption.Disabled, 1, True, 123)>
~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC30650ERR_InvalidEnumBase()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidEnumBase">
<file name="a.vb"><![CDATA[
Module ICase1mod
Enum color1 As Double
blue
End Enum
Enum color2 As String
blue
End Enum
Enum color3 As Single
blue
End Enum
Enum color4 As Date
blue
End Enum
Enum color5 As Object
blue
End Enum
Enum color6 As Boolean
blue
End Enum
Enum color7 As Decimal
blue
End Enum
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30650: Enums must be declared as an integral type.
Enum color1 As Double
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color2 As String
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color3 As Single
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color4 As Date
~~~~
BC30650: Enums must be declared as an integral type.
Enum color5 As Object
~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color6 As Boolean
~~~~~~~
BC30650: Enums must be declared as an integral type.
Enum color7 As Decimal
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30651ERR_ByRefIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ByRefIllegal1">
<file name="a.vb"><![CDATA[
Class C
Property P(ByVal x, ByRef y)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
ReadOnly Property Q(ParamArray p())
Get
Return Nothing
End Get
End Property
WriteOnly Property R(Optional x = Nothing)
Set(value)
End Set
End Property
End Class
Interface I
ReadOnly Property P(ByRef x, Optional ByVal y = Nothing)
WriteOnly Property Q(ParamArray p())
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30651: property parameters cannot be declared 'ByRef'.
Property P(ByVal x, ByRef y)
~~~~~
BC30651: property parameters cannot be declared 'ByRef'.
ReadOnly Property P(ByRef x, Optional ByVal y = Nothing)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30652ERR_UnreferencedAssembly3()
Dim Lib1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Lib1">
<file name="a.vb"><![CDATA[
Public Class C1
End Class
]]></file>
</compilation>)
Dim Lib2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Lib2">
<file name="a.vb"><![CDATA[
Public Class C2
Dim s as C1
End Class
]]></file>
</compilation>)
Dim ref1 = New VisualBasicCompilationReference(Lib1)
Lib2 = Lib2.AddReferences(ref1)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UnreferencedAssembly3">
<file name="a.vb"><![CDATA[
Public Class C
Dim s as C1
End Class
]]></file>
</compilation>)
Dim ref2 = New VisualBasicCompilationReference(Lib2)
compilation1 = compilation1.AddReferences(ref2)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'C1' is not defined.
Dim s as C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538153")>
<Fact>
Public Sub BC30656ERR_UnsupportedField1()
Dim csharpComp = CSharp.CSharpCompilation.Create("Test", options:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim text = "public class A { public static volatile int X; }"
Dim ref = Net40.mscorlib
csharpComp = csharpComp.AddSyntaxTrees(CSharp.SyntaxFactory.ParseSyntaxTree(text))
csharpComp = csharpComp.AddReferences(ref)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnsupportedField1">
<file name="a.vb"><![CDATA[
Module M
Dim X = A.X
End Module
]]></file>
</compilation>)
compilation1 = compilation1.AddReferences(MetadataReference.CreateFromImage(csharpComp.EmitToArray()))
Dim expectedErrors1 = <errors><![CDATA[
BC30656: Field 'X' is of an unsupported type.
Dim X = A.X
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30660ERR_LocalsCannotHaveAttributes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="LocalsCannotHaveAttributes">
<file name="at30660.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(p As ULong)
End Sub
End Class
Public Class Goo
Public Function SSS() As Byte
<My(12345)> Dim x As Byte = 1
Return x
End Function
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_LocalsCannotHaveAttributes, "<My(12345)>"))
End Sub
<Fact>
Public Sub BC30662ERR_InvalidAttributeUsage2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidAttributeUsage2">
<file name="a.vb"><![CDATA[
Imports System
Namespace DecAttr
<AttributeUsageAttribute(AttributeTargets.Property)> Class attr1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Event)> Class attr2
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Delegate)> Class attr3
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Constructor)> Class attr4
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Field)> Class attr5
Inherits Attribute
End Class
Class scen1
<attr1()> Public Declare Function Beep1 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr2()> Public Declare Function Beep2 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr3()> Public Declare Function Beep3 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr4()> Public Declare Function Beep4 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
<attr5()> Public Declare Function Beep5 Lib "kernel32" Alias "Beep" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
End Class
End Namespace
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr1").WithArguments("attr1", "Beep1"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr2").WithArguments("attr2", "Beep2"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr3").WithArguments("attr3", "Beep3"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr4").WithArguments("attr4", "Beep4"),
Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "attr5").WithArguments("attr5", "Beep5"))
End Sub
<WorkItem(538370, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538370")>
<Fact>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly:clscompliant(true), Assembly:clscompliant(true), Assembly:clscompliant(true)>
<Module:clscompliant(true), Module:clscompliant(true), Module:clscompliant(true)>
Namespace DecAttr
<AttributeUsageAttribute(AttributeTargets.Property)>
Class attrProperty
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Parameter)>
Class attrParameter
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.ReturnValue)>
Class attrReturnType
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Class)>
Class attrClass
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Struct)>
Class attrStruct
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Method)>
Class attrMethod
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Field)>
Class attrField
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Enum)>
Class attrEnum
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Constructor)>
Class attrCtor
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Delegate)>
Class attrDelegate
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Interface)>
Class attrInterface
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Assembly)>
Class attrAssembly
Inherits Attribute
End Class
<AttributeUsageAttribute(AttributeTargets.Module)>
Class attrModule
Inherits Attribute
End Class
<attrClass(), attrClass(), attrClass()>
Module M1
End Module
<attrInterface(), attrInterface(), attrInterface()>
Interface I
End Interface
<attrEnum(), attrEnum(), attrEnum()>
Enum E
member
End Enum
<attrDelegate(), attrDelegate(), attrDelegate()>
Delegate Sub Del()
<attrClass(), attrClass()>
<attrClass()>
Class scen1(Of T1)
<attrCtor(), attrCtor(), attrCtor()>
Public Sub New()
End Sub
<attrField(), attrField(), attrField()>
Public field as Integer
Private newPropertyValue As String
<attrProperty()> ' first ok
<attrProperty()> ' first error
<attrProperty()> ' second error
Public Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
<attrMethod(), attrMethod(), attrMethod()>
Public function Sub1(Of T)(
<attrParameter(), attrParameter(), attrParameter()> a as Integer,
b as T) as <attrReturnType(), attrReturnType(), attrReturnType()> Integer
return 23
End function
End Class
<attrStruct()>
<attrStruct(), attrStruct()>
Structure S1
End Structure
End Namespace
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Assembly:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Assembly:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Module:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "Module:clscompliant(true)").WithArguments("CLSCompliantAttribute"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrDelegate()").WithArguments("attrDelegate"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrDelegate()").WithArguments("attrDelegate"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrEnum()").WithArguments("attrEnum"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrEnum()").WithArguments("attrEnum"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrInterface()").WithArguments("attrInterface"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrInterface()").WithArguments("attrInterface"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrStruct()").WithArguments("attrStruct"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrStruct()").WithArguments("attrStruct"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrParameter()").WithArguments("attrParameter"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrParameter()").WithArguments("attrParameter"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrClass()").WithArguments("attrClass"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrCtor()").WithArguments("attrCtor"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrCtor()").WithArguments("attrCtor"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrField()").WithArguments("attrField"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrField()").WithArguments("attrField"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrProperty()").WithArguments("attrProperty"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrProperty()").WithArguments("attrProperty"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrReturnType()").WithArguments("attrReturnType"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrReturnType()").WithArguments("attrReturnType"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrMethod()").WithArguments("attrMethod"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "attrMethod()").WithArguments("attrMethod"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1a">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
<A1(), A2()>
Partial Private Sub M(i As Integer)
End Sub
End Class
Partial Class C1
<A1(), A2()>
Private Sub M(i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1b">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
<A2(), A1(), A2()>
Partial Private Sub M(i As Integer)
End Sub
End Class
Partial Class C1
<A1(), A1(), A2()>
Private Sub M(i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1c()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1c">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
Partial Private Sub M(<A1(), A2()>i As Integer)
End Sub
End Class
Partial Class C1
Private Sub M(<A1(), A2()>i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact()>
Public Sub BC30663ERR_InvalidMultipleAttributeUsage1d()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidMultipleAttributeUsage1d">
<file name="a.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All, AllowMultiple:=False)>
Class A1
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class A2
Inherits Attribute
End Class
Partial Class C1
Partial Private Sub M(<A2(), A1(), A2()>i As Integer)
End Sub
End Class
Partial Class C1
Private Sub M(<A1(), A1(), A2()>i As Integer)
Dim s As New C1
s.M(i)
End Sub
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"),
Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsage1, "A1()").WithArguments("A1"))
End Sub
<Fact>
Public Sub BC30668ERR_UseOfObsoleteSymbol2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UseOfObsoleteSymbol2">
<file name="a.vb"><![CDATA[
Imports System
Namespace NS
Class clstest
<Obsolete("Scenario6 Message", True)> Protected Friend WriteOnly Property scenario6()
Set(ByVal Value)
End Set
End Property
<Obsolete("", True)> Public Shared WriteOnly Property scenario7()
Set(ByVal Value)
End Set
End Property
<Obsolete()> Default Property scenario8(ByVal i As Integer) As Integer
Get
Return 1
End Get
Set(ByVal Value As Integer)
End Set
End Property
End Class
Class clsTest1
<Obsolete("", True)> Default Public ReadOnly Property scenario9(ByVal i As Long) As Long
Get
Return 1
End Get
End Property
End Class
Friend Module OBS022mod
<Obsolete("Scenario1 Message", True)> WriteOnly Property Scenario1a()
Set(ByVal Value)
End Set
End Property
<Obsolete("Scenario2 Message", True)> ReadOnly Property scenario2()
Get
Return 1
End Get
End Property
Sub OBS022()
Dim obj As Object = 23%
Dim cls1 As New clstest()
'COMPILEERROR: BC30668, "Scenario1a"
Scenario1a = obj
'COMPILEERROR: BC30668, "scenario2"
obj = scenario2
'COMPILEERROR: BC30668, "cls1.scenario6"
cls1.scenario6 = obj
'COMPILEERROR: BC30668, "clstest.scenario7"
clstest.scenario7 = obj
Dim cls2 As New clsTest1()
'COMPILEERROR: BC30668, "cls2"
obj = cls2(4)
End Sub
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30668: 'Public WriteOnly Property Scenario1a As Object' is obsolete: 'Scenario1 Message'.
Scenario1a = obj
~~~~~~~~~~
BC30668: 'Public ReadOnly Property scenario2 As Object' is obsolete: 'Scenario2 Message'.
obj = scenario2
~~~~~~~~~
BC30668: 'Protected Friend WriteOnly Property scenario6 As Object' is obsolete: 'Scenario6 Message'.
cls1.scenario6 = obj
~~~~~~~~~~~~~~
BC31075: 'Public Shared WriteOnly Property scenario7 As Object' is obsolete.
clstest.scenario7 = obj
~~~~~~~~~~~~~~~~~
BC31075: 'Public ReadOnly Default Property scenario9(i As Long) As Long' is obsolete.
obj = cls2(4)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538173")>
<Fact>
Public Sub BC30683ERR_InheritsStmtWrongOrder()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsStmtWrongOrder">
<file name="a.vb"><![CDATA[
Class cn1
Public ss As Long
'COMPILEERROR: BC30683, "Inherits c2"
Inherits c2
End Class
Class c2
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30683: 'Inherits' statement must precede all declarations in a class.
Inherits c2
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseParseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30688ERR_InterfaceEventCantUse1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceEventCantUse1">
<file name="a.vb"><![CDATA[
Interface I
Event Goo() Implements I.Goo
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30688: Events in interfaces cannot be declared 'Implements'.
Event Goo() Implements I.Goo
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30695ERR_MustShadow2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustShadow2">
<file name="a.vb"><![CDATA[
Class c1
'COMPILEERROR: BC30695, "goo",
Sub goo()
End Sub
Shadows Function goo(ByVal i As Integer) As Integer
End Function
End Class
Class c2_1
Public goo As Integer
End Class
Class c2_2
Inherits c2_1
Shadows Sub goo()
End Sub
'COMPILEERROR: BC30695,"goo"
Sub goo(ByVal c As Char)
End Sub
'COMPILEERROR: BC30695,"goo"
Sub goo(ByVal d As Double)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30695: sub 'goo' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Sub goo()
~~~
BC30695: sub 'goo' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Sub goo(ByVal c As Char)
~~~
BC40004: sub 'goo' conflicts with variable 'goo' in the base class 'c2_1' and should be declared 'Shadows'.
Sub goo(ByVal c As Char)
~~~
BC30695: sub 'goo' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Sub goo(ByVal d As Double)
~~~
BC40004: sub 'goo' conflicts with variable 'goo' in the base class 'c2_1' and should be declared 'Shadows'.
Sub goo(ByVal d As Double)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30695ERR_MustShadow2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class Base
Sub Method(x As Integer)
End Sub
Overloads Sub Method(x As String)
End Sub
End Class
Partial Class Derived1
Inherits Base
Shadows Sub Method(x As String)
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Class Derived1
Inherits Base
Overrides Sub Method(x As Integer)
End Sub
End Class
Class Derived2
Inherits Base
Function Method(x As String, y As Integer) As String
End Function
Overrides Sub Method(x As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: sub 'Method' must be declared 'Overloads' because another 'Method' is declared 'Overloads' or 'Overrides'.
Sub Method(x As Integer)
~~~~~~
BC30695: sub 'Method' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Overrides Sub Method(x As Integer)
~~~~~~
BC31086: 'Public Overrides Sub Method(x As Integer)' cannot override 'Public Sub Method(x As Integer)' because it is not declared 'Overridable'.
Overrides Sub Method(x As Integer)
~~~~~~
BC31409: function 'Method' must be declared 'Overloads' because another 'Method' is declared 'Overloads' or 'Overrides'.
Function Method(x As String, y As Integer) As String
~~~~~~
BC40003: function 'Method' shadows an overloadable member declared in the base class 'Base'. If you want to overload the base method, this method must be declared 'Overloads'.
Function Method(x As String, y As Integer) As String
~~~~~~
BC31086: 'Public Overrides Sub Method(x As Integer)' cannot override 'Public Sub Method(x As Integer)' because it is not declared 'Overridable'.
Overrides Sub Method(x As Integer)
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30696ERR_OverloadWithOptionalTypes2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverloadWithOptionalTypes2">
<file name="a.vb"><![CDATA[
Class Cla30696
'COMPILEERROR: BC30696, "goo"
Public Function goo(Optional ByVal arg As ULong = 1)
Return "BC30696"
End Function
Public Function goo(Optional ByVal arg As Integer = 1)
Return "BC30696"
End Function
'COMPILEERROR: BC30696, "goo3"
Public Function goo1(ByVal arg As Integer, Optional ByVal arg1 As String = "")
Return "BC30696"
End Function
Public Function goo1(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
Return "BC30696"
End Function
End Class
Interface Scen2_1
'COMPILEERROR: BC30696, "goo"
Function goo(Optional ByVal arg As Object = Nothing)
Function goo(Optional ByVal arg As ULong = 1)
'COMPILEERROR: BC30696, "goo3"
Function goo1(ByVal arg As Integer, Optional ByVal arg1 As Object = Nothing)
Function goo1(ByVal arg As Integer, Optional ByVal arg1 As ULong = 1)
End Interface
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors><![CDATA[]]></errors>)
End Sub
<WorkItem(529018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529018")>
<Fact()>
Public Sub BC30697ERR_OverrideWithOptionalTypes2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideWithOptionalTypes2">
<file name="a.vb"><![CDATA[
Class Base
Public Overridable Sub goo(ByVal x As String, Optional ByVal y As String = "hello")
End Sub
End Class
Class C1
Inherits Base
Public Overrides Sub goo(ByVal x As String, Optional ByVal y As Integer = 1)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30697: 'Public Overrides Sub goo(x As String, [y As Integer = 1])' cannot override 'Public Overridable Sub goo(x As String, [y As String = "hello"])' because they differ by the types of optional parameters.
Public Overrides Sub goo(ByVal x As String, Optional ByVal y As Integer = 1)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30728ERR_StructsCannotHandleEvents()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructsCannotHandleEvents">
<file name="a.vb"><![CDATA[
Public Structure S1
Event e()
Sub goo() Handles c.e
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30728: Methods declared in structures cannot have 'Handles' clauses.
Sub goo() Handles c.e
~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Sub goo() Handles c.e
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30730ERR_OverridesImpliesOverridable()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverridesImpliesOverridable">
<file name="a.vb"><![CDATA[
Class CBase
overridable function goo
End function
End Class
Class C1
Inherits CBase
Overrides public Overridable function goo
End function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30730: Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.
Overrides public Overridable function goo
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for ERRID_ModuleCantUseMemberSpecifier1
' Old name="ModifierErrorsInsideModules"
<Fact>
Public Sub BC30735ERR_ModuleCantUseTypeSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module m1
protected Class c
Protected Enum e1
a
End Enum
End Class
Protected Enum e5
a
End Enum
Shadows Enum e6
a
End Enum
protected structure struct1
end structure
protected delegate Sub d1(i as integer)
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30735: Type in a Module cannot be declared 'protected'.
protected Class c
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'Protected'.
Protected Enum e5
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'Shadows'.
Shadows Enum e6
~~~~~~~
BC30735: Type in a Module cannot be declared 'protected'.
protected structure struct1
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'protected'.
protected delegate Sub d1(i as integer)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC30770ERR_DefaultEventNotFound1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="DefaultEventNotFound1">
<file name="a.vb"><![CDATA[
Imports System.ComponentModel
<DefaultEvent("LogonCompleted")> Public Class EventSource1
Private Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource2
Public Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource22
Friend Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource23
Protected Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleteD")> Public Class EventSource24
Protected Friend Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent(Nothing)> Public Class EventSource3
End Class
<DefaultEvent("")> Public Class EventSource4
End Class
<DefaultEvent(" ")> Public Class EventSource5
End Class
Class Base
Public Event LogonCompleted()
End Class
<DefaultEvent("LogonCompleted")> Class EventSource6
Inherits Base
Private Shadows Event LogonCompleted(ByVal UserName As String)
End Class
<DefaultEvent("LogonCompleted")> Interface EventSource7
End Interface
<DefaultEvent("LogonCompleted")> Structure EventSource8
End Structure
]]></file>
</compilation>, {SystemRef}, TestOptions.ReleaseDll)
Dim expectedErrors = <errors><![CDATA[
BC30770: Event 'LogonCompleted' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent("LogonCompleted")> Public Class EventSource1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30770: Event 'LogonCompleteD' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent("LogonCompleteD")> Public Class EventSource23
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30770: Event 'LogonCompleteD' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent("LogonCompleteD")> Public Class EventSource24
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30770: Event ' ' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.
<DefaultEvent(" ")> Public Class EventSource5
~~~~~~~~~~~~~~~~~~
BC30662: Attribute 'DefaultEventAttribute' cannot be applied to 'EventSource7' because the attribute is not valid on this declaration type.
<DefaultEvent("LogonCompleted")> Interface EventSource7
~~~~~~~~~~~~
BC30662: Attribute 'DefaultEventAttribute' cannot be applied to 'EventSource8' because the attribute is not valid on this declaration type.
<DefaultEvent("LogonCompleted")> Structure EventSource8
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact, WorkItem(545966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545966")>
Public Sub BC30772ERR_InvalidNonSerializedUsage()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidNonSerializedUsage">
<file name="a.vb"><![CDATA[
Imports System
Module M1
<NonSerialized>
Dim x = 1
<NonSerialized>
Event E As System.Action
End Module
]]></file>
</compilation>)
Dim expectedErrors =
<errors><![CDATA[
BC30772: 'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.
<NonSerialized>
~~~~~~~~~~~~~
BC30772: 'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.
<NonSerialized>
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30786ERR_ModuleCantUseDLLDeclareSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleCantUseDLLDeclareSpecifier1">
<file name="a.vb"><![CDATA[
Module M
Protected Declare Sub Goo Lib "My" ()
End Module
]]></file>
</compilation>)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_ModuleCantUseDLLDeclareSpecifier1, "Protected").WithArguments("Protected"))
End Sub
<Fact>
Public Sub BC30791ERR_StructCantUseDLLDeclareSpecifier1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructCantUseDLLDeclareSpecifier1">
<file name="a.vb"><![CDATA[
Structure M
Protected Declare Sub Goo Lib "My" ()
End Structure
]]></file>
</compilation>)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_StructCantUseDLLDeclareSpecifier1, "Protected").WithArguments("Protected"))
End Sub
<Fact>
Public Sub BC30795ERR_SharedStructMemberCannotSpecifyNew()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SharedStructMemberCannotSpecifyNew">
<file name="a.vb"><![CDATA[
Structure S1
' does not work
Dim structVar1 As New System.ApplicationException
' works
Shared structVar2 As New System.ApplicationException
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30795: Non-shared members in a Structure cannot be declared 'New'.
Dim structVar1 As New System.ApplicationException
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC31049ERR_SharedStructMemberCannotSpecifyInitializers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC30795ERR_SharedStructMemberCannotSpecifyInitializers">
<file name="a.vb"><![CDATA[
Structure S1
' does not work
Dim structVar1 As System.ApplicationException = New System.ApplicationException()
' works
Shared structVar2 As System.ApplicationException = New System.ApplicationException()
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31049: Initializers on structure members are valid only for 'Shared' members and constants.
Dim structVar1 As System.ApplicationException = New System.ApplicationException()
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC30798ERR_InvalidTypeForAliasesImport2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InvalidTypeForAliasesImport2">
<file name="a.vb"><![CDATA[
Imports aa = System.Action 'BC30798
Imports bb = ns1.Intfc2.intfc2goo 'BC40056
Namespace ns1
Public Class Intfc2
Public intfc2goo As Integer
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30798: 'Action' for the Imports alias to 'Action' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.
Imports aa = System.Action 'BC30798
~~~~~~~~~~~~~~~~~~
BC40056: Namespace or type specified in the Imports 'ns1.Intfc2.intfc2goo' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports bb = ns1.Intfc2.intfc2goo 'BC40056
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
<WorkItem(13926, "https://github.com/dotnet/roslyn/issues/13926")>
Public Sub BadAliasTarget()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports BadAlias = unknown
Public Class Class1
Public Shared Sub Main()
End Sub
Function Test() As BadAlias
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'unknown' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports BadAlias = unknown
~~~~~~~
BC31208: Type or namespace 'unknown' is not defined.
Function Test() As BadAlias
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
Dim test = compilation1.GetTypeByMetadataName("Class1").GetMember(Of MethodSymbol)("Test")
Assert.True(test.ReturnType.IsErrorType())
Assert.Equal(DiagnosticSeverity.Error, DirectCast(test.ReturnType, ErrorTypeSymbol).ErrorInfo.Severity)
End Sub
<Fact>
Public Sub BC30828ERR_ObsoleteAsAny()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ObsoleteAsAny">
<file name="a.vb"><![CDATA[
Class C1
Declare Sub goo Lib "a.dll" (ByRef bit As Any)
End Class
]]></file>
</compilation>)
compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_ObsoleteAsAny, "Any").WithArguments("Any"))
End Sub
<Fact>
Public Sub BC30906ERR_OverrideWithArrayVsParamArray2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideWithArrayVsParamArray2">
<file name="a.vb"><![CDATA[
Class C1
Overridable Sub goo(ByVal a As Integer())
End Sub
End Class
Class C2
Inherits C1
Overrides Sub goo(ByVal ParamArray a As Integer())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30906: 'Public Overrides Sub goo(ParamArray a As Integer())' cannot override 'Public Overridable Sub goo(a As Integer())' because they differ by parameters declared 'ParamArray'.
Overrides Sub goo(ByVal ParamArray a As Integer())
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30907ERR_CircularBaseDependencies4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CircularBaseDependencies4">
<file name="a.vb"><![CDATA[
Class A
Inherits B
End Class
Class B
Inherits C
End Class
Class C
Inherits A.D
End Class
Partial Class A
Class D
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30907: This inheritance causes circular dependencies between class 'A' and its nested or base type '
'A' inherits from 'B'.
'B' inherits from 'C'.
'C' inherits from 'A.D'.
'A.D' is nested in 'A'.'.
Inherits B
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30908ERR_NestedBase2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NestedBase2">
<file name="a.vb"><![CDATA[
NotInheritable Class cls1b
Inherits cls1a
MustInherit Class cls1a
Sub subScen1()
gstrexpectedresult = "Scen1"
End Sub
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31446: Class 'cls1b' cannot reference its nested type 'cls1b.cls1a' in Inherits clause.
Inherits cls1a
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class PublicClass
Protected Friend Structure ProtectedFriendStructure
End Structure
End Class
Friend Class FriendClass
End Class
Friend Structure FriendStructure
End Structure
Friend Interface FriendInterface
End Interface
Friend Enum FriendEnum
A
End Enum
Public Class A
Inherits PublicClass
Public F As ProtectedFriendStructure
Public G As FriendClass
Public H As FriendStructure
End Class
Public Structure B
Public F As FriendInterface
Public G As FriendEnum
End Structure
Public Class C
Inherits PublicClass
Public Function F() As ProtectedFriendStructure
End Function
Public Sub M(x As FriendClass)
End Sub
End Class
Public Interface I
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'F' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'A'.
Public F As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'G' cannot expose type 'FriendClass' outside the project through class 'A'.
Public G As FriendClass
~~~~~~~~~~~
BC30909: 'H' cannot expose type 'FriendStructure' outside the project through class 'A'.
Public H As FriendStructure
~~~~~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendInterface' outside the project through structure 'B'.
Public F As FriendInterface
~~~~~~~~~~~~~~~
BC30909: 'G' cannot expose type 'FriendEnum' outside the project through structure 'B'.
Public G As FriendEnum
~~~~~~~~~~
BC30909: 'F' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'C'.
Public Function F() As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendClass' outside the project through class 'C'.
Public Sub M(x As FriendClass)
~~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendStructure' outside the project through interface 'I'.
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'y' cannot expose type 'FriendInterface' outside the project through interface 'I'.
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendEnum' outside the project through interface 'I'.
Function F(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class PublicClass
Protected Friend Structure ProtectedFriendStructure
End Structure
End Class
Friend Class FriendClass
End Class
Friend Structure FriendStructure
End Structure
Friend Interface FriendInterface
End Interface
Friend Enum FriendEnum
A
End Enum
Public Class A
Inherits PublicClass
Property P As ProtectedFriendStructure
Property Q As FriendClass
Property R As FriendStructure
End Class
Public Structure B
Property P As FriendInterface
Property Q As FriendEnum
End Structure
Public Class C
Inherits PublicClass
ReadOnly Property P(x As FriendClass) As ProtectedFriendStructure
Get
Return Nothing
End Get
End Property
End Class
Public Interface I
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'P' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'A'.
Property P As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'Q' cannot expose type 'FriendClass' outside the project through class 'A'.
Property Q As FriendClass
~~~~~~~~~~~
BC30909: 'R' cannot expose type 'FriendStructure' outside the project through class 'A'.
Property R As FriendStructure
~~~~~~~~~~~~~~~
BC30909: 'P' cannot expose type 'FriendInterface' outside the project through structure 'B'.
Property P As FriendInterface
~~~~~~~~~~~~~~~
BC30909: 'Q' cannot expose type 'FriendEnum' outside the project through structure 'B'.
Property Q As FriendEnum
~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendClass' outside the project through class 'C'.
ReadOnly Property P(x As FriendClass) As ProtectedFriendStructure
~~~~~~~~~~~
BC30909: 'P' cannot expose type 'PublicClass.ProtectedFriendStructure' outside the project through class 'C'.
ReadOnly Property P(x As FriendClass) As ProtectedFriendStructure
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'x' cannot expose type 'FriendStructure' outside the project through interface 'I'.
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'y' cannot expose type 'FriendInterface' outside the project through interface 'I'.
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~~~~~~
BC30909: 'P' cannot expose type 'FriendEnum' outside the project through interface 'I'.
ReadOnly Property P(x As FriendStructure, y As FriendInterface) As FriendEnum
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528153")>
<Fact()>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class PublicClass
Protected Friend Interface ProtectedFriendInterface
End Interface
Protected Friend Class ProtectedFriendClass
End Class
End Class
Friend Interface FriendInterface
End Interface
Friend Class FriendClass
End Class
Public Class A
Inherits PublicClass
Public Sub M(Of T As ProtectedFriendInterface, U As ProtectedFriendClass)()
End Sub
End Class
Public Structure B
Public Sub M(Of T As FriendInterface, U As FriendClass)()
End Sub
End Structure
Public Interface I
Function F(Of T As FriendInterface, U As FriendClass)() As Object
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'M' cannot expose type 'PublicClass.ProtectedFriendInterface' outside the project through class 'A'.
Public Sub M(Of T As ProtectedFriendInterface, U As ProtectedFriendClass)()
~~~~~~~~~~~~~~~~~~~~~~~~
BC30909: 'M' cannot expose type 'PublicClass.ProtectedFriendClass' outside the project through class 'A'.
Public Sub M(Of T As ProtectedFriendInterface, U As ProtectedFriendClass)()
~~~~~~~~~~~~~~~~~~~~
BC30909: 'M' cannot expose type 'FriendInterface' outside the project through structure 'B'.
Public Sub M(Of T As FriendInterface, U As FriendClass)()
~~~~~~~~~~~~~~~
BC30909: 'M' cannot expose type 'FriendClass' outside the project through structure 'B'.
Public Sub M(Of T As FriendInterface, U As FriendClass)()
~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendInterface' outside the project through interface 'I'.
Function F(Of T As FriendInterface, U As FriendClass)() As Object
~~~~~~~~~~~~~~~
BC30909: 'F' cannot expose type 'FriendClass' outside the project through interface 'I'.
Function F(Of T As FriendInterface, U As FriendClass)() As Object
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528153")>
<Fact()>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Public Interface A
Friend Interface B
End Interface
Public Interface C
Function F() As B
Public Interface D
Sub M(o As B)
End Interface
End Interface
End Interface
Public Interface E
Inherits A
Function F() As B
End Interface
Public Interface F
Sub M(o As A.B)
End Interface
End Namespace
Public Interface G
Function F() As N.A.B
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'F' cannot expose type 'A.B' outside the project through interface 'C'.
Function F() As B
~
BC30909: 'o' cannot expose type 'A.B' outside the project through interface 'D'.
Sub M(o As B)
~
BC30909: 'F' cannot expose type 'A.B' outside the project through interface 'E'.
Function F() As B
~
BC30909: 'o' cannot expose type 'A.B' outside the project through interface 'F'.
Sub M(o As A.B)
~~~
BC30909: 'F' cannot expose type 'A.B' outside the project through interface 'G'.
Function F() As N.A.B
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30909ERR_AccessMismatchOutsideAssembly4_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Friend Enum E
A
End Enum
Public Class C
Public Const F As E = E.A
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30909: 'F' cannot expose type 'E' outside the project through class 'C'.
Public Const F As E = E.A
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30910ERR_InheritanceAccessMismatchOutside3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritanceAccessMismatchOutside3">
<file name="a.vb"><![CDATA[
Friend Interface I1
End Interface
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30910: 'I2' cannot inherit from interface 'I1' because it expands the access of the base interface outside the assembly.
Inherits I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30911ERR_UseOfObsoletePropertyAccessor3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoletePropertyAccessor3">
<file name="a.vb"><![CDATA[
Imports System
Class C1
ReadOnly Property p As String
<Obsolete("hello", True)>
Get
Return "hello"
End Get
End Property
End Class
Class C2
Sub goo()
Dim s As New C1
Dim a = s.p
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30911: 'Get' accessor of 'Public ReadOnly Property p As String' is obsolete: 'hello'.
Dim a = s.p
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30912ERR_UseOfObsoletePropertyAccessor2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoletePropertyAccessor2">
<file name="a.vb"><![CDATA[
Imports System
Class C1
ReadOnly Property p As String
<Obsolete(nothing,True)>
Get
Return "hello"
End Get
End Property
End Class
Class C2
Sub goo()
Dim s As New C1
Dim a = s.p
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30912: 'Get' accessor of 'Public ReadOnly Property p As String' is obsolete.
Dim a = s.p
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543640")>
Public Sub BC30914ERR_AccessMismatchImplementedEvent6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AccessMismatchImplementedEvent6">
<file name="a.vb"><![CDATA[
Public Class C
Protected Interface i1
Event goo()
End Interface
Friend Class c1
Implements i1
Public Event goo() Implements i1.goo
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30914: 'goo' cannot expose the underlying delegate type 'C.i1.gooEventHandler' of the event it is implementing to namespace '<Default>' through class 'c1'.
Public Event goo() Implements i1.goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543641")>
Public Sub BC30915ERR_AccessMismatchImplementedEvent4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AccessMismatchImplementedEvent4">
<file name="a.vb"><![CDATA[
Interface i1
Event goo()
End Interface
Public Class c1
Implements i1
Public Event goo() Implements i1.goo
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30915: 'goo' cannot expose the underlying delegate type 'i1.gooEventHandler' of the event it is implementing outside the project through class 'c1'.
Public Event goo() Implements i1.goo
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30916ERR_InheritanceCycleInImportedType1()
Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1
Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2
Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Class C
Class C
Inherits C1
implements I1
End Class
End Class
]]></file>
</compilation>,
{Net451.mscorlib, C1, C2})
Dim expectedErrors = <errors><![CDATA[
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
Inherits C1
~~
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30916ERR_InheritanceCycleInImportedType1_2()
Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1
Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2
Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Class C
Inherits C2
implements I1
End Class
]]></file>
</compilation>,
{Net451.mscorlib, C1, C2})
Dim expectedErrors = <errors><![CDATA[
BC30916: Type 'C2' is not supported because it either directly or indirectly inherits from itself.
Inherits C2
~~
BC30916: Type 'C2' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30916ERR_InheritanceCycleInImportedType1_3()
Dim C1 = TestReferences.SymbolsTests.CyclicInheritance.Class1
Dim C2 = TestReferences.SymbolsTests.CyclicInheritance.Class2
Dim Comp = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Class C
Inherits C1
implements I1
End Class
]]></file>
</compilation>,
{Net451.mscorlib, C1, C2})
Dim expectedErrors = <errors><![CDATA[
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
Inherits C1
~~
BC30916: Type 'C1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
BC30916: Type 'I1' is not supported because it either directly or indirectly inherits from itself.
implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30921ERR_InheritsTypeArgAccessMismatch7()
Dim Comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsTypeArgAccessMismatch7">
<file name="a.vb"><![CDATA[
Public Class containingClass
Public Class baseClass(Of t)
End Class
Friend Class derivedClass
Inherits baseClass(Of internalStructure)
End Class
Private Structure internalStructure
Dim firstMember As Integer
End Structure
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30921: 'derivedClass' cannot inherit from class 'containingClass.baseClass(Of containingClass.internalStructure)' because it expands the access of type 'containingClass.internalStructure' to namespace '<Default>'.
Inherits baseClass(Of internalStructure)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30922ERR_InheritsTypeArgAccessMismatchOutside5()
Dim Comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritsTypeArgAccessMismatchOutside5">
<file name="a.vb"><![CDATA[
Public Class baseClass(Of t)
End Class
Public Class derivedClass
Inherits baseClass(Of restrictedStructure)
End Class
Friend Structure restrictedStructure
Dim firstMember As Integer
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30922: 'derivedClass' cannot inherit from class 'baseClass(Of restrictedStructure)' because it expands the access of type 'restrictedStructure' outside the assembly.
Inherits baseClass(Of restrictedStructure)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(Comp, expectedErrors)
End Sub
<Fact>
Public Sub BC30925ERR_PartialTypeAccessMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialTypeAccessMismatch3">
<file name="a.vb"><![CDATA[
Class s1
Partial Protected Class c1
End Class
Partial Private Class c1
End Class
Partial Friend Class c1
End Class
Partial Protected Interface I1
End Interface
Partial Private Interface I1
End Interface
Partial Friend Interface I1
End Interface
End Class
Partial Public Module m1
End Module
Partial Friend Module m1
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30925: Specified access 'Private' for 'c1' does not match the access 'Protected' specified on one of its other partial types.
Partial Private Class c1
~~
BC30925: Specified access 'Friend' for 'c1' does not match the access 'Protected' specified on one of its other partial types.
Partial Friend Class c1
~~
BC30925: Specified access 'Private' for 'I1' does not match the access 'Protected' specified on one of its other partial types.
Partial Private Interface I1
~~
BC30925: Specified access 'Friend' for 'I1' does not match the access 'Protected' specified on one of its other partial types.
Partial Friend Interface I1
~~
BC30925: Specified access 'Friend' for 'm1' does not match the access 'Public' specified on one of its other partial types.
Partial Friend Module m1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30926ERR_PartialTypeBadMustInherit1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialTypeBadMustInherit1">
<file name="a.vb"><![CDATA[
Partial Class C1
Partial MustInherit Class C2
End Class
End Class
Partial Class C1
Partial NotInheritable Class C2
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30926: 'MustInherit' cannot be specified for partial type 'C2' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.
Partial MustInherit Class C2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' dup of 30607?
<Fact>
Public Sub BC30927ERR_MustOverOnNotInheritPartClsMem1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustOverOnNotInheritPartClsMem1">
<file name="a.vb"><![CDATA[
Public Class C1
MustOverride Sub goo()
End Class
Partial Public NotInheritable Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30927: 'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.
MustOverride Sub goo()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30928ERR_BaseMismatchForPartialClass3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseMismatchForPartialClass3">
<file name="a.vb"><![CDATA[
Option Strict On
Interface I1
End Interface
Interface I2
End Interface
Partial Interface I3
Inherits I1
End Interface
Partial Interface I3
Inherits I2
End Interface
Class TestModule
Sub Test(x As I3)
Dim y As I1 = x
Dim z As I2 = x
End Sub
End Class
Partial Class Cls2(Of T, U)
Inherits Class1(Of U, T)
End Class
Partial Class Cls2(Of T, U)
Inherits Class1(Of T, T)
End Class
Class Class1(Of X, Y)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30928: Base class 'Class1(Of T, T)' specified for class 'Cls2' cannot be different from the base class 'Class1(Of U, T)' of one of its other partial types.
Inherits Class1(Of T, T)
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30931ERR_PartialTypeTypeParamNameMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A(Of T)
Partial Class B(Of U As A(Of T), V As A(Of V))
End Class
Partial Class B(Of X As A(Of T), Y As A(Of Y))
End Class
Partial Interface I(Of U As A(Of T), V As A(Of V))
End Interface
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
End Interface
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30931: Type parameter name 'X' does not match the name 'U' of the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30931: Type parameter name 'Y' does not match the name 'V' of the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30002: Type 'Y' is not defined.
Partial Class B(Of X As A(Of T), Y As A(Of Y))
~
BC30931: Type parameter name 'X' does not match the name 'U' of the corresponding type parameter defined on one of the other partial types of 'I'.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
BC30931: Type parameter name 'Y' does not match the name 'V' of the corresponding type parameter defined on one of the other partial types of 'I'.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'I'.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
BC30002: Type 'Y' is not defined.
Partial Interface I(Of X As A(Of T), Y As A(Of Y))
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30932ERR_PartialTypeConstraintMismatch1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
End Interface
Interface IB
End Interface
' Different constraints.
Partial Class A1(Of T As Structure)
End Class
Partial Class A1(Of T As Class)
End Class
Partial Class A2(Of T As Structure, U As IA(Of T))
End Class
Partial Class A2(Of T As Class, U As IB)
End Class
Partial Class A3(Of T As IA(Of T))
End Class
Partial Class A3(Of T As IA(Of IA(Of T)))
End Class
Partial Class A4(Of T As {Structure, IB})
End Class
Partial Class A4(Of T As {Class, IB})
End Class
Partial Structure A5(Of T As {IA(Of T), New})
End Structure
Partial Structure A5(Of T As {IA(Of T), New})
End Structure
Partial Structure A5(Of T As {IB, New})
End Structure
' Additional constraints.
Partial Class B1(Of T As New)
End Class
Partial Class B1(Of T As {Class, New})
End Class
Partial Class B2(Of T, U As {IA(Of T)})
End Class
Partial Class B2(Of T, U As {IB, IA(Of T)})
End Class
' Missing constraints.
Partial Class C1(Of T As {Class, New})
End Class
Partial Class C1(Of T As {New})
End Class
Partial Structure C2(Of T, U As {IB, IA(Of T)})
End Structure
Partial Structure C2(Of T, U As {IA(Of T)})
End Structure
' Same constraints, different order.
Partial Class D1(Of T As {Structure, IA(Of T), IB})
End Class
Partial Class D1(Of T As {IB, IA(Of T), Structure})
End Class
Partial Class D1(Of T As {Structure, IB, IA(Of T)})
End Class
Partial Class D2(Of T, U, V As {T, U})
End Class
Partial Class D2(Of T, U, V As {U, T})
End Class
' Different constraint clauses.
Partial Class E1(Of T, U As T)
End Class
Partial Class E1(Of T As Class, U)
End Class
Partial Class E1(Of T, U As T)
End Class
Partial Class E2(Of T, U As IB)
End Class
Partial Class E2(Of T As IA(Of U), U)
End Class
Partial Class E2(Of T As IB, U)
End Class
' Additional constraint clause.
Partial Class F1(Of T)
End Class
Partial Class F1(Of T)
End Class
Partial Class F1(Of T As Class)
End Class
Partial Class F2(Of T As Class, U)
End Class
Partial Class F2(Of T As Class, U As T)
End Class
' Missing constraint clause.
Partial Class G1(Of T As {Class})
End Class
Partial Class G1(Of T)
End Class
Partial Structure G2(Of T As {Class}, U As {T})
End Structure
Partial Structure G2(Of T As {Class}, U)
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A1'.
Partial Class A1(Of T As Class)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A2'.
Partial Class A2(Of T As Class, U As IB)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A2'.
Partial Class A2(Of T As Class, U As IB)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A3'.
Partial Class A3(Of T As IA(Of IA(Of T)))
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A4'.
Partial Class A4(Of T As {Class, IB})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A5'.
Partial Structure A5(Of T As {IB, New})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B1'.
Partial Class B1(Of T As {Class, New})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B2'.
Partial Class B2(Of T, U As {IB, IA(Of T)})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'C1'.
Partial Class C1(Of T As {New})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'C2'.
Partial Structure C2(Of T, U As {IA(Of T)})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E1'.
Partial Class E1(Of T As Class, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E1'.
Partial Class E1(Of T As Class, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IA(Of U), U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IA(Of U), U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IB, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'E2'.
Partial Class E2(Of T As IB, U)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'F1'.
Partial Class F1(Of T As Class)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'F2'.
Partial Class F2(Of T As Class, U As T)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'G1'.
Partial Class G1(Of T)
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'G2'.
Partial Structure G2(Of T As {Class}, U)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Unrecognized constraint types should not result
' in constraint mismatch errors in partial types.
<Fact()>
Public Sub BC30932ERR_PartialTypeConstraintMismatch1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Partial Class C(Of T As {Class, Unknown})
End Class
Partial Class C(Of T As {Unknown, Class})
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'Unknown' is not defined.
Partial Class C(Of T As {Class, Unknown})
~~~~~~~
BC30002: Type 'Unknown' is not defined.
Partial Class C(Of T As {Unknown, Class})
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Duplicate constraints in partial types.
<Fact()>
Public Sub BC30932ERR_PartialTypeConstraintMismatch1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Partial Class A(Of T As {New, New, I, I})
End Class
Partial Class A(Of T As {New, I})
End Class
Partial Class B(Of T, U As T)
End Class
Partial Class B(Of T, U As {T, T})
End Class
]]></file>
</compilation>)
' Note: Dev10 simply reports the duplicate constraint in each case, even
' in subsequent partial declarations. Arguably the Dev10 behavior is better.
Dim expectedErrors1 = <errors><![CDATA[
BC32081: 'New' constraint cannot be specified multiple times for the same type parameter.
Partial Class A(Of T As {New, New, I, I})
~~~
BC32071: Constraint type 'I' already specified for this type parameter.
Partial Class A(Of T As {New, New, I, I})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'A'.
Partial Class A(Of T As {New, I})
~
BC30932: Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of 'B'.
Partial Class B(Of T, U As {T, T})
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30935ERR_AmbiguousOverrides3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousOverrides3">
<file name="a.vb"><![CDATA[
Public Class baseClass(Of t)
Public Overridable Sub goo(ByVal inputValue As String)
End Sub
Public Overridable Sub goo(ByVal inputValue As t)
End Sub
End Class
Public Class derivedClass
Inherits baseClass(Of String)
Overrides Sub goo(ByVal inputValue As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30935: Member 'Public Overridable Sub goo(inputValue As String)' that matches this signature cannot be overridden because the class 'baseClass' contains multiple members with this same name and signature:
'Public Overridable Sub goo(inputValue As String)'
'Public Overridable Sub goo(inputValue As t)'
Overrides Sub goo(ByVal inputValue As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC30937ERR_AmbiguousImplements3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AmbiguousImplements3">
<file name="a.vb"><![CDATA[
Public Interface baseInterface(Of t)
Sub doSomething(ByVal inputValue As String)
Sub doSomething(ByVal inputValue As t)
End Interface
Public Class implementingClass
Implements baseInterface(Of String)
Sub doSomething(ByVal inputValue As String) _
Implements baseInterface(Of String).doSomething
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'implementingClass' must implement 'Sub doSomething(inputValue As String)' for interface 'baseInterface(Of String)'.
Implements baseInterface(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~
BC30937: Member 'baseInterface(Of String).doSomething' that matches this signature cannot be implemented because the interface 'baseInterface(Of String)' contains multiple members with this same name and signature:
'Sub doSomething(inputValue As String)'
'Sub doSomething(inputValue As String)'
Implements baseInterface(Of String).doSomething
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC30972ERR_StructLayoutAttributeNotAllowed()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructLayoutAttributeNotAllowed">
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Runtime.InteropServices
<StructLayout(1)>
Structure C1(Of T)
Sub goo(ByVal a As T)
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30972: Attribute 'StructLayout' cannot be applied to a generic type.
<StructLayout(1)>
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31029ERR_EventHandlerSignatureIncompatible2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventHandlerSignatureIncompatible2">
<file name="a.vb"><![CDATA[
option strict on
Class clsTest1
Event ev1(ByVal ArgC As Char)
End Class
Class clsTest2
Inherits clsTest1
Shadows Event ev1(ByVal ArgI As Integer)
End Class
Class clsTest3
Dim WithEvents clsTest As clsTest2
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31029: Method 'subTest' cannot handle event 'ev1' because they do not have a compatible signature.
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31029ERR_EventHandlerSignatureIncompatible2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventHandlerSignatureIncompatible2a">
<file name="a.vb"><![CDATA[
option strict off
Class clsTest1
Event ev1(ByVal ArgC As Char)
End Class
Class clsTest2
Inherits clsTest1
Shadows Event ev1(ByVal ArgI As Integer)
End Class
Class clsTest3
Dim WithEvents clsTest As clsTest2
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31029: Method 'subTest' cannot handle event 'ev1' because they do not have a compatible signature.
Private Sub subTest(ByVal ArgC As Char) Handles clsTest.ev1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(542143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542143")>
<Fact>
Public Sub BC31033ERR_InterfaceImplementedTwice1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceImplementedTwice1">
<file name="a.vb"><![CDATA[
Class C1
Implements I1(Of Integer), I1(Of Double), I1(Of Integer)
End Class
Interface I1(Of T)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31033: Interface 'I1(Of Integer)' can be implemented only once by this type.
Implements I1(Of Integer), I1(Of Double), I1(Of Integer)
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31033ERR_InterfaceImplementedTwice1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceImplementedTwice1">
<file name="a.vb"><![CDATA[
Class c3_1
Implements i3_1
End Class
Class c3_2
Inherits c3_1
Implements i3_1, i3_1, i3_1
End Class
Interface i3_1
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31033: Interface 'i3_1' can be implemented only once by this type.
Implements i3_1, i3_1, i3_1
~~~~
BC31033: Interface 'i3_1' can be implemented only once by this type.
Implements i3_1, i3_1, i3_1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31035ERR_InterfaceNotImplemented1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceNotImplemented1">
<file name="a.vb"><![CDATA[
Interface I
Sub S()
End Interface
Class C1
Implements I
Public Sub S() Implements I.S
End Sub
End Class
Class C2
Inherits C1
Public Sub F() Implements I.S
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31035: Interface 'I' is not implemented by this class.
Public Sub F() Implements I.S
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31041ERR_BadInterfaceMember()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadInterfaceMember">
<file name="a.vb"><![CDATA[
Interface Interface1
Module Module1
End Module
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30603: Statement cannot appear within an interface body.
Module Module1
~~~~~~~~~~~~~~
BC30603: Statement cannot appear within an interface body.
End Module
~~~~~~~~~~
BC30622: 'End Module' must be preceded by a matching 'Module'.
End Module
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseParseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31043ERR_ArrayInitInStruct_1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public j(10) As Integer
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public j(10) As Integer
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31043ERR_ArrayInitInStruct_2">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared j(10) As Integer
End Structure
]]></file>
</compilation>)
CompilationUtils.AssertNoDeclarationDiagnostics(compilation1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31043ERR_ArrayInitInStruct_3">
<file name="a.vb"><![CDATA[
Public Structure S1
Public k(10) As Integer = {1}
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public k(10) As Integer = {1}
~~~~~
BC31049: Initializers on structure members are valid only for 'Shared' members and constants.
Public k(10) As Integer = {1}
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31043ERR_ArrayInitInStruct_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ArrayInitInStruct_4">
<file name="a.vb"><![CDATA[
Public Structure S1
Public l(10), m(1), n As Integer
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public l(10), m(1), n As Integer
~~~~~
BC31043: Arrays declared as structure members cannot be declared with an initial size.
Public l(10), m(1), n As Integer
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31044ERR_EventTypeNotDelegate()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventTypeNotDelegate">
<file name="a.vb"><![CDATA[
Public Class C1
Public Event E As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31044: Events declared with an 'As' clause must have a delegate type.
Public Event E As String
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31047ERR_ProtectedTypeOutsideClass()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ProtectedTypeOutsideClass">
<file name="a.vb"><![CDATA[
Protected Enum Enum11
Apple
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31047: Protected types can only be declared inside of a class.
Protected Enum Enum11
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for ERRID_StructCantUseVarSpecifier1
' Oldname"ModifierErrorsInsideStructures"
<Fact>
Public Sub BC31047ERR_ProtectedTypeOutsideClass_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Structure s
Protected Enum e3
a
End Enum
Private Enum e4
x
End Enum
protected delegate Sub d1(i as integer)
Protected Structure s_s1
end structure
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31047: Protected types can only be declared inside of a class.
Protected Enum e3
~~
BC31047: Protected types can only be declared inside of a class.
protected delegate Sub d1(i as integer)
~~
BC31047: Protected types can only be declared inside of a class.
Protected Structure s_s1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC31048ERR_DefaultPropertyWithNoParams()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Default Property P()
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
Class B
Default ReadOnly Property Q(ParamArray x As Object())
Get
Return Nothing
End Get
End Property
End Class
Interface IA
Default WriteOnly Property P()
End Interface
Interface IB
Default Property Q(ParamArray x As Object())
End Interface
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property P()
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default ReadOnly Property Q(ParamArray x As Object())
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default WriteOnly Property P()
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property Q(ParamArray x As Object())
~
]]></errors>)
End Sub
<Fact>
Public Sub BC31048ERR_DefaultPropertyWithNoParams_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA
Default Property P(Optional o As Object = Nothing)
Property Q(Optional o As Object = Nothing)
End Interface
Interface IB
Default Property P(x As Object, Optional y As Integer = 1)
Default Property P(Optional x As Integer = 0, Optional y As Integer = 1)
Property Q(Optional x As Integer = 0, Optional y As Integer = 1)
End Interface
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property P(Optional o As Object = Nothing)
~
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default Property P(Optional x As Integer = 0, Optional y As Integer = 1)
~
]]></errors>)
End Sub
<Fact>
Public Sub BC31049ERR_InitializerInStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InitializerInStruct">
<file name="a.vb"><![CDATA[
Structure S1
' does not work
Dim i As Integer = 10
' works
const j as Integer = 10
shared k as integer = 10
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31049: Initializers on structure members are valid only for 'Shared' members and constants.
Dim i As Integer = 10
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31051ERR_DuplicateImport1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateImport1">
<file name="a.vb"><![CDATA[
Imports ns1.genclass(Of String)
Imports ns1.genclass(Of String)
Namespace ns1
Class genclass(Of T)
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31051: Namespace or type 'genclass(Of String)' has already been imported.
Imports ns1.genclass(Of String)
~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31051ERR_DuplicateImport1_GlobalImports()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateImport1_GlobalImports">
<file name="a.vb"><![CDATA[
Imports System.Collections
Imports System.Collections
Class C
End Class
]]></file>
</compilation>, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithGlobalImports(
GlobalImport.Parse(
{"System.Collections", "System.Collections"}
)
))
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31051: Namespace or type 'System.Collections' has already been imported.
Imports System.Collections
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31051ERR_DuplicateImport1_GlobalImports_NoErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31051ERR_DuplicateImport1_GlobalImports_NoErrors">
<file name="a.vb"><![CDATA[
Imports System.Collections
Class C
End Class
]]></file>
</compilation>, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithGlobalImports(
GlobalImport.Parse(
{"System.Collections", "System.Collections"}
)
))
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors><![CDATA[]]></errors>)
End Sub
<Fact()>
Public Sub BC31052ERR_BadModuleFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BC31052ERR_BadModuleFlags1">
<file name="a.vb"><![CDATA[
NotInheritable Module M1
End Module
shared Module M2
End Module
readonly Module M3
End Module
overridable Module M5
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31052: Modules cannot be declared 'NotInheritable'.
NotInheritable Module M1
~~~~~~~~~~~~~~
BC31052: Modules cannot be declared 'shared'.
shared Module M2
~~~~~~
BC31052: Modules cannot be declared 'readonly'.
readonly Module M3
~~~~~~~~
BC31052: Modules cannot be declared 'overridable'.
overridable Module M5
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_1()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module M1
Class Cls1
Event e()
End Class
Event obj1()
Dim obj1event As [Delegate]
End Module
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_SynthMemberClashesWithMember5, "obj1").WithArguments("event", "obj1", "obj1Event", "module", "M1"))
End Sub
<Fact>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property u
Function get_p()
Return Nothing
End Function
Shared Function set_p()
Return Nothing
End Function
Shared Sub GET_Q()
End Sub
Sub SET_Q()
End Sub
Dim get_R
Shared set_R
Shared Property get_s
Property set_s
Class get_T
End Class
Structure set_T
End Structure
Enum get_U
X
End Enum
End Class
]]></file>
</compilation>)
' Since nested types are bound before members, we report 31061 for
' cases where nested types conflict with implicit property members.
' This differs from Dev10 which reports 31060 in all these cases.
Dim expectedErrors1 = <errors><![CDATA[
BC31060: property 'P' implicitly defines 'get_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'P' implicitly defines 'set_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'Q' implicitly defines 'get_Q', which conflicts with a member of the same name in class 'C'.
Shared Property Q
~
BC31060: property 'Q' implicitly defines 'set_Q', which conflicts with a member of the same name in class 'C'.
Shared Property Q
~
BC31060: property 'r' implicitly defines 'get_r', which conflicts with a member of the same name in class 'C'.
Property r
~
BC31060: property 'r' implicitly defines 'set_r', which conflicts with a member of the same name in class 'C'.
Property r
~
BC31060: property 's' implicitly defines 'get_s', which conflicts with a member of the same name in class 'C'.
Shared Property s
~
BC31060: property 's' implicitly defines 'set_s', which conflicts with a member of the same name in class 'C'.
Shared Property s
~
BC31061: class 'get_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Class get_T
~~~~~
BC31061: structure 'set_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Structure set_T
~~~~~
BC31061: enum 'get_U' conflicts with a member implicitly declared for property 'u' in class 'C'.
Enum get_U
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
Get
Return Nothing
End Get
Set
End Set
End Property
ReadOnly Property Q
Get
Return Nothing
End Get
End Property
WriteOnly Property R
Set
End Set
End Property
Private get_P
Private set_P
Private get_Q
Private set_Q
Private get_R
Private set_R
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31060: property 'P' implicitly defines 'get_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'P' implicitly defines 'set_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'Q' implicitly defines 'get_Q', which conflicts with a member of the same name in class 'C'.
ReadOnly Property Q
~
BC31060: property 'R' implicitly defines 'set_R', which conflicts with a member of the same name in class 'C'.
WriteOnly Property R
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31060ERR_SynthMemberClashesWithMember5_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property U
Property v
Shared Property w
Property X
Function _p()
Return Nothing
End Function
Shared Sub _Q()
End Sub
Dim _r
Shared _S
Shared Property _t
Property _U
Class _v
End Class
Structure _W
End Structure
Enum _x
X
End Enum
End Class
]]></file>
</compilation>)
' Since nested types are bound before members, we report 31061 for
' cases where nested types conflict with implicit property members.
' This differs from Dev10 which reports 31060 in all these cases.
Dim expectedErrors1 = <errors><![CDATA[
BC31060: property 'P' implicitly defines '_P', which conflicts with a member of the same name in class 'C'.
Property P
~
BC31060: property 'Q' implicitly defines '_Q', which conflicts with a member of the same name in class 'C'.
Shared Property Q
~
BC31060: property 'r' implicitly defines '_r', which conflicts with a member of the same name in class 'C'.
Property r
~
BC31060: property 's' implicitly defines '_s', which conflicts with a member of the same name in class 'C'.
Shared Property s
~
BC31060: property 'T' implicitly defines '_T', which conflicts with a member of the same name in class 'C'.
Property T
~
BC31060: property 'U' implicitly defines '_U', which conflicts with a member of the same name in class 'C'.
Shared Property U
~
BC31061: class '_v' conflicts with a member implicitly declared for property 'v' in class 'C'.
Class _v
~~
BC31061: structure '_W' conflicts with a member implicitly declared for property 'w' in class 'C'.
Structure _W
~~
BC31061: enum '_x' conflicts with a member implicitly declared for property 'X' in class 'C'.
Enum _x
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31061ERR_MemberClashesWithSynth6_1()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M1
Class Cls1
Event e()
End Class
Dim WithEvents ObjEvent As Cls1
Event Obj()
End Module
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MemberClashesWithSynth6, "ObjEvent").WithArguments("WithEvents variable", "ObjEvent", "event", "Obj", "module", "M1"))
End Sub
<Fact>
Public Sub BC31061ERR_MemberClashesWithSynth6_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Function get_p()
Return Nothing
End Function
Shared Function set_p()
Return Nothing
End Function
Shared Sub GET_Q()
End Sub
Sub SET_Q()
End Sub
Dim get_R
Shared set_R
Shared Property get_s
Property set_s
Class get_T
End Class
Structure set_T
End Structure
Enum get_U
X
End Enum
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property u
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: function 'get_p' conflicts with a member implicitly declared for property 'P' in class 'C'.
Function get_p()
~~~~~
BC31061: function 'set_p' conflicts with a member implicitly declared for property 'P' in class 'C'.
Shared Function set_p()
~~~~~
BC31061: sub 'GET_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Shared Sub GET_Q()
~~~~~
BC31061: sub 'SET_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Sub SET_Q()
~~~~~
BC31061: variable 'get_R' conflicts with a member implicitly declared for property 'r' in class 'C'.
Dim get_R
~~~~~
BC31061: variable 'set_R' conflicts with a member implicitly declared for property 'r' in class 'C'.
Shared set_R
~~~~~
BC31061: property 'get_s' conflicts with a member implicitly declared for property 's' in class 'C'.
Shared Property get_s
~~~~~
BC31061: property 'set_s' conflicts with a member implicitly declared for property 's' in class 'C'.
Property set_s
~~~~~
BC31061: class 'get_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Class get_T
~~~~~
BC31061: structure 'set_T' conflicts with a member implicitly declared for property 'T' in class 'C'.
Structure set_T
~~~~~
BC31061: enum 'get_U' conflicts with a member implicitly declared for property 'u' in class 'C'.
Enum get_U
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31061ERR_MemberClashesWithSynth6_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Private get_P
Private set_P
Private get_Q
Private set_Q
Private get_R
Private set_R
Property P
Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
ReadOnly Property Q
Get
Return Nothing
End Get
End Property
WriteOnly Property R
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: variable 'get_P' conflicts with a member implicitly declared for property 'P' in class 'C'.
Private get_P
~~~~~
BC31061: variable 'set_P' conflicts with a member implicitly declared for property 'P' in class 'C'.
Private set_P
~~~~~
BC31061: variable 'get_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Private get_Q
~~~~~
BC31061: variable 'set_R' conflicts with a member implicitly declared for property 'R' in class 'C'.
Private set_R
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31061ERR_MemberClashesWithSynth6_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Function _p()
Return Nothing
End Function
Shared Sub _Q()
End Sub
Dim _r
Shared _S
Shared Property _t
Property _U
Class _v
End Class
Structure _W
End Structure
Enum _x
X
End Enum
Property P
Shared Property Q
Property r
Shared Property s
Property T
Shared Property U
Property v
Shared Property w
Property X
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31061: function '_p' conflicts with a member implicitly declared for property 'P' in class 'C'.
Function _p()
~~
BC31061: sub '_Q' conflicts with a member implicitly declared for property 'Q' in class 'C'.
Shared Sub _Q()
~~
BC31061: variable '_r' conflicts with a member implicitly declared for property 'r' in class 'C'.
Dim _r
~~
BC31061: variable '_S' conflicts with a member implicitly declared for property 's' in class 'C'.
Shared _S
~~
BC31061: property '_t' conflicts with a member implicitly declared for property 'T' in class 'C'.
Shared Property _t
~~
BC31061: property '_U' conflicts with a member implicitly declared for property 'U' in class 'C'.
Property _U
~~
BC31061: class '_v' conflicts with a member implicitly declared for property 'v' in class 'C'.
Class _v
~~
BC31061: structure '_W' conflicts with a member implicitly declared for property 'w' in class 'C'.
Structure _W
~~
BC31061: enum '_x' conflicts with a member implicitly declared for property 'X' in class 'C'.
Enum _x
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31063ERR_SetHasOnlyOneParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SetHasOnlyOneParam">
<file name="a.vb"><![CDATA[
Module M
WriteOnly Property P(ByVal i As Integer) As Integer
Set(x As Integer, ByVal Value As Integer)
End Set
End Property
WriteOnly Property Q()
Set() ' No error
If value Is Nothing Then
End If
End Set
End Property
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31063: 'Set' method cannot have more than one parameter.
Set(x As Integer, ByVal Value As Integer)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31064ERR_SetValueNotPropertyType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SetValueNotPropertyType">
<file name="a.vb"><![CDATA[
' Implicit property type and implicit set argument type (same)
Structure A
WriteOnly Property P%
Set(ap%) ' no error
End Set
End Property
WriteOnly Property Q&
Set(aq&) ' no error
End Set
End Property
WriteOnly Property R@
Set(ar@) ' no error
End Set
End Property
WriteOnly Property S!
Set(as!) ' no error
End Set
End Property
WriteOnly Property T#
Set(at#) ' no error
End Set
End Property
WriteOnly Property U$
Set(au$) ' no error
End Set
End Property
End Structure
' Implicit property type and explicit set argument type (same)
Class B
WriteOnly Property P%
Set(bp As Integer) ' no error
End Set
End Property
WriteOnly Property Q&
Set(bq As Long) ' no error
End Set
End Property
WriteOnly Property R@
Set(br As Decimal) ' no error
End Set
End Property
WriteOnly Property S!
Set(ba As Single) ' no error
End Set
End Property
WriteOnly Property T#
Set(bt As Double) ' no error
End Set
End Property
WriteOnly Property U$
Set(bu As String) ' no error
End Set
End Property
End Class
' Explicit property type and explicit set argument type (same)
Structure C
WriteOnly Property P As Integer
Set(cp As Integer) ' no error
End Set
End Property
WriteOnly Property Q As Long
Set(cq As Long) ' no error
End Set
End Property
WriteOnly Property R As Decimal
Set(cr As Decimal) ' no error
End Set
End Property
WriteOnly Property S As Single
Set(cs As Single) ' no error
End Set
End Property
WriteOnly Property T As Double
Set(ct As Double) ' no error
End Set
End Property
WriteOnly Property U As String
Set(cu As String) ' no error
End Set
End Property
End Structure
' Implicit property type and implicit set argument type (different)
Class D
WriteOnly Property P%
Set(ap&) ' BC31064
End Set
End Property
WriteOnly Property Q&
Set(aq@) ' BC31064
End Set
End Property
WriteOnly Property R@
Set(ar!) ' BC31064
End Set
End Property
WriteOnly Property S!
Set(as#) ' BC31064
End Set
End Property
WriteOnly Property T#
Set(at$) ' BC31064
End Set
End Property
WriteOnly Property U$
Set(au%) ' BC31064
End Set
End Property
End Class
' Implicit property type and explicit set argument type (different)
Structure E
WriteOnly Property P%
Set(bp As Decimal) ' BC31064
End Set
End Property
WriteOnly Property Q&
Set(bq As Single) ' BC31064
End Set
End Property
WriteOnly Property R@
Set(br As Double) ' BC31064
End Set
End Property
WriteOnly Property S!
Set(ba As String) ' BC31064
End Set
End Property
WriteOnly Property T#
Set(bt As Integer) ' BC31064
End Set
End Property
WriteOnly Property U$
Set(bu As Long) ' BC31064
End Set
End Property
End Structure
' Explicit property type and explicit set argument type (different)
Class F
WriteOnly Property P As Integer
Set(cp As Single) ' BC31064
End Set
End Property
WriteOnly Property Q As Long
Set(cq As Double) ' BC31064
End Set
End Property
WriteOnly Property R As Decimal
Set(cr As String) ' BC31064
End Set
End Property
WriteOnly Property S As Single
Set(cs As Integer) ' BC31064
End Set
End Property
WriteOnly Property T As Double
Set(ct As Long) ' BC31064
End Set
End Property
WriteOnly Property U As String
Set(cu As Decimal) ' BC31064
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ap&) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(aq@) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ar!) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(as#) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(at$) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(au%) ' BC31064
~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bp As Decimal) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bq As Single) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(br As Double) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ba As String) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bt As Integer) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(bu As Long) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cp As Single) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cq As Double) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cr As String) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cs As Integer) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ct As Long) ' BC31064
~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(cu As Decimal) ' BC31064
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31065ERR_SetHasToBeByVal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SetHasToBeByVal1">
<file name="a.vb"><![CDATA[
Class C
WriteOnly Property P
Set(ByRef value)
End Set
End Property
WriteOnly Property Q
Set(ByVal ParamArray value())
End Set
End Property
WriteOnly Property R As Integer()
Set(ParamArray value As Integer())
End Set
End Property
WriteOnly Property S
Set(Optional value = Nothing)
End Set
End Property
WriteOnly Property T
Set(ByVal value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31065: 'Set' parameter cannot be declared 'ByRef'.
Set(ByRef value)
~~~~~
BC31065: 'Set' parameter cannot be declared 'ParamArray'.
Set(ByVal ParamArray value())
~~~~~~~~~~
BC31064: 'Set' parameter must have the same type as the containing property.
Set(ByVal ParamArray value())
~~~~~
BC31065: 'Set' parameter cannot be declared 'ParamArray'.
Set(ParamArray value As Integer())
~~~~~~~~~~
BC31065: 'Set' parameter cannot be declared 'Optional'.
Set(Optional value = Nothing)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31067ERR_StructureCantUseProtected()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="StructureCantUseProtected">
<file name="a.vb"><![CDATA[
Structure S
Protected Sub New(o)
End Sub
Protected Friend Sub New(x, y)
End Sub
Protected Sub M()
End Sub
Protected Friend Function F()
Return Nothing
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Sub New(o)
~~~~~~~~~
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Friend Sub New(x, y)
~~~~~~~~~~~~~~~~
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Sub M()
~~~~~~~~~
BC31067: Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.
Protected Friend Function F()
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31068ERR_BadInterfaceDelegateSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceDelegateSpecifier1">
<file name="a.vb"><![CDATA[
Interface i1
private Delegate Sub goo
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31068: Delegate in an interface cannot be declared 'private'.
private Delegate Sub goo
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31069ERR_BadInterfaceEnumSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceEnumSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
Public Enum E
ONE
End Enum
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31069: Enum in an interface cannot be declared 'Public'.
Public Enum E
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31070ERR_BadInterfaceClassSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceClassSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
Interface I2
Protected Class C1
End Class
Friend Class C2
End Class
End Interface
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31070: Class in an interface cannot be declared 'Protected'.
Protected Class C1
~~~~~~~~~
BC31070: Class in an interface cannot be declared 'Friend'.
Friend Class C2
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31071ERR_BadInterfaceStructSpecifier1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadInterfaceStructSpecifier1">
<file name="a.vb"><![CDATA[
Interface I1
Public Structure S1
End Structure
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31071: Structure in an interface cannot be declared 'Public'.
Public Structure S1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31075ERR_UseOfObsoleteSymbolNoMessage1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoleteSymbolNoMessage1">
<file name="a.vb"><![CDATA[
Imports System
<Obsolete(Nothing, True)> Interface I1
End Interface
Class class1
Implements I1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31075: 'I1' is obsolete.
Implements I1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31083ERR_ModuleMemberCantImplement()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ModuleMemberCantImplement">
<file name="a.vb"><![CDATA[
Module class1
Interface I1
Sub goo()
End Interface
'COMPILEERROR: BC31083, "Implements"
Public Sub goo() Implements I1.goo
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31083: Members in a Module cannot implement interface members.
Public Sub goo() Implements I1.goo
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31084ERR_EventDelegatesCantBeFunctions()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventDelegatesCantBeFunctions">
<file name="a.vb"><![CDATA[
Imports System
Class A
Event X As Func(Of String)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31084: Events cannot be declared with a delegate type that has a return type.
Event X As Func(Of String)
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31086ERR_CantOverride4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverride4">
<file name="a.vb"><![CDATA[
Class C1
Public Sub F1()
End Sub
End Class
Class B
Inherits C1
Public Overrides Sub F1()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31086: 'Public Overrides Sub F1()' cannot override 'Public Sub F1()' because it is not declared 'Overridable'.
Public Overrides Sub F1()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
Private Shared ReadOnly s_typeWithMixedProperty As String = <![CDATA[
.class public auto ansi beforefieldinit Base_VirtGet_Set
extends [mscorlib]System.Object
{
.method public hidebysig specialname newslot virtual
instance int32 get_Prop() cil managed
{
// Code size 2 (0x2)
.maxstack 8
ldstr "Base_VirtGet_Set.Get"
call void [mscorlib]System.Console::WriteLine(string)
IL_0000: ldc.i4.1
IL_0001: ret
}
.method public hidebysig specialname
instance void set_Prop(int32 'value') cil managed
{
// Code size 1 (0x1)
ldstr "Base_VirtGet_Set.Set"
call void [mscorlib]System.Console::WriteLine(string)
.maxstack 8
IL_0000: ret
}
.property instance int32 Prop()
{
.get instance int32 Base_VirtGet_Set::get_Prop()
.set instance void Base_VirtGet_Set::set_Prop(int32)
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
.class public auto ansi beforefieldinit Base_Get_VirtSet
extends [mscorlib]System.Object
{
.method public hidebysig specialname
instance int32 get_Prop() cil managed
{
// Code size 2 (0x2)
.maxstack 8
ldstr "Base_Get_VirtSet.Get"
call void [mscorlib]System.Console::WriteLine(string)
IL_0000: ldc.i4.1
IL_0001: ret
}
.method public hidebysig specialname newslot virtual
instance void set_Prop(int32 'value') cil managed
{
// Code size 1 (0x1)
.maxstack 8
ldstr "Base_Get_VirtSet.Set"
call void [mscorlib]System.Console::WriteLine(string)
IL_0000: ret
}
.property instance int32 Prop()
{
.get instance int32 Base_Get_VirtSet::get_Prop()
.set instance void Base_Get_VirtSet::set_Prop(int32)
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
]]>.Value.Replace(vbLf, vbCrLf)
<WorkItem(528982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528982")>
<Fact()>
Public Sub BC31086ERR_CantOverride5a()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="CantOverride5a">
<file name="a.vb"><![CDATA[
Class VBDerived
Inherits Base_Get_VirtSet
Public Overrides Property Prop As Integer
Get
System.Console.WriteLine("VBDerived.Get")
Return MyBase.Prop
End Get
Set(value As Integer)
System.Console.WriteLine("VBDerived.Set")
MyBase.Prop = value
End Set
End Property
Shared Sub Main()
Dim o As Base_Get_VirtSet
o = New Base_Get_VirtSet()
o.Prop = o.Prop
o = New VBDerived()
o.Prop = o.Prop
End Sub
End Class
]]></file>
</compilation>, s_typeWithMixedProperty, options:=TestOptions.DebugExe)
' There are no Errors, but getter is actually not overridden!!!
Dim validator = Sub(m As ModuleSymbol)
Dim p1 = m.GlobalNamespace.GetMember(Of PropertySymbol)("VBDerived.Prop")
Assert.True(p1.IsOverrides)
Dim baseP1 As PropertySymbol = p1.OverriddenProperty
Assert.True(baseP1.IsOverridable)
Assert.False(baseP1.GetMethod.IsOverridable)
Assert.True(baseP1.SetMethod.IsOverridable)
Dim p1Get = p1.GetMethod
Dim p1Set = p1.SetMethod
Assert.True(p1Get.IsOverrides)
Assert.Same(baseP1.GetMethod, p1Get.OverriddenMethod)
Assert.True(p1Set.IsOverrides)
Assert.Same(baseP1.SetMethod, p1Set.OverriddenMethod)
End Sub
CompileAndVerify(compilation1, expectedOutput:=
"Base_Get_VirtSet.Get
Base_Get_VirtSet.Set
Base_Get_VirtSet.Get
VBDerived.Set
Base_Get_VirtSet.Set", sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
<WorkItem(528982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528982")>
<Fact()>
Public Sub BC31086ERR_CantOverride5b()
Dim compilation1 = CompilationUtils.CreateCompilationWithCustomILSource(
<compilation name="CantOverride5b">
<file name="a.vb"><![CDATA[
Class VBDerived
Inherits Base_VirtGet_Set
Public Overrides Property Prop As Integer
Get
System.Console.WriteLine("VBDerived.Get")
Return MyBase.Prop
End Get
Set(value As Integer)
System.Console.WriteLine("VBDerived.Set")
MyBase.Prop = value
End Set
End Property
Shared Sub Main()
Dim o As Base_VirtGet_Set
o = New Base_VirtGet_Set()
o.Prop = o.Prop
o = New VBDerived()
o.Prop = o.Prop
End Sub
End Class
]]></file>
</compilation>, s_typeWithMixedProperty, options:=TestOptions.DebugExe)
' There are no Errors, but setter is actually not overridden!!!
Dim validator = Sub(m As ModuleSymbol)
Dim p1 = m.GlobalNamespace.GetMember(Of PropertySymbol)("VBDerived.Prop")
Assert.True(p1.IsOverrides)
Dim baseP1 As PropertySymbol = p1.OverriddenProperty
Assert.True(baseP1.IsOverridable)
Assert.True(baseP1.GetMethod.IsOverridable)
Assert.False(baseP1.SetMethod.IsOverridable)
Dim p1Get = p1.GetMethod
Dim p1Set = p1.SetMethod
Assert.True(p1Get.IsOverrides)
Assert.Same(baseP1.GetMethod, p1Get.OverriddenMethod)
Assert.True(p1Set.IsOverrides)
Assert.Same(baseP1.SetMethod, p1Set.OverriddenMethod)
End Sub
CompileAndVerify(compilation1, expectedOutput:=
"Base_VirtGet_Set.Get
Base_VirtGet_Set.Set
VBDerived.Get
Base_VirtGet_Set.Get
Base_VirtGet_Set.Set", sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
<Fact()>
Public Sub BC31087ERR_CantSpecifyArraysOnBoth()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CantSpecifyArraysOnBoth">
<file name="a.vb"><![CDATA[
Module M
Sub Goo(ByVal x() As String())
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31087: Array modifiers cannot be specified on both a variable and its type.
Sub Goo(ByVal x() As String())
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31087ERR_CantSpecifyArraysOnBoth_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantSpecifyArraysOnBoth">
<file name="a.vb"><![CDATA[
Class C
Public Shared Sub Main()
Dim a()() As Integer = nothing
For Each x() As Integer() In a
Next
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected><![CDATA[
BC31087: Array modifiers cannot be specified on both a variable and its type.
For Each x() As Integer() In a
~~~~~~~~~
BC30332: Value of type 'Integer()' cannot be converted to 'Integer()()' because 'Integer' is not derived from 'Integer()'.
For Each x() As Integer() In a
~
]]></expected>)
End Sub
<WorkItem(540876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540876")>
<Fact>
Public Sub BC31088ERR_NotOverridableRequiresOverrides()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NotOverridableRequiresOverrides">
<file name="a.vb"><![CDATA[
Class C1
NotOverridable Sub Goo()
End Sub
Public NotOverridable Property F As Integer
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
NotOverridable Sub Goo()
~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
Public NotOverridable Property F As Integer
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31089ERR_PrivateTypeOutsideType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PrivateTypeOutsideType">
<file name="a.vb"><![CDATA[
Namespace ns1
Private Module Mod1
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31089: Types declared 'Private' must be inside another type.
Private Module Mod1
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31099ERR_BadPropertyAccessorFlags()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags">
<file name="a.vb"><![CDATA[
Class C
Property P
Static Get
Return Nothing
End Get
Shared Set
End Set
End Property
Property Q
Partial Get
Return Nothing
End Get
Default Set
End Set
End Property
Property R
MustInherit Get
Return Nothing
End Get
NotInheritable Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31099: Property accessors cannot be declared 'Static'.
Static Get
~~~~~~
BC31099: Property accessors cannot be declared 'Shared'.
Shared Set
~~~~~~
BC31099: Property accessors cannot be declared 'Partial'.
Partial Get
~~~~~~~
BC31099: Property accessors cannot be declared 'Default'.
Default Set
~~~~~~~
BC31099: Property accessors cannot be declared 'MustInherit'.
MustInherit Get
~~~~~~~~~~~
BC31099: Property accessors cannot be declared 'NotInheritable'.
NotInheritable Set
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31100ERR_BadPropertyAccessorFlagsRestrict()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlagsRestrict">
<file name="a.vb"><![CDATA[
Class C
Public Property P1
Get
Return Nothing
End Get
Public Set(ByVal value) ' P1 BC31100
End Set
End Property
Public Property P2
Get
Return Nothing
End Get
Friend Set(ByVal value)
End Set
End Property
Public Property P3
Get
Return Nothing
End Get
Protected Set(ByVal value)
End Set
End Property
Public Property P4
Get
Return Nothing
End Get
Protected Friend Set(ByVal value)
End Set
End Property
Public Property P5
Get
Return Nothing
End Get
Private Set(ByVal value)
End Set
End Property
Friend Property Q1
Public Get ' Q1 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q2
Friend Get ' Q2 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q3
Protected Get ' Q3 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q4
Protected Friend Get ' Q4 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Friend Property Q5
Private Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Protected Property R1
Get
Return Nothing
End Get
Public Set(ByVal value) ' R1 BC31100
End Set
End Property
Protected Property R2
Get
Return Nothing
End Get
Friend Set(ByVal value) ' R2 BC31100
End Set
End Property
Protected Property R3
Get
Return Nothing
End Get
Protected Set(ByVal value) ' R3 BC31100
End Set
End Property
Protected Property R4
Get
Return Nothing
End Get
Protected Friend Set(ByVal value) ' R4 BC31100
End Set
End Property
Protected Property R5
Get
Return Nothing
End Get
Private Set(ByVal value)
End Set
End Property
Protected Friend Property S1
Get
Return Nothing
End Get
Public Set(ByVal value) ' S1 BC31100
End Set
End Property
Protected Friend Property S2
Get
Return Nothing
End Get
Friend Set(ByVal value)
End Set
End Property
Protected Friend Property S3
Get
Return Nothing
End Get
Protected Set(ByVal value)
End Set
End Property
Protected Friend Property S4
Get
Return Nothing
End Get
Protected Friend Set(ByVal value) ' S4 BC31100
End Set
End Property
Protected Friend Property S5
Get
Return Nothing
End Get
Private Set(ByVal value)
End Set
End Property
Private Property T1
Public Get ' T1 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T2
Friend Get ' T2 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T3
Protected Get ' T3 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T4
Protected Friend Get ' T4 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Private Property T5
Private Get ' T5 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U1
Public Get ' U1 BC31100
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U2
Friend Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U3
Protected Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U4
Protected Friend Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
Property U5
Private Get
Return Nothing
End Get
Set(ByVal value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Set(ByVal value) ' P1 BC31100
~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Get ' Q1 BC31100
~~~~~~
BC31100: Access modifier 'Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Friend Get ' Q2 BC31100
~~~~~~
BC31100: Access modifier 'Protected' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Get ' Q3 BC31100
~~~~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Get ' Q4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Set(ByVal value) ' R1 BC31100
~~~~~~
BC31100: Access modifier 'Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Friend Set(ByVal value) ' R2 BC31100
~~~~~~
BC31100: Access modifier 'Protected' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Set(ByVal value) ' R3 BC31100
~~~~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Set(ByVal value) ' R4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Set(ByVal value) ' S1 BC31100
~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Set(ByVal value) ' S4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Get ' T1 BC31100
~~~~~~
BC31100: Access modifier 'Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Friend Get ' T2 BC31100
~~~~~~
BC31100: Access modifier 'Protected' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Get ' T3 BC31100
~~~~~~~~~
BC31100: Access modifier 'Protected Friend' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Protected Friend Get ' T4 BC31100
~~~~~~~~~~~~~~~~
BC31100: Access modifier 'Private' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Private Get ' T5 BC31100
~~~~~~~
BC31100: Access modifier 'Public' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.
Public Get ' U1 BC31100
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31101ERR_OnlyOneAccessorForGetSet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOneAccessorForGetSet">
<file name="a.vb"><![CDATA[
Class C
Property P
Private Get
Return Nothing
End Get
Protected Set(value)
End Set
End Property
Property Q
Friend Set
End Set
Friend Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31101: Access modifier can only be applied to either 'Get' or 'Set', but not both.
Protected Set(value)
~~~~~~~~~~~~~~~~~~~~
BC31101: Access modifier can only be applied to either 'Get' or 'Set', but not both.
Friend Get
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31104ERR_WriteOnlyNoAccessorFlag()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
WriteOnly Property Goo(ByVal x As Integer) As Integer
Private Set(ByVal value As Integer)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31104: 'WriteOnly' properties cannot have an access modifier on 'Set'.
Private Set(ByVal value As Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31105ERR_ReadOnlyNoAccessorFlag()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C1
ReadOnly Property Goo(ByVal x As Integer) As Integer
Protected Get
Return 1
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31105: 'ReadOnly' properties cannot have an access modifier on 'Get'.
Protected Get
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31106ERR_BadPropertyAccessorFlags1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags1">
<file name="a.vb"><![CDATA[
Class A
Overridable Property P
Overridable Property Q
Get
Return Nothing
End Get
Protected Set
End Set
End Property
End Class
Class B
Inherits A
NotOverridable Overrides Property P
Get
Return Nothing
End Get
Private Set
End Set
End Property
Public Overrides Property Q
Get
Return Nothing
End Get
Protected Set
End Set
End Property
End Class
MustInherit Class C
MustOverride Property P
End Class
Class D
Inherits C
NotOverridable Overrides Property P
Private Get
Return Nothing
End Get
Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31106: Property accessors cannot be declared 'Private' in a 'NotOverridable' property.
Private Set
~~~~~~~
BC30266: 'Private NotOverridable Overrides Property Set P(Value As Object)' cannot override 'Public Overridable Property Set P(AutoPropertyValue As Object)' because they have different access levels.
Private Set
~~~
BC31106: Property accessors cannot be declared 'Private' in a 'NotOverridable' property.
Private Get
~~~~~~~
BC30266: 'Private NotOverridable Overrides Property Get P() As Object' cannot override 'Public MustOverride Property Get P() As Object' because they have different access levels.
Private Get
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31107ERR_BadPropertyAccessorFlags2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags2">
<file name="a.vb"><![CDATA[
Class C
Default Property P(o)
Private Get
Return Nothing
End Get
Set
End Set
End Property
End Class
Structure S
Default Property P(x, y)
Get
Return Nothing
End Get
Private Set
End Set
End Property
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31107: Property accessors cannot be declared 'Private' in a 'Default' property.
Private Get
~~~~~~~
BC31107: Property accessors cannot be declared 'Private' in a 'Default' property.
Private Set
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31108ERR_BadPropertyAccessorFlags3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadPropertyAccessorFlags3">
<file name="a.vb"><![CDATA[
Class C
Overridable Property P
Private Get
Return Nothing
End Get
Set
End Set
End Property
Overridable Property Q
Get
Return Nothing
End Get
Private Set
End Set
End Property
Overridable Property R
Protected Get
Return Nothing
End Get
Set
End Set
End Property
Overridable Property S
Get
Return Nothing
End Get
Friend Set
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31108: Property cannot be declared 'Overridable' because it contains a 'Private' accessor.
Overridable Property P
~~~~~~~~~~~
BC31108: Property cannot be declared 'Overridable' because it contains a 'Private' accessor.
Overridable Property Q
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31127ERR_DuplicateAddHandlerDef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateAddHandlerDef">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31127: 'AddHandler' is already declared.
AddHandler(ByVal value As EventHandler)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31128ERR_DuplicateRemoveHandlerDef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateRemoveHandlerDef">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31128: 'RemoveHandler' is already declared.
RemoveHandler(ByVal value As EventHandler)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31129ERR_DuplicateRaiseEventDef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateRaiseEventDef">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31129: 'RaiseEvent' is already declared.
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31130ERR_MissingAddHandlerDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MissingAddHandlerDef1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31130: 'AddHandler' definition missing for event 'Public Event Click As EventHandler'.
Public Custom Event Click As EventHandler
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31131ERR_MissingRemoveHandlerDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MissingRemoveHandlerDef1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31131: 'RemoveHandler' definition missing for event 'Public Event Click As EventHandler'.
Public Custom Event Click As EventHandler
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31132ERR_MissingRaiseEventDef1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MissingRaiseEventDef1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31132: 'RaiseEvent' definition missing for event 'Public Event Click As EventHandler'.
Public Custom Event Click As EventHandler
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31133ERR_EventAddRemoveHasOnlyOneParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventAddRemoveHasOnlyOneParam">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler()
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31133: 'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.
AddHandler()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31134ERR_EventAddRemoveByrefParamIllegal()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventAddRemoveByrefParamIllegal">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByRef value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31134: 'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.
RemoveHandler(ByRef value As EventHandler)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31136ERR_AddRemoveParamNotEventType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AddRemoveParamNotEventType">
<file name="a.vb"><![CDATA[
Option Strict Off
Imports System
Public Class M
Custom Event x As Action
AddHandler(ByVal value As Action(Of Integer))
End AddHandler
RemoveHandler(ByVal value)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.
AddHandler(ByVal value As Action(Of Integer))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31136: 'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.
RemoveHandler(ByVal value)
~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31137ERR_RaiseEventShapeMismatch1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="RaiseEventShapeMismatch1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByRef sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31137: 'RaiseEvent' method must have the same signature as the containing event's delegate type 'EventHandler'.
RaiseEvent(ByRef sender As Object, ByVal e As EventArgs)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31138ERR_EventMethodOptionalParamIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventMethodOptionalParamIllegal1">
<file name="a.vb"><![CDATA[
Imports System
Public NotInheritable Class ReliabilityOptimizedControl
Public Custom Event Click As EventHandler
AddHandler(Optional ByVal value As EventHandler = Nothing)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31138: 'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared 'Optional'.
AddHandler(Optional ByVal value As EventHandler = Nothing)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31142ERR_ObsoleteInvalidOnEventMember()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ObsoleteInvalidOnEventMember">
<file name="a.vb"><![CDATA[
Imports System
Public Class C1
Custom Event x As Action
AddHandler(ByVal value As Action)
End AddHandler
RemoveHandler(ByVal value As Action)
End RemoveHandler
<Obsolete()>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.
<Obsolete()>
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31400ERR_BadStaticLocalInStruct()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadStaticLocalInStruct">
<file name="a.vb"><![CDATA[
Structure S
Sub Goo()
Static x As Integer = 1
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31400: Local variables within methods of structures cannot be declared 'Static'.
Static x As Integer = 1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31400ERR_BadStaticLocalInStruct2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadStaticLocalInStruct2">
<file name="a.vb"><![CDATA[
Structure S
Sub Goo()
Static Static x As Integer
End Sub
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31400: Local variables within methods of structures cannot be declared 'Static'.
Static Static x As Integer
~~~~~~
BC30178: Specifier is duplicated.
Static Static x As Integer
~~~~~~
BC42024: Unused local variable: 'x'.
Static Static x As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BadLocalspecifiers()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BC31400ERR_BadLocalspecifiers">
<file name="a.vb"><![CDATA[
Class S
Sub Goo()
Static Static a As Integer
Static Dim Dim b As Integer
Static Const Dim c As Integer
Private d As Integer
Private Private e As Integer
Private Const f As Integer
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30178: Specifier is duplicated.
Static Static a As Integer
~~~~~~
BC42024: Unused local variable: 'a'.
Static Static a As Integer
~
BC30178: Specifier is duplicated.
Static Dim Dim b As Integer
~~~
BC42024: Unused local variable: 'b'.
Static Dim Dim b As Integer
~
BC30246: 'Dim' is not valid on a local constant declaration.
Static Const Dim c As Integer
~~~
BC30438: Constants must have a value.
Static Const Dim c As Integer
~
BC30247: 'Private' is not valid on a local variable declaration.
Private d As Integer
~~~~~~~
BC42024: Unused local variable: 'd'.
Private d As Integer
~
BC30247: 'Private' is not valid on a local variable declaration.
Private Private e As Integer
~~~~~~~
BC30247: 'Private' is not valid on a local variable declaration.
Private Private e As Integer
~~~~~~~
BC42024: Unused local variable: 'e'.
Private Private e As Integer
~
BC30247: 'Private' is not valid on a local variable declaration.
Private Const f As Integer
~~~~~~~
BC30438: Constants must have a value.
Private Const f As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31401ERR_DuplicateLocalStatic1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalStatic1">
<file name="a.vb"><![CDATA[
Module M
Sub Main()
If True Then
Static x = 1
End If
If True Then
Static x = 1
End If
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31401: Static local variable 'x' is already declared.
Static x = 1
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31403ERR_ImportAliasConflictsWithType2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ImportAliasConflictsWithType2">
<file name="a.vb"><![CDATA[
Imports System = System
Module M
Sub Main()
System.Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31403: Imports alias 'System' conflicts with 'System' declared in the root namespace.
Imports System = System
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31404ERR_CantShadowAMustOverride1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantShadowAMustOverride1">
<file name="a.vb"><![CDATA[
MustInherit Class A
MustOverride Sub Goo(ByVal x As Integer)
End Class
MustInherit Class B
Inherits A
Shadows Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31404: 'Public Sub Goo()' cannot shadow a method declared 'MustOverride'.
Shadows Sub Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31407ERR_MultipleEventImplMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleEventImplMismatch3">
<file name="a.vb"><![CDATA[
Interface I1
Event evtTest1()
Event evtTest2()
End Interface
Class C1
Implements I1
Event evtTest3() Implements I1.evtTest1, I1.evtTest2
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31407: Event 'Public Event evtTest3 As I1.evtTest1EventHandler' cannot implement event 'I1.Event evtTest2()' because its delegate type does not match the delegate type of another event implemented by 'Public Event evtTest3 As I1.evtTest1EventHandler'.
Event evtTest3() Implements I1.evtTest1, I1.evtTest2
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
CompilationUtils.AssertTheseEmitDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_0()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Partial NotInheritable Class C1
End Class
Partial MustInherit Class C1
End Class
Partial MustInherit NotInheritable Class C1
End Class
Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30926: 'MustInherit' cannot be specified for partial type 'C1' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.
Partial MustInherit Class C1
~~
BC31408: 'MustInherit' and 'NotInheritable' cannot be combined.
Partial MustInherit NotInheritable Class C1
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538931")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit NotInheritable Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'MustInherit' and 'NotInheritable' cannot be combined.
MustInherit NotInheritable Class C1
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(538931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538931")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A1
Private Overridable Sub scen1()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Private' and 'Overridable' cannot be combined.
Private Overridable Sub scen1()
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb"><![CDATA[
Class C
ReadOnly WriteOnly Property P
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
Structure S
WriteOnly ReadOnly Property Q
Get
Return Nothing
End Get
Set
End Set
End Property
End Structure
Interface I
ReadOnly WriteOnly Property R
End Interface
Class D
Private Overridable Property S
Overridable Private Property T
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30635: 'ReadOnly' and 'WriteOnly' cannot be combined.
ReadOnly WriteOnly Property P
~~~~~~~~~
BC30022: Properties declared 'ReadOnly' cannot have a 'Set'.
Set
~~~
BC30635: 'ReadOnly' and 'WriteOnly' cannot be combined.
WriteOnly ReadOnly Property Q
~~~~~~~~
BC30023: Properties declared 'WriteOnly' cannot have a 'Get'.
Get
~~~
BC30635: 'ReadOnly' and 'WriteOnly' cannot be combined.
ReadOnly WriteOnly Property R
~~~~~~~~~
BC31408: 'Private' and 'Overridable' cannot be combined.
Private Overridable Property S
~~~~~~~~~~~
BC31408: 'Private' and 'Overridable' cannot be combined.
Overridable Private Property T
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(541025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541025")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A1
Private MustOverride Sub scen1()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Private' and 'MustOverride' cannot be combined.
Private MustOverride Sub scen1()
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(542159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542159")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Infer On
Module M1
Sub Goo()
End Sub
End Module
MustInherit Class C1
MustOverride Sub goo()
Dim s = (New C2)
End Class
Class C2
Inherits C1
Overrides Shadows Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Overrides' and 'Shadows' cannot be combined.
Overrides Shadows Sub goo()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(837983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837983")>
<Fact>
Public Sub BC31408ERR_BadSpecifierCombo2_6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Module Module1
Sub main()
End Sub
End Module
Public Class Cls
Public ValueOfProperty1 As IEnumerable(Of String)
'COMPILEERROR: BC31408, "Iterator"
Public WriteOnly Iterator Property WriteOnlyPro1() As IEnumerable(Of String)
Set(value As IEnumerable(Of String))
ValueOfProperty1 = value
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Iterator' and 'WriteOnly' cannot be combined.
Public WriteOnly Iterator Property WriteOnlyPro1() As IEnumerable(Of String)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(837993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837993")>
<Fact>
Public Sub BC36938ERR_BadIteratorReturn_Property()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
' Bug51817: Incorrect Iterator Modifier in Source Code Causes VBC to exit incorrectly when Msbuild Project
Public Class Scenario2
Implements IEnumerator(Of Integer)
Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
Return True
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
End Sub
Public ReadOnly Iterator Property Current As Integer Implements IEnumerator(Of Integer).Current
'COMPILEERROR: BC36938 ,"Get"
Get
End Get
End Property
Public ReadOnly Iterator Property Current1 As Object Implements IEnumerator.Current
'COMPILEERROR: BC36938 ,"Get"
Get
End Get
End Property
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
End If
End If
Me.disposedValue = True
End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public ReadOnly Iterator Property Current As Integer Implements IEnumerator(Of Integer).Current
~~~~~~~
BC36938: Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.
Public ReadOnly Iterator Property Current1 As Object Implements IEnumerator.Current
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31409ERR_MustBeOverloads2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class C1
Overloads Sub goo(ByVal i As Integer)
End Sub
Sub goo(ByVal s As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: sub 'goo' must be declared 'Overloads' because another 'goo' is declared 'Overloads' or 'Overrides'.
Sub goo(ByVal s As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31409ERR_MustBeOverloads2_Mixed_Properties_And_Methods()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class OverloadedPropertiesBase
Overridable Overloads ReadOnly Property Prop(x As Integer) As String
Get
Return Nothing
End Get
End Property
Overridable ReadOnly Property Prop(x As String) As String
Get
Return Nothing
End Get
End Property
Overridable Overloads Function Prop(x As String) As String
Return Nothing
End Function
Shadows Function Prop(x As Integer) As Integer
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: property 'Prop' must be declared 'Overloads' because another 'Prop' is declared 'Overloads' or 'Overrides'.
Overridable ReadOnly Property Prop(x As String) As String
~~~~
BC30260: 'Prop' is already declared as 'Public Overridable Overloads ReadOnly Property Prop(x As Integer) As String' in this class.
Overridable Overloads Function Prop(x As String) As String
~~~~
BC30260: 'Prop' is already declared as 'Public Overridable Overloads ReadOnly Property Prop(x As Integer) As String' in this class.
Shadows Function Prop(x As Integer) As Integer
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31409ERR_MustBeOverloads2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustBeOverloads2">
<file name="a.vb"><![CDATA[
Class Base
Sub Method(x As Integer)
End Sub
Overloads Sub Method(x As String)
End Sub
End Class
Partial Class Derived1
Inherits Base
Shadows Sub Method(x As String)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31409: sub 'Method' must be declared 'Overloads' because another 'Method' is declared 'Overloads' or 'Overrides'.
Sub Method(x As Integer)
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' spec changed in Roslyn
<WorkItem(527642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527642")>
<Fact>
Public Sub BC31410ERR_CantOverloadOnMultipleInheritance()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantOverloadOnMultipleInheritance">
<file name="a.vb"><![CDATA[
Interface IA
Overloads Sub Goo(ByVal x As Integer)
End Interface
Interface IB
Overloads Sub Goo(ByVal x As String)
End Interface
Interface IC
Inherits IA, IB
Overloads Sub Goo()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31411ERR_MustOverridesInClass1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Class C1
MustOverride Sub goo()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31411: 'C1' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Public Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31411ERR_MustOverridesInClass1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
MustOverride Property P
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31411: 'C' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Class C
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31413ERR_SynthMemberShadowsMustOverride5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SynthMemberShadowsMustOverride5">
<file name="a.vb"><![CDATA[
MustInherit Class clsTest1
MustOverride Sub add_e(ByVal ArgX As clsTest2.eEventHandler)
End Class
MustInherit Class clsTest2
Inherits clsTest1
Shadows Event e()
End Class
]]></file>
</compilation>)
' CONSIDER: Dev11 prints "Sub add_E", rather than "AddHandler Event e", but roslyn's behavior seems friendlier
' and more consistent with the way property accessors are displayed (in both dev11 and roslyn).
Dim expectedErrors1 = <errors><![CDATA[
BC31413: 'Public AddHandler Event e(obj As clsTest2.eEventHandler)', implicitly declared for event 'e', cannot shadow a 'MustOverride' method in the base class 'clsTest1'.
Shadows Event e()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540613")>
<Fact>
Public Sub BC31417ERR_CannotOverrideInAccessibleMember()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CannotOverrideInAccessibleMember">
<file name="a.vb"><![CDATA[
Class Cls1
Private Overridable Sub goo()
End Sub
End Class
Class Cls2
Inherits Cls1
Private Overrides Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31408: 'Private' and 'Overridable' cannot be combined.
Private Overridable Sub goo()
~~~~~~~~~~~
BC31417: 'Private Overrides Sub goo()' cannot override 'Private Sub goo()' because it is not accessible in this context.
Private Overrides Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31418ERR_HandlesSyntaxInModule()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="HandlesSyntaxInModule">
<file name="a.vb"><![CDATA[
Option Strict Off
Module M
Sub Bar() Handles Me.Goo
End Sub
Event Goo()
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31418: 'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.
Sub Bar() Handles Me.Goo
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31420ERR_ClashWithReservedEnumMember1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClashWithReservedEnumMember1">
<file name="a.vb"><![CDATA[
Structure S
Public Enum InterfaceColors
value__
End Enum
End Structure
Class c1
Public Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31420: 'value__' conflicts with the reserved member by this name that is implicitly declared in all enums.
value__
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539947")>
<Fact>
Public Sub BC31420ERR_ClashWithReservedEnumMember2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ClashWithReservedEnumMember1">
<file name="a.vb"><![CDATA[
Module M
Public Enum InterfaceColors
Value__
End Enum
End Module
Class c1
Public Shared Sub Main(args As String())
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31420: 'Value__' conflicts with the reserved member by this name that is implicitly declared in all enums.
Value__
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31422ERR_BadUseOfVoid_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C1
Function scen1() As Void
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31422: 'System.Void' can only be used in a GetType expression.
Function scen1() As Void
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BC31422ERR_BadUseOfVoid_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Property P As System.Void
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31422: 'System.Void' can only be used in a GetType expression.
Property P As System.Void
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
CompilationUtils.AssertTheseEmitDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC31423ERR_EventImplMismatch5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventImplMismatch5">
<file name="a.vb"><![CDATA[
Imports System
Public Interface IA
Event E()
End Interface
Public Class A
Implements IA
Public Event E As Action Implements IA.E
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31423: Event 'Public Event E As Action' cannot implement event 'Event E()' on interface 'IA' because their delegate types 'Action' and 'IA.EEventHandler' do not match.
Public Event E As Action Implements IA.E
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539760")>
<Fact>
Public Sub BC31429ERR_MetadataMembersAmbiguous3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MetadataMembersAmbiguous3">
<file name="a.vb"><![CDATA[
Class Base
Public Shared Sub Main
Dim a As Integer = 5
Dim b As Base = New Derived(a)
End Sub
Private Class Derived
Inherits Base
Private a As Integer
Public Sub New(a As Integer)
Me.a = a
End Sub
Public Sub New()
End Sub
End Class
End Class
Class Base
Public Shared Sub Main
Dim a As Integer = 5
Dim b As Base = New Derived(a)
End Sub
Private Class Derived
Inherits Base
Private a As Integer
Public Sub New(a As Integer)
Me.a = a
End Sub
Public Sub New()
End Sub
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30521: Overload resolution failed because no accessible 'New' is most specific for these arguments:
'Public Sub New(a As Integer)': Not most specific.
'Public Sub New(a As Integer)': Not most specific.
Dim b As Base = New Derived(a)
~~~~~~~
BC31429: 'a' is ambiguous because multiple kinds of members with this name exist in class 'Base.Derived'.
Me.a = a
~~~~
BC30179: class 'Base' and class 'Base' conflict in namespace '<Default>'.
Class Base
~~~~
BC30521: Overload resolution failed because no accessible 'New' is most specific for these arguments:
'Public Sub New(a As Integer)': Not most specific.
'Public Sub New(a As Integer)': Not most specific.
Dim b As Base = New Derived(a)
~~~~~~~
BC30179: class 'Derived' and class 'Derived' conflict in class 'Base'.
Private Class Derived
~~~~~~~
BC31429: 'a' is ambiguous because multiple kinds of members with this name exist in class 'Base.Derived'.
Me.a = a
~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1">
<file name="a.vb"><![CDATA[
Class C1
Partial Public Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Public'.
Partial Public Sub goo()
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1a">
<file name="a.vb"><![CDATA[
Class C1
Partial Protected Overridable Sub goo()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Protected'.
Partial Protected Overridable Sub goo()
~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Overridable'.
Partial Protected Overridable Sub goo()
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1b">
<file name="a.vb"><![CDATA[
Class C1
Partial Protected Friend Sub M1()
End Sub
Partial Friend Protected Overridable Sub M2()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Protected Friend'.
Partial Protected Friend Sub M1()
~~~~~~~~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Friend Protected'.
Partial Friend Protected Overridable Sub M2()
~~~~~~~~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Overridable'.
Partial Friend Protected Overridable Sub M2()
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31431ERR_OnlyPrivatePartialMethods1c()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyPrivatePartialMethods1c">
<file name="a.vb"><![CDATA[
Class C1
Partial Protected Overridable Friend Sub M()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31431: Partial methods must be declared 'Private' instead of 'Protected'.
Partial Protected Overridable Friend Sub M()
~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Overridable'.
Partial Protected Overridable Friend Sub M()
~~~~~~~~~~~
BC31431: Partial methods must be declared 'Private' instead of 'Friend'.
Partial Protected Overridable Friend Sub M()
~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31432ERR_PartialMethodsMustBePrivate()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialMethodsMustBePrivate">
<file name="a.vb"><![CDATA[
Class C1
Partial Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31432: Partial methods must be declared 'Private'.
Partial Sub Goo()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2">
<file name="a.vb"><![CDATA[
Class C1
Partial Private Sub Goo()
End Sub
Partial Private Sub Goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31433: Method 'Goo' cannot be declared 'Partial' because only one method 'Goo' can be marked 'Partial'.
Partial Private Sub Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2a">
<file name="b.vb"><![CDATA[
Class C1
Partial Private Sub Goo()
End Sub
Partial Private Sub GoO()
End Sub
End Class
]]></file>
<file name="a.vb"><![CDATA[
Partial Class C1
Partial Private Sub goo()
End Sub
Partial Private Sub GOO()
End Sub
End Class
]]></file>
</compilation>)
' note the exact methods errors are reported on
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31433: Method 'goo' cannot be declared 'Partial' because only one method 'goo' can be marked 'Partial'.
Partial Private Sub goo()
~~~
BC31433: Method 'GOO' cannot be declared 'Partial' because only one method 'GOO' can be marked 'Partial'.
Partial Private Sub GOO()
~~~
BC31433: Method 'GoO' cannot be declared 'Partial' because only one method 'GoO' can be marked 'Partial'.
Partial Private Sub GoO()
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2b">
<file name="a.vb"><![CDATA[
Class CLS
Partial Private Shared Sub PS(a As Integer)
End Sub
Partial Private Shared Sub Ps(a As Integer)
End Sub
Private Shared Sub pS(a As Integer)
End Sub
Private Shared Sub ps(a As Integer)
End Sub
Public Sub PS(a As Integer)
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30269: 'Private Shared Sub PS(a As Integer)' has multiple definitions with identical signatures.
Partial Private Shared Sub PS(a As Integer)
~~
BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'.
Partial Private Shared Sub Ps(a As Integer)
~~
BC31434: Method 'ps' cannot implement partial method 'ps' because 'ps' already implements it. Only one method can implement a partial method.
Private Shared Sub ps(a As Integer)
~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31433ERR_OnlyOnePartialMethodAllowed2c()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOnePartialMethodAllowed2c">
<file name="a.vb"><![CDATA[
Class CLS
Partial Private Shared Sub PS(a As Integer)
End Sub
Partial Private Overloads Shared Sub Ps(a As Integer)
End Sub
Private Overloads Shared Sub ps(a As Integer)
End Sub
Private Shared Sub pS(a As Integer)
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31409: sub 'PS' must be declared 'Overloads' because another 'PS' is declared 'Overloads' or 'Overrides'.
Partial Private Shared Sub PS(a As Integer)
~~
BC31433: Method 'Ps' cannot be declared 'Partial' because only one method 'Ps' can be marked 'Partial'.
Partial Private Overloads Shared Sub Ps(a As Integer)
~~
BC31409: sub 'pS' must be declared 'Overloads' because another 'pS' is declared 'Overloads' or 'Overrides'.
Private Shared Sub pS(a As Integer)
~~
BC31434: Method 'pS' cannot implement partial method 'pS' because 'pS' already implements it. Only one method can implement a partial method.
Private Shared Sub pS(a As Integer)
~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31434ERR_OnlyOneImplementingMethodAllowed3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOneImplementingMethodAllowed3">
<file name="a.vb"><![CDATA[
Public Class C1
Partial Private Sub GoO2()
End Sub
End Class
Partial Public Class C1
Private Sub GOo2()
End Sub
End Class
Partial Public Class C1
Private Sub Goo2()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31434: Method 'Goo2' cannot implement partial method 'Goo2' because 'Goo2' already implements it. Only one method can implement a partial method.
Private Sub Goo2()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31434ERR_OnlyOneImplementingMethodAllowed3a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OnlyOneImplementingMethodAllowed3a">
<file name="b.vb"><![CDATA[
Public Class C1
Partial Private Sub GoO2()
End Sub
End Class
Partial Public Class C1
Private Sub GOo2()
End Sub
End Class
Partial Public Class C1
Private Sub Goo2()
End Sub
End Class
]]></file>
<file name="a.vb"><![CDATA[
Partial Public Class C1
Private Sub GOO2()
End Sub
End Class
Partial Public Class C1
Private Sub GoO2()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31434: Method 'GOO2' cannot implement partial method 'GOO2' because 'GOO2' already implements it. Only one method can implement a partial method.
Private Sub GOO2()
~~~~
BC31434: Method 'GoO2' cannot implement partial method 'GoO2' because 'GoO2' already implements it. Only one method can implement a partial method.
Private Sub GoO2()
~~~~
BC31434: Method 'Goo2' cannot implement partial method 'Goo2' because 'Goo2' already implements it. Only one method can implement a partial method.
Private Sub Goo2()
~~~~
]]></errors>
' note the exact methods errors are reported on
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31437ERR_PartialMethodsMustBeSub1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialMethodsMustBeSub1">
<file name="a.vb"><![CDATA[
Class C1
Partial Function Goo() As Boolean
Return True
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC31437: 'Goo' cannot be declared 'Partial' because partial methods must be Subs.
Partial Function Goo() As Boolean
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31437ERR_PartialMethodsMustBeSub2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialMethodsMustBeSub2">
<file name="a.vb"><![CDATA[
Class C1
Partial Private Sub Goo()
End Sub
Partial Function Goo() As Boolean
Return True
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC30301: 'Private Sub Goo()' and 'Public Function Goo() As Boolean' cannot overload each other because they differ only by return types.
Partial Private Sub Goo()
~~~
BC31437: 'Goo' cannot be declared 'Partial' because partial methods must be Subs.
Partial Function Goo() As Boolean
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31438ERR_PartialMethodGenericConstraints2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
End Interface
Interface IB
End Interface
Class C(Of X)
' Different constraints.
Partial Private Sub A1(Of T As Structure)()
End Sub
Private Sub A1(Of T As Class)()
End Sub
Partial Private Sub A2(Of T As Structure, U As IA(Of T))()
End Sub
Private Sub A2(Of T As Structure, U As IB)()
End Sub
Partial Private Sub A3(Of T As IA(Of T))()
End Sub
Private Sub A3(Of T As IA(Of IA(Of T)))()
End Sub
Partial Private Sub A4(Of T As {Structure, IA(Of T)}, U)()
End Sub
Private Sub A4(Of T As {Structure, IA(Of U)}, U)()
End Sub
' Additional constraints.
Partial Private Sub B1(Of T)()
End Sub
Private Sub B1(Of T As New)()
End Sub
Partial Private Sub B2(Of T As {X, New})()
End Sub
Private Sub B2(Of T As {X, Class, New})()
End Sub
Partial Private Sub B3(Of T As IA(Of T), U)()
End Sub
Private Sub B3(Of T As {IB, IA(Of T)}, U)()
End Sub
' Missing constraints.
Partial Private Sub C1(Of T As Class)()
End Sub
Private Sub C1(Of T)()
End Sub
Partial Private Sub C2(Of T As {Class, New})()
End Sub
Private Sub C2(Of T As {Class})()
End Sub
Partial Private Sub C3(Of T, U As {IB, IA(Of T)})()
End Sub
Private Sub C3(Of T, U As IA(Of T))()
End Sub
' Same constraints, different order.
Private Sub D1(Of T As {IA(Of T), IB})()
End Sub
Partial Private Sub D1(Of T As {IB, IA(Of T)})()
End Sub
Private Sub D2(Of T, U, V As {T, U, X})()
End Sub
Partial Private Sub D2(Of T, U, V As {U, X, T})()
End Sub
' Different constraint clauses.
Private Sub E1(Of T, U As T)()
End Sub
Partial Private Sub E1(Of T As Class, U)()
End Sub
' Additional constraint clause.
Private Sub F1(Of T As Class, U)()
End Sub
Partial Private Sub F1(Of T As Class, U As T)()
End Sub
' Missing constraint clause.
Private Sub G1(Of T As Class, U As T)()
End Sub
Partial Private Sub G1(Of T As Class, U)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31438: Method 'A1' does not have the same generic constraints as the partial method 'A1'.
Private Sub A1(Of T As Class)()
~~
BC31438: Method 'A2' does not have the same generic constraints as the partial method 'A2'.
Private Sub A2(Of T As Structure, U As IB)()
~~
BC31438: Method 'A3' does not have the same generic constraints as the partial method 'A3'.
Private Sub A3(Of T As IA(Of IA(Of T)))()
~~
BC31438: Method 'A4' does not have the same generic constraints as the partial method 'A4'.
Private Sub A4(Of T As {Structure, IA(Of U)}, U)()
~~
BC31438: Method 'B1' does not have the same generic constraints as the partial method 'B1'.
Private Sub B1(Of T As New)()
~~
BC31438: Method 'B2' does not have the same generic constraints as the partial method 'B2'.
Private Sub B2(Of T As {X, Class, New})()
~~
BC31438: Method 'B3' does not have the same generic constraints as the partial method 'B3'.
Private Sub B3(Of T As {IB, IA(Of T)}, U)()
~~
BC31438: Method 'C1' does not have the same generic constraints as the partial method 'C1'.
Private Sub C1(Of T)()
~~
BC31438: Method 'C2' does not have the same generic constraints as the partial method 'C2'.
Private Sub C2(Of T As {Class})()
~~
BC31438: Method 'C3' does not have the same generic constraints as the partial method 'C3'.
Private Sub C3(Of T, U As IA(Of T))()
~~
BC31438: Method 'E1' does not have the same generic constraints as the partial method 'E1'.
Private Sub E1(Of T, U As T)()
~~
BC31438: Method 'F1' does not have the same generic constraints as the partial method 'F1'.
Private Sub F1(Of T As Class, U)()
~~
BC31438: Method 'G1' does not have the same generic constraints as the partial method 'G1'.
Private Sub G1(Of T As Class, U As T)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31438ERR_PartialMethodGenericConstraints2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Class Base(Of T As Class)
Class Derived
Inherits Base(Of Base(Of String))
Partial Private Sub Goo(Of S As {Base(Of String), IComparable})(i As Integer)
End Sub
Private Sub GOO(Of S As {IComparable, Base(Of IDisposable)})(i As Integer)
End Sub
Private Sub GoO(Of s As {IComparable, Base(Of IEnumerable)})(i As Integer)
End Sub
Private Sub gOo(Of s As {IComparable, Base(Of IComparable)})(i As Integer)
End Sub
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31438: Method 'GOO' does not have the same generic constraints as the partial method 'Goo'.
Private Sub GOO(Of S As {IComparable, Base(Of IDisposable)})(i As Integer)
~~~
BC31434: Method 'GoO' cannot implement partial method 'GoO' because 'GoO' already implements it. Only one method can implement a partial method.
Private Sub GoO(Of s As {IComparable, Base(Of IEnumerable)})(i As Integer)
~~~
BC31434: Method 'gOo' cannot implement partial method 'gOo' because 'gOo' already implements it. Only one method can implement a partial method.
Private Sub gOo(Of s As {IComparable, Base(Of IComparable)})(i As Integer)
~~~
]]></errors>)
' NOTE: Dev10 reports three BC31438 in this case
End Sub
<Fact()>
Public Sub BC31438ERR_PartialMethodGenericConstraints2b()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Public Class Base(Of T As Class)
Public Class Derived
Inherits Base(Of Base(Of String))
Partial Private Sub Goo(Of S As {Base(Of String), IComparable})(i As Integer)
End Sub
Private Sub gOo(Of s As {IComparable, C.I})(i As Integer)
End Sub
Partial Private Sub Bar(Of S As {C.I})(i As Integer)
End Sub
Private Sub bar(Of s As {C.I})(i As Integer)
End Sub
Public Class C
Interface I
End Interface
End Class
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31438: Method 'gOo' does not have the same generic constraints as the partial method 'Goo'.
Private Sub gOo(Of s As {IComparable, C.I})(i As Integer)
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31439ERR_PartialDeclarationImplements1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialDeclarationImplements1">
<file name="a.vb"><![CDATA[
Imports System
Class A
Implements IDisposable
Partial Private Sub Dispose() Implements IDisposable.Dispose
End Sub
Private Sub Dispose()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'A' must implement 'Sub Dispose()' for interface 'IDisposable'.
Implements IDisposable
~~~~~~~~~~~
BC31439: Partial method 'Dispose' cannot use the 'Implements' keyword.
Partial Private Sub Dispose() Implements IDisposable.Dispose
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31439ERR_PartialDeclarationImplements1a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PartialDeclarationImplements1a">
<file name="a.vb"><![CDATA[
Imports System
Class A
Implements IDisposable
Partial Private Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30149: Class 'A' must implement 'Sub Dispose()' for interface 'IDisposable'.
Implements IDisposable
~~~~~~~~~~~
BC31439: Partial method 'Dispose' cannot use the 'Implements' keyword.
Partial Private Sub Dispose() Implements IDisposable.Dispose
~~~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31441ERR_ImplementationMustBePrivate2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementationMustBePrivate2">
<file name="a.vb"><![CDATA[
Partial Class C1
Partial Private Sub GOO()
End Sub
End Class
Partial Class C1
Sub GOO()
'HELLO
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31441: Method 'GOO' must be declared 'Private' in order to implement partial method 'GOO'.
Sub GOO()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31441ERR_ImplementationMustBePrivate2a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementationMustBePrivate2a">
<file name="a.vb"><![CDATA[
Partial Class C1
Partial Private Sub GOO()
End Sub
End Class
Partial Class C1
Sub Goo()
End Sub
Private Sub gOO()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31441: Method 'Goo' must be declared 'Private' in order to implement partial method 'GOO'.
Sub Goo()
~~~
BC31434: Method 'gOO' cannot implement partial method 'gOO' because 'gOO' already implements it. Only one method can implement a partial method.
Private Sub gOO()
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31442ERR_PartialMethodParamNamesMustMatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialMethodParamNamesMustMatch3">
<file name="a.vb"><![CDATA[
Module M
Partial Private Sub Goo(ByVal x As Integer)
End Sub
Private Sub Goo(ByVal y As Integer)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31442: Parameter name 'y' does not match the name of the corresponding parameter, 'x', defined on the partial method declaration 'Goo'.
Private Sub Goo(ByVal y As Integer)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC31442ERR_PartialMethodParamNamesMustMatch3a()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialMethodParamNamesMustMatch3a">
<file name="a.vb"><![CDATA[
Module M
Partial Private Sub Goo(ByVal x As Integer, a As Integer)
End Sub
Private Sub Goo(ByVal x As Integer, b As Integer)
End Sub
Private Sub Goo(ByVal y As Integer, b As Integer)
End Sub
Private Sub Goo(ByVal y As Integer, b As Integer)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC31442: Parameter name 'b' does not match the name of the corresponding parameter, 'a', defined on the partial method declaration 'Goo'.
Private Sub Goo(ByVal x As Integer, b As Integer)
~
BC31434: Method 'Goo' cannot implement partial method 'Goo' because 'Goo' already implements it. Only one method can implement a partial method.
Private Sub Goo(ByVal y As Integer, b As Integer)
~~~
BC31434: Method 'Goo' cannot implement partial method 'Goo' because 'Goo' already implements it. Only one method can implement a partial method.
Private Sub Goo(ByVal y As Integer, b As Integer)
~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC31443ERR_PartialMethodTypeParamNameMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PartialMethodTypeParamNameMismatch3">
<file name="a.vb"><![CDATA[
Module M
Partial Private Sub Goo(Of S)()
End Sub
Private Sub Goo(Of T)()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31443: Name of type parameter 'T' does not match 'S', the corresponding type parameter defined on the partial method declaration 'Goo'.
Private Sub Goo(Of T)()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC31503ERR_AttributeMustBeClassNotStruct1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeMustBeClassNotStruct1">
<file name="a.vb"><![CDATA[
Structure s1
End Structure
<s1()>
Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31503: 's1' cannot be used as an attribute because it is not a class.
<s1()>
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540625")>
<Fact>
Public Sub BC31504ERR_AttributeMustInheritSysAttr()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeMustInheritSysAttr">
<file name="at31504.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public Class MyAttribute
'Inherits Attribute
End Class
<MyAttribute()>
Class Test
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttributeMustInheritSysAttr, "MyAttribute").WithArguments("MyAttribute"))
End Sub
<WorkItem(540628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540628")>
<Fact>
Public Sub BC31506ERR_AttributeCannotBeAbstract()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeCannotBeAbstract">
<file name="at31506.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public MustInherit Class MyAttribute
Inherits Attribute
Public Sub New()
End Sub
End Class
<My()>
Class Goo
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttributeCannotBeAbstract, "My").WithArguments("MyAttribute"))
End Sub
<WorkItem(540628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540628")>
<Fact>
Public Sub BC31507ERR_AttributeCannotHaveMustOverride()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttributeCannotHaveMustOverride">
<file name="at31500.vb"><![CDATA[
Imports System
<AttributeUsage(AttributeTargets.All)>
Public MustInherit Class MyAttribute
Inherits Attribute
Public Sub New()
End Sub
'MustOverride Property AbsProp As Byte
Public MustOverride Sub AbsSub()
End Class
<My()>
Class Goo
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttributeCannotBeAbstract, "My").WithArguments("MyAttribute"))
End Sub
<Fact>
Public Sub BC31512ERR_STAThreadAndMTAThread0()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="STAThreadAndMTAThread0">
<file name="a.vb"><![CDATA[
Imports System
Class C1
<MTAThread>
<STAThread>
Sub goo()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31512: 'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.
Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' BC31523ERR_DllImportNotLegalOnDeclare
' BC31524ERR_DllImportNotLegalOnGetOrSet
' BC31526ERR_DllImportOnGenericSubOrFunction
' see AttributeTests
<Fact()>
Public Sub BC31527ERR_ComClassOnGeneric()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassOnGeneric">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic
<ComClass()>
Class C1(Of T)
Sub GOO(ByVal s As T)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.
Class C1(Of T)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' BC31529ERR_DllImportOnInstanceMethod
' BC31530ERR_DllImportOnInterfaceMethod
' BC31531ERR_DllImportNotLegalOnEventMethod
' see AttributeTests
<Fact, WorkItem(1116455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116455")>
Public Sub BC31534ERR_FriendAssemblyBadArguments()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="FriendAssemblyBadArguments">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleTo("Test, Version=*")> ' ok
<Assembly: InternalsVisibleTo("Test, PublicKeyToken=*")> ' ok
<Assembly: InternalsVisibleTo("Test, Culture=*")> ' ok
<Assembly: InternalsVisibleTo("Test, Retargetable=*")> ' ok
<Assembly: InternalsVisibleTo("Test, ContentType=*")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=.")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=..")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=...")> ' ok
<Assembly: InternalsVisibleTo("Test, Version=1")> ' error
<Assembly: InternalsVisibleTo("Test, Version=1.*")> ' error
<Assembly: InternalsVisibleTo("Test, Version=1.1.*")> ' error
<Assembly: InternalsVisibleTo("Test, Version=1.1.1.*")> ' error
<Assembly: InternalsVisibleTo("Test, ProcessorArchitecture=MSIL")> ' error
<Assembly: InternalsVisibleTo("Test, CuLTure=EN")> ' error
<Assembly: InternalsVisibleTo("Test, PublicKeyToken=null")> ' ok
]]></file>
</compilation>, {SystemCoreRef})
' Tested against Dev12
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1"")").WithArguments("Test, Version=1").WithLocation(11, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1.*"")").WithArguments("Test, Version=1.*").WithLocation(12, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1.1.*"")").WithArguments("Test, Version=1.1.*").WithLocation(13, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, Version=1.1.1.*"")").WithArguments("Test, Version=1.1.1.*").WithLocation(14, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")").WithArguments("Test, ProcessorArchitecture=MSIL").WithLocation(15, 2),
Diagnostic(ERRID.ERR_FriendAssemblyBadArguments, "Assembly: InternalsVisibleTo(""Test, CuLTure=EN"")").WithArguments("Test, CuLTure=EN").WithLocation(16, 2))
End Sub
<Fact>
Public Sub BC31537ERR_FriendAssemblyNameInvalid()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="FriendAssemblyNameInvalid">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleTo("' '")> ' ok
<Assembly: InternalsVisibleTo("\t\r\n;a")> ' ok (whitespace escape)
<Assembly: InternalsVisibleTo("\u1234;a")> ' ok (assembly name Unicode escape)
<Assembly: InternalsVisibleTo("' a '")> ' ok
<Assembly: InternalsVisibleTo("\u1000000;a")> ' invalid escape
<Assembly: InternalsVisibleTo("a'b'c")> ' quotes in the middle
<Assembly: InternalsVisibleTo("Test, PublicKey=Null")>
<Assembly: InternalsVisibleTo("Test, Bar")>
<Assembly: InternalsVisibleTo("Test, Version")>
]]></file>
</compilation>, {SystemCoreRef})
' Tested against Dev12
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""\u1000000;a"")").WithArguments("\u1000000;a").WithLocation(6, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""a'b'c"")").WithArguments("a'b'c").WithLocation(7, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""Test, PublicKey=Null"")").WithArguments("Test, PublicKey=Null").WithLocation(8, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""Test, Bar"")").WithArguments("Test, Bar").WithLocation(9, 2),
Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: InternalsVisibleTo(""Test, Version"")").WithArguments("Test, Version").WithLocation(10, 2))
End Sub
<Fact()>
Public Sub BC31549ERR_PIAHasNoAssemblyGuid1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"/>
</compilation>,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
compilation2.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC31549: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute.
]]></errors>)
End Sub
<Fact()>
Public Sub BC31553ERR_PIAHasNoTypeLibAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"><![CDATA[
<Assembly: System.Runtime.InteropServices.Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
]]></file>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"/>
</compilation>,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
compilation2.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC31553: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute.
]]></errors>)
End Sub
<Fact()>
Public Sub BC31553ERR_PIAHasNoTypeLibAttribute1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="A">
<file name="a.vb"/>
</compilation>)
compilation1.AssertNoErrors()
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"/>
</compilation>,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
compilation2.AssertTheseDeclarationDiagnostics(<errors><![CDATA[
BC31549: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute.
BC31553: Cannot embed interop types from assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute.
]]></errors>)
End Sub
<Fact>
Public Sub BC32040ERR_BadFlagsOnNewOverloads()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadFlagsOnNewOverloads">
<file name="a.vb"><![CDATA[
class C1
End class
Friend Class C2
Inherits C1
Public Overloads Sub New(ByVal x As Integer)
MyBase.New(CType (x, Short))
End Sub
Public Sub New(ByVal x As Date)
MyBase.New(1)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32040: The 'Overloads' keyword is used to overload inherited members; do not use the 'Overloads' keyword when overloading 'Sub New'.
Public Overloads Sub New(ByVal x As Integer)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32041ERR_TypeCharOnGenericParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeCharOnGenericParam">
<file name="a.vb"><![CDATA[
Structure S(Of T@)
Sub M(Of U@)()
End Sub
End Structure
Interface I(Of T#)
Sub M(Of U#)()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32041: Type character cannot be used in a type parameter declaration.
Structure S(Of T@)
~~
BC32041: Type character cannot be used in a type parameter declaration.
Sub M(Of U@)()
~~
BC32041: Type character cannot be used in a type parameter declaration.
Interface I(Of T#)
~~
BC32041: Type character cannot be used in a type parameter declaration.
Sub M(Of U#)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32042ERR_TooFewGenericArguments1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TooFewGenericArguments1">
<file name="a.vb"><![CDATA[
Structure S1(Of t)
End Structure
Class c1
Dim x3 As S1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32042: Too few type arguments to 'S1(Of t)'.
Dim x3 As S1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32043ERR_TooManyGenericArguments1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TooManyGenericArguments1">
<file name="a.vb"><![CDATA[
Structure S1(Of arg1)
End Structure
Class c1
Dim scen2 As New S1(Of String, Integer, Double, Decimal)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32043: Too many type arguments to 'S1(Of arg1)'.
Dim scen2 As New S1(Of String, Integer, Double, Decimal)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32044ERR_GenericConstraintNotSatisfied2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T1, T2)
Sub M(Of U As {T1, T2})()
M(Of T1)()
M(Of T2)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32044: Type argument 'T1' does not inherit from or implement the constraint type 'T2'.
M(Of T1)()
~~~~~~~~
BC32044: Type argument 'T2' does not inherit from or implement the constraint type 'T1'.
M(Of T2)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32044ERR_GenericConstraintNotSatisfied2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Module M
Sub Main()
Goo(Function(x As String) x, Function(x As Object) x)
End Sub
Sub Goo(Of T, S As T)(ByVal x As T, ByVal y As S)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32044: Type argument 'Function <generated method>(x As Object) As Object' does not inherit from or implement the constraint type 'Function <generated method>(x As String) As String'.
Goo(Function(x As String) x, Function(x As Object) x)
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32047ERR_MultipleClassConstraints1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleClassConstraints1">
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
Inherits A
End Class
Class C
Inherits B
End Class
Interface IA(Of T, U As {A, T, B})
End Interface
Interface IB
Sub M(Of T As {A, B, C, New})()
End Interface
MustInherit Class D(Of T, U)
MustOverride Sub M(Of V As {T, U, C, New})()
End Class
MustInherit Class E
Inherits D(Of A, B)
Public Overrides Sub M(Of V As {A, B, C, New})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32047: Type parameter 'U' can only have one constraint that is a class.
Interface IA(Of T, U As {A, T, B})
~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Sub M(Of T As {A, B, C, New})()
~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Sub M(Of T As {A, B, C, New})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32048ERR_ConstNotClassInterfaceOrTypeParam1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ConstNotClassInterfaceOrTypeParam1">
<file name="a.vb"><![CDATA[
Class A
End Class
Delegate Sub D()
Structure S
End Structure
Enum E
A
End Enum
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
End Class
MustInherit Class C2(Of T1, T2, T3, T4, T5)
MustOverride Sub M(Of U1 As T1, U2 As T2, U3 As T3, U4 As T4, U5 As T5)()
End Class
MustInherit Class C3
Inherits C2(Of A(), D, S, E, Unknown)
MustOverride Overrides Sub M(Of U1 As A(), U2 As D, U3 As S, U4 As E, U5 As Unknown)()
End Class
Class C3(Of T As {S(), E()})
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32048: Type constraint 'A()' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~~~
BC32048: Type constraint 'D' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~
BC32048: Type constraint 'S' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~
BC32048: Type constraint 'E' must be either a class, interface or type parameter.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~
BC30002: Type 'Unknown' is not defined.
Class C1(Of T1 As A(), T2 As D, T3 As S, T4 As E, T5 As Unknown)
~~~~~~~
BC30002: Type 'Unknown' is not defined.
Inherits C2(Of A(), D, S, E, Unknown)
~~~~~~~
BC30002: Type 'Unknown' is not defined.
MustOverride Overrides Sub M(Of U1 As A(), U2 As D, U3 As S, U4 As E, U5 As Unknown)()
~~~~~~~
BC32048: Type constraint 'S()' must be either a class, interface or type parameter.
Class C3(Of T As {S(), E()})
~~~
BC32048: Type constraint 'E()' must be either a class, interface or type parameter.
Class C3(Of T As {S(), E()})
~~~
BC32119: Constraint 'E()' conflicts with the constraint 'S()' already specified for type parameter 'T'.
Class C3(Of T As {S(), E()})
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Checks for duplicate type parameters
<Fact>
Public Sub BC32049ERR_DuplicateTypeParamName1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
class c(of tT, TT, Tt)
end class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32049: Type parameter already declared with name 'TT'.
class c(of tT, TT, Tt)
~~
BC32049: Type parameter already declared with name 'Tt'.
class c(of tT, TT, Tt)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32054ERR_ShadowingGenericParamWithMember1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingGenericParamWithMember1">
<file name="a.vb"><![CDATA[
Partial Structure S1(Of membername)
Function membername() As String
End Function
End Structure
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32054: 'membername' has the same name as a type parameter.
Function membername() As String
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32055ERR_GenericParamBase2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericParamBase2">
<file name="a.vb"><![CDATA[
Class C1(Of T)
Class cls3
Inherits T
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32055: Class 'cls3' cannot inherit from a type parameter.
Inherits T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32055ERR_GenericParamBase2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericParamBase2">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
Class c1
Inherits T
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32055: Class 'c1' cannot inherit from a type parameter.
Inherits T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32056ERR_ImplementsGenericParam()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeParamQualifierDisallowed">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
Class c1
Implements T
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32056: Type parameter not allowed in 'Implements' clause.
Implements T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32060ERR_ClassConstraintNotInheritable1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
NotInheritable Class A
End Class
Class B
End Class
Interface IA(Of T As {A, B})
End Interface
Interface IB(Of T)
Sub M(Of U As T)()
End Interface
Class C
Implements IB(Of A)
Private Sub M(Of U As A)() Implements IB(Of A).M
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32060: Type constraint cannot be a 'NotInheritable' class.
Interface IA(Of T As {A, B})
~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Interface IA(Of T As {A, B})
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32061ERR_ConstraintIsRestrictedType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Interface I(Of T As Object, U As System.ValueType)
End Interface
Structure S(Of T As System.Enum, U As System.Array)
End Structure
Delegate Sub D(Of T As System.Delegate, U As System.MulticastDelegate)()
Class C(Of T As {Object, A}, U As {A, Object})
End Class
Class A(Of T1, T2, T3, T4, T5, T6)
End Class
Class B
Inherits A(Of Object, System.ValueType, System.Enum, System.Array, System.Delegate, System.MulticastDelegate)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32061: 'Object' cannot be used as a type constraint.
Interface I(Of T As Object, U As System.ValueType)
~~~~~~
BC32061: 'ValueType' cannot be used as a type constraint.
Interface I(Of T As Object, U As System.ValueType)
~~~~~~~~~~~~~~~~
BC32061: '[Enum]' cannot be used as a type constraint.
Structure S(Of T As System.Enum, U As System.Array)
~~~~~~~~~~~
BC32061: 'Array' cannot be used as a type constraint.
Structure S(Of T As System.Enum, U As System.Array)
~~~~~~~~~~~~
BC32061: '[Delegate]' cannot be used as a type constraint.
Delegate Sub D(Of T As System.Delegate, U As System.MulticastDelegate)()
~~~~~~~~~~~~~~~
BC32061: 'MulticastDelegate' cannot be used as a type constraint.
Delegate Sub D(Of T As System.Delegate, U As System.MulticastDelegate)()
~~~~~~~~~~~~~~~~~~~~~~~~
BC32061: 'Object' cannot be used as a type constraint.
Class C(Of T As {Object, A}, U As {A, Object})
~~~~~~
BC32047: Type parameter 'T' can only have one constraint that is a class.
Class C(Of T As {Object, A}, U As {A, Object})
~
BC32047: Type parameter 'U' can only have one constraint that is a class.
Class C(Of T As {Object, A}, U As {A, Object})
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540653")>
<Fact>
Public Sub BC32067ERR_AttrCannotBeGenerics()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AttrCannotBeGenerics">
<file name="a.vb"><![CDATA[
Imports System
Class Test(Of attributeusageattribute)
'COMPILEERROR: BC32067,"attributeusageattribute"
<attributeusageattribute(AttributeTargets.All)> Class c1
End Class
Class myattr
'COMPILEERROR: BC32074,"Attribute"
Inherits Attribute
End Class
'COMPILEERROR: BC32067,"myattr"
<myattr()> Class test3
End Class
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AttrCannotBeGenerics, "attributeusageattribute").WithArguments("attributeusageattribute"),
Diagnostic(ERRID.ERR_AttrCannotBeGenerics, "myattr").WithArguments("Test(Of attributeusageattribute).myattr"),
Diagnostic(ERRID.ERR_GenericClassCannotInheritAttr, "myattr"))
End Sub
<Fact()>
Public Sub BC32068ERR_BadStaticLocalInGenericMethod()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadStaticLocalInGenericMethod">
<file name="a.vb"><![CDATA[
Module M
Sub Goo(Of T)()
Static x = 1
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32068: Local variables within generic methods cannot be declared 'Static'.
Static x = 1
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32070ERR_SyntMemberShadowsGenericParam3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="SyntMemberShadowsGenericParam3">
<file name="a.vb"><![CDATA[
Class C(Of _P, get_P, set_P, _q, get_R, set_R, _R)
Property P
Property Q
Property R
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32070: property 'P' implicitly defines a member '_P' which has the same name as a type parameter.
Property P
~
BC32070: property 'Q' implicitly defines a member '_Q' which has the same name as a type parameter.
Property Q
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32071ERR_ConstraintAlreadyExists1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
MustInherit Class B(Of T, U)
MustOverride Sub M1(Of V As {T, U, I})()
End Class
MustInherit Class C
Inherits B(Of I, A)
MustOverride Overrides Sub M1(Of V As {I, A, I})()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32071: Constraint type 'I' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'T' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32047: Type parameter 'U' can only have one constraint that is a class.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'A' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'I' already specified for this type parameter.
Delegate Sub D(Of T As I, U As {New, T, I, I, A, T, A, I})()
~
BC32071: Constraint type 'I' already specified for this type parameter.
MustOverride Overrides Sub M1(Of V As {I, A, I})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Duplicate undefined constraint types.
<Fact()>
Public Sub BC32071ERR_ConstraintAlreadyExists1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {A, B, A})
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30002: Type 'A' is not defined.
Class C(Of T As {A, B, A})
~
BC30002: Type 'B' is not defined.
Class C(Of T As {A, B, A})
~
BC30002: Type 'A' is not defined.
Class C(Of T As {A, B, A})
~
BC32071: Constraint type 'A' already specified for this type parameter.
Class C(Of T As {A, B, A})
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
Public Sub BC32072ERR_InterfacePossiblyImplTwice2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfacePossiblyImplTwice2">
<file name="a.vb"><![CDATA[
Class C1(Of T As IAsyncResult, u As IComparable)
Implements intf1(Of T)
Implements intf1(Of u)
End Class
Interface intf1(Of T)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32072: Cannot implement interface 'intf1(Of u)' because its implementation could conflict with the implementation of another implemented interface 'intf1(Of T)' for some type arguments.
Implements intf1(Of u)
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540652")>
<Fact()>
Public Sub BC32074ERR_GenericClassCannotInheritAttr()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Reflection
Friend Module RegressVSW108431mod
<AttributeUsage(AttributeTargets.All)>
Class Attr1(Of A)
'COMPILEERROR: BC32074, "Attribute"
Inherits Attribute
End Class
Class G(Of T)
Class Attr2
'COMPILEERROR: BC32074,"Attribute"
Inherits Attribute
End Class
End Class
End Module
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class Attr1(Of A)
~~~~~
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class Attr2
~~~~~
]]></errors>)
End Sub
<WorkItem(543672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543672")>
<Fact()>
Public Sub BC32074ERR_GenericClassCannotInheritAttr_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Inherits System.Attribute
End Class
Class B(Of T)
Inherits A
End Class
Class C(Of T)
Class B
Inherits A
End Class
End Class
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class B(Of T)
~
BC32074: Classes that are generic or contained in a generic type cannot inherit from an attribute class.
Class B
~
]]></errors>)
End Sub
<Fact>
Public Sub BC32075ERR_DeclaresCantBeInGeneric()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="GenericClassCannotInheritAttr">
<file name="a.vb"><![CDATA[
Public Class C1(Of t)
Declare Sub goo Lib "a.dll" ()
End Class
]]></file>
</compilation>)
compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_DeclaresCantBeInGeneric, "goo"))
End Sub
<Fact()>
Public Sub BC32077ERR_OverrideWithConstraintMismatch2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
End Interface
Interface IB
End Interface
MustInherit Class A
' Different constraints.
Friend MustOverride Sub A1(Of T As Structure)()
Friend MustOverride Sub A2(Of T As Structure, U As IA(Of T))()
Friend MustOverride Sub A3(Of T As IA(Of T))()
Friend MustOverride Sub A4(Of T As {Structure, IA(Of T)}, U)()
' Additional constraints.
Friend MustOverride Sub B1(Of T)()
Friend MustOverride Sub B2(Of T As New)()
Friend MustOverride Sub B3(Of T As IA(Of T), U)()
' Missing constraints.
Friend MustOverride Sub C1(Of T As Class)()
Friend MustOverride Sub C2(Of T As {Class, New})()
Friend MustOverride Sub C3(Of T, U As {IB, IA(Of T)})()
' Same constraints, different order.
Friend MustOverride Sub D1(Of T As {IA(Of T), IB})()
Friend MustOverride Sub D2(Of T, U, V As {T, U})()
' Different constraint clauses.
Friend MustOverride Sub E1(Of T, U As T)()
' Different type parameter names.
Friend MustOverride Sub F1(Of T As Class, U As T)()
Friend MustOverride Sub F2(Of T As Class, U As T)()
End Class
MustInherit Class B
Inherits A
' Different constraints.
Friend MustOverride Overrides Sub A1(Of T As Class)()
Friend MustOverride Overrides Sub A2(Of T As Structure, U As IB)()
Friend MustOverride Overrides Sub A3(Of T As IA(Of IA(Of T)))()
Friend MustOverride Overrides Sub A4(Of T As {Structure, IA(Of U)}, U)()
' Additional constraints.
Friend MustOverride Overrides Sub B1(Of T As New)()
Friend MustOverride Overrides Sub B2(Of T As {Class, New})()
Friend MustOverride Overrides Sub B3(Of T As {IB, IA(Of T)}, U)()
' Missing constraints.
Friend MustOverride Overrides Sub C1(Of T)()
Friend MustOverride Overrides Sub C2(Of T As Class)()
Friend MustOverride Overrides Sub C3(Of T, U As IA(Of T))()
' Same constraints, different order.
Friend MustOverride Overrides Sub D1(Of T As {IB, IA(Of T)})()
Friend MustOverride Overrides Sub D2(Of T, U, V As {U, T})()
' Different constraint clauses.
Friend MustOverride Overrides Sub E1(Of T As Class, U)()
' Different type parameter names.
Friend MustOverride Overrides Sub F1(Of U As Class, T As U)()
Friend MustOverride Overrides Sub F2(Of T1 As Class, T2 As T1)()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32077: 'Friend MustOverride Overrides Sub A1(Of T As Class)()' cannot override 'Friend MustOverride Sub A1(Of T As Structure)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A1(Of T As Class)()
~~
BC32077: 'Friend MustOverride Overrides Sub A2(Of T As Structure, U As IB)()' cannot override 'Friend MustOverride Sub A2(Of T As Structure, U As IA(Of T))()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A2(Of T As Structure, U As IB)()
~~
BC32077: 'Friend MustOverride Overrides Sub A3(Of T As IA(Of IA(Of T)))()' cannot override 'Friend MustOverride Sub A3(Of T As IA(Of T))()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A3(Of T As IA(Of IA(Of T)))()
~~
BC32077: 'Friend MustOverride Overrides Sub A4(Of T As {Structure, IA(Of U)}, U)()' cannot override 'Friend MustOverride Sub A4(Of T As {Structure, IA(Of T)}, U)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub A4(Of T As {Structure, IA(Of U)}, U)()
~~
BC32077: 'Friend MustOverride Overrides Sub B1(Of T As New)()' cannot override 'Friend MustOverride Sub B1(Of T)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub B1(Of T As New)()
~~
BC32077: 'Friend MustOverride Overrides Sub B2(Of T As {Class, New})()' cannot override 'Friend MustOverride Sub B2(Of T As New)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub B2(Of T As {Class, New})()
~~
BC32077: 'Friend MustOverride Overrides Sub B3(Of T As {IB, IA(Of T)}, U)()' cannot override 'Friend MustOverride Sub B3(Of T As IA(Of T), U)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub B3(Of T As {IB, IA(Of T)}, U)()
~~
BC32077: 'Friend MustOverride Overrides Sub C1(Of T)()' cannot override 'Friend MustOverride Sub C1(Of T As Class)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub C1(Of T)()
~~
BC32077: 'Friend MustOverride Overrides Sub C2(Of T As Class)()' cannot override 'Friend MustOverride Sub C2(Of T As {Class, New})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub C2(Of T As Class)()
~~
BC32077: 'Friend MustOverride Overrides Sub C3(Of T, U As IA(Of T))()' cannot override 'Friend MustOverride Sub C3(Of T, U As {IB, IA(Of T)})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub C3(Of T, U As IA(Of T))()
~~
BC32077: 'Friend MustOverride Overrides Sub E1(Of T As Class, U)()' cannot override 'Friend MustOverride Sub E1(Of T, U As T)()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub E1(Of T As Class, U)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32077ERR_OverrideWithConstraintMismatch2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
End Interface
Class A
Implements I
End Class
Structure S
End Structure
MustInherit Class A0(Of T)
Friend MustOverride Sub AM(Of U As {T, Structure})()
End Class
MustInherit Class A1
Inherits A0(Of S)
Friend MustOverride Overrides Sub AM(Of U As {Structure, S})()
End Class
MustInherit Class A2
Inherits A0(Of S)
Friend MustOverride Overrides Sub AM(Of U As S)()
End Class
MustInherit Class B0(Of T)
Friend MustOverride Sub BX(Of U As {T, Class})()
End Class
MustInherit Class B1
Inherits B0(Of A)
Friend MustOverride Overrides Sub BX(Of U As {Class, A})()
End Class
MustInherit Class B2
Inherits B0(Of A)
Friend MustOverride Overrides Sub BX(Of U As A)()
End Class
MustInherit Class C0(Of T, U)
Friend MustOverride Sub CM(Of V As {T, U})()
End Class
MustInherit Class C1(Of T)
Inherits C0(Of T, T)
Friend MustOverride Overrides Sub CM(Of V As T)()
End Class
MustInherit Class C2(Of T)
Inherits C0(Of T, T)
Friend MustOverride Overrides Sub CM(Of V As {T, T})()
End Class
MustInherit Class D0(Of T, U)
Friend MustOverride Sub DM(Of V As {T, U, A, I})()
End Class
MustInherit Class D1
Inherits D0(Of I, A)
Friend MustOverride Overrides Sub DM(Of V As A)()
End Class
MustInherit Class D2
Inherits D0(Of I, A)
Friend MustOverride Overrides Sub DM(Of V As {A, I})()
End Class
MustInherit Class D3
Inherits D0(Of A, I)
Friend MustOverride Overrides Sub DM(Of V As {A, I, A, I})()
End Class
MustInherit Class E0(Of T, U)
Friend MustOverride Sub EM(Of V As {T, U, Structure})()
End Class
MustInherit Class E1
Inherits E0(Of Object, ValueType)
Friend MustOverride Overrides Sub EM(Of U As Structure)()
End Class
MustInherit Class E2
Inherits E0(Of Object, ValueType)
Friend MustOverride Overrides Sub EM(Of U As {Structure, Object, ValueType})()
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32077: 'Friend MustOverride Overrides Sub AM(Of U As S)()' cannot override 'Friend MustOverride Sub AM(Of U As {Structure, S})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub AM(Of U As S)()
~~
BC32077: 'Friend MustOverride Overrides Sub BX(Of U As A)()' cannot override 'Friend MustOverride Sub BX(Of U As {Class, A})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub BX(Of U As A)()
~~
BC32071: Constraint type 'T' already specified for this type parameter.
Friend MustOverride Overrides Sub CM(Of V As {T, T})()
~
BC32077: 'Friend MustOverride Overrides Sub DM(Of V As A)()' cannot override 'Friend MustOverride Sub DM(Of V As {I, A})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub DM(Of V As A)()
~~
BC32071: Constraint type 'A' already specified for this type parameter.
Friend MustOverride Overrides Sub DM(Of V As {A, I, A, I})()
~
BC32071: Constraint type 'I' already specified for this type parameter.
Friend MustOverride Overrides Sub DM(Of V As {A, I, A, I})()
~
BC32077: 'Friend MustOverride Overrides Sub EM(Of U As Structure)()' cannot override 'Friend MustOverride Sub EM(Of V As {Structure, Object, ValueType})()' because they differ by type parameter constraints.
Friend MustOverride Overrides Sub EM(Of U As Structure)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface I
End Interface
Class A
Implements I
End Class
Structure S
End Structure
Interface IA(Of T)
Sub AM(Of U As {T, Structure})()
End Interface
Class A1
Implements IA(Of S)
Private Sub AM(Of U As {Structure, S})() Implements IA(Of S).AM
End Sub
End Class
Class A2
Implements IA(Of S)
Private Sub AM(Of U As S)() Implements IA(Of S).AM
End Sub
End Class
Interface IB(Of T)
Sub BX(Of U As {T, Class})()
End Interface
Class B1
Implements IB(Of A)
Private Sub BX(Of U As {Class, A})() Implements IB(Of A).BX
End Sub
End Class
Class B2
Implements IB(Of A)
Private Sub BX(Of U As A)() Implements IB(Of A).BX
End Sub
End Class
Interface IC(Of T, U)
Sub CM(Of V As {T, U})()
End Interface
Class C1(Of T)
Implements IC(Of T, T)
Private Sub CM(Of V As T)() Implements IC(Of T, T).CM
End Sub
End Class
Class C2(Of T)
Implements IC(Of T, T)
Private Sub CM(Of V As {T, T})() Implements IC(Of T, T).CM
End Sub
End Class
Interface ID(Of T, U)
Sub DM(Of V As {T, U, A, I})()
End Interface
Class D1
Implements ID(Of I, A)
Private Sub DM(Of V As A)() Implements ID(Of I, A).DM
End Sub
End Class
Class D2
Implements ID(Of I, A)
Private Sub DM(Of V As {A, I})() Implements ID(Of I, A).DM
End Sub
End Class
Class D3
Implements ID(Of A, I)
Private Sub DM(Of V As {A, I, A, I})() Implements ID(Of A, I).DM
End Sub
End Class
Interface IE(Of T, U)
Sub EM(Of V As {T, U, Structure})()
End Interface
Class E1
Implements IE(Of Object, ValueType)
Private Sub EM(Of U As Structure)() Implements IE(Of Object, ValueType).EM
End Sub
End Class
Class E2
Implements IE(Of Object, ValueType)
Private Sub EM(Of U As {Structure, Object, ValueType})() Implements IE(Of Object, ValueType).EM
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32078: 'Private Sub AM(Of U As S)()' cannot implement 'IA(Of S).Sub AM(Of U As {Structure, S})()' because they differ by type parameter constraints.
Private Sub AM(Of U As S)() Implements IA(Of S).AM
~~~~~~~~~~~
BC32078: 'Private Sub BX(Of U As A)()' cannot implement 'IB(Of A).Sub BX(Of U As {Class, A})()' because they differ by type parameter constraints.
Private Sub BX(Of U As A)() Implements IB(Of A).BX
~~~~~~~~~~~
BC32071: Constraint type 'T' already specified for this type parameter.
Private Sub CM(Of V As {T, T})() Implements IC(Of T, T).CM
~
BC32078: 'Private Sub DM(Of V As A)()' cannot implement 'ID(Of I, A).Sub DM(Of V As {I, A})()' because they differ by type parameter constraints.
Private Sub DM(Of V As A)() Implements ID(Of I, A).DM
~~~~~~~~~~~~~~
BC32071: Constraint type 'A' already specified for this type parameter.
Private Sub DM(Of V As {A, I, A, I})() Implements ID(Of A, I).DM
~
BC32071: Constraint type 'I' already specified for this type parameter.
Private Sub DM(Of V As {A, I, A, I})() Implements ID(Of A, I).DM
~
BC32078: 'Private Sub EM(Of U As Structure)()' cannot implement 'IE(Of Object, ValueType).Sub EM(Of V As {Structure, Object, ValueType})()' because they differ by type parameter constraints.
Private Sub EM(Of U As Structure)() Implements IE(Of Object, ValueType).EM
~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Single method implementing multiple interface methods.
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T)
Sub AM(Of U As {T, Structure})()
End Interface
Interface IB(Of T)
Sub BX(Of U As {T, Class})()
End Interface
Class C(Of T)
Implements IA(Of T), IB(Of T)
Public Sub M(Of U As T)() Implements IA(Of T).AM, IB(Of T).BX
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32078: 'Public Sub M(Of U As T)()' cannot implement 'IA(Of T).Sub AM(Of U As {Structure, T})()' because they differ by type parameter constraints.
Public Sub M(Of U As T)() Implements IA(Of T).AM, IB(Of T).BX
~~~~~~~~~~~
BC32078: 'Public Sub M(Of U As T)()' cannot implement 'IB(Of T).Sub BX(Of U As {Class, T})()' because they differ by type parameter constraints.
Public Sub M(Of U As T)() Implements IA(Of T).AM, IB(Of T).BX
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Interface II
Sub m(Of T As I)()
End Interface
Class CLS
Implements II
Partial Private Sub X()
End Sub
Private Sub X(Of T)() Implements II.m
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC32078: 'Private Sub X(Of T)()' cannot implement 'II.Sub m(Of T As I)()' because they differ by type parameter constraints.
Private Sub X(Of T)() Implements II.m
~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC32078ERR_ImplementsWithConstraintMismatch3_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Interface II
Sub m(Of T As I)()
End Interface
Class CLS
Implements II
Partial Private Sub X(Of T)()
End Sub
Private Sub X(Of T)() Implements II.m
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC32078: 'Private Sub X(Of T)()' cannot implement 'II.Sub m(Of T As I)()' because they differ by type parameter constraints.
Private Sub X(Of T)() Implements II.m
~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC32080ERR_HandlesInvalidOnGenericMethod()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="HandlesInvalidOnGenericMethod">
<file name="a.vb"><![CDATA[
Class A
Event X()
Sub Goo(Of T)() Handles Me.X
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32080: Generic methods cannot use 'Handles' clause.
Sub Goo(Of T)() Handles Me.X
~~~
BC31029: Method 'Goo' cannot handle event 'X' because they do not have a compatible signature.
Sub Goo(Of T)() Handles Me.X
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32081ERR_MultipleNewConstraints()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MultipleNewConstraints">
<file name="a.vb"><![CDATA[
Imports System
Class C(Of T As {New, New})
Sub M(Of U As {New, Class, New})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32081: 'New' constraint cannot be specified multiple times for the same type parameter.
Class C(Of T As {New, New})
~~~
BC32081: 'New' constraint cannot be specified multiple times for the same type parameter.
Sub M(Of U As {New, Class, New})()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32082ERR_MustInheritForNewConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustInheritForNewConstraint2">
<file name="a.vb"><![CDATA[
Class C1(Of T)
Dim x As New C2(Of Base).C2Inner(Of Derived)
Sub New()
End Sub
End Class
Class Base
End Class
MustInherit Class Derived
Inherits Base
Public Sub New()
End Sub
End Class
Class C2(Of T As New)
Class C2Inner(Of S As {T, Derived, New})
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32082: Type argument 'Derived' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter 'S'.
Dim x As New C2(Of Base).C2Inner(Of Derived)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32083ERR_NoSuitableNewForNewConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoSuitableNewForNewConstraint2">
<file name="a.vb"><![CDATA[
Class [Public]
Public Sub New()
End Sub
End Class
Class [Friend]
Friend Sub New()
End Sub
End Class
Class ProtectedFriend
Protected Friend Sub New()
End Sub
End Class
Class [Protected]
Protected Sub New()
End Sub
End Class
Class [Private]
Private Sub New()
End Sub
End Class
Interface [Interface]
End Interface
Structure [Structure]
End Structure
Class C
Function F(Of T As New)() As T
Return New T
End Function
Sub M()
Dim o
o = F(Of [Public])()
o = F(Of [Friend])()
o = F(Of [ProtectedFriend])()
o = F(Of [Protected])()
o = F(Of [Private])()
o = F(Of [Interface])()
o = F(Of [Structure])()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32083: Type argument '[Friend]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Friend])()
~~~~~~~~~~~~~~
BC32083: Type argument 'ProtectedFriend' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [ProtectedFriend])()
~~~~~~~~~~~~~~~~~~~~~~~
BC32083: Type argument '[Protected]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Protected])()
~~~~~~~~~~~~~~~~~
BC32083: Type argument '[Private]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Private])()
~~~~~~~~~~~~~~~
BC32083: Type argument '[Interface]' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = F(Of [Interface])()
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
' Constructors with optional and params args
' should not be considered parameterless.
<Fact()>
Public Sub BC32083ERR_NoSuitableNewForNewConstraint2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NoSuitableNewForNewConstraint2">
<file name="a.vb"><![CDATA[
Class A
Public Sub New(Optional o As Object = Nothing)
End Sub
End Class
Class B
Public Sub New(ParamArray o As Object())
End Sub
End Class
Class C(Of T As New)
Shared Sub M(Of U As New)()
Dim o
o = New A()
o = New C(Of A)()
M(Of A)()
o = New B()
o = New C(Of B)()
M(Of B)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32083: Type argument 'A' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = New C(Of A)()
~
BC32083: Type argument 'A' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'U'.
M(Of A)()
~~~~~~~
BC32083: Type argument 'B' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'T'.
o = New C(Of B)()
~
BC32083: Type argument 'B' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter 'U'.
M(Of B)()
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32084ERR_BadGenericParamForNewConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Structure S
End Structure
Class A
Shared Sub M(Of T As New)()
End Sub
End Class
Class B(Of T)
Overridable Sub M(Of U As T)()
End Sub
Shared Sub M(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As U, U)()
A.M(Of T1)()
A.M(Of T2)()
A.M(Of T3)()
A.M(Of T4)()
A.M(Of T5)()
A.M(Of T6)()
A.M(Of T7)()
End Sub
End Class
Class CI
Inherits B(Of I)
Public Overrides Sub M(Of UI As I)()
A.M(Of UI)()
End Sub
End Class
Class CS
Inherits B(Of S)
Public Overrides Sub M(Of US As S)()
A.M(Of US)()
End Sub
End Class
Class CA
Inherits B(Of A)
Public Overrides Sub M(Of UA As A)()
A.M(Of UA)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32084: Type parameter 'T1' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T1)()
~~~~~~~~
BC32084: Type parameter 'T2' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T2)()
~~~~~~~~
BC32084: Type parameter 'T5' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T5)()
~~~~~~~~
BC32084: Type parameter 'T6' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T6)()
~~~~~~~~
BC32084: Type parameter 'T7' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of T7)()
~~~~~~~~
BC32084: Type parameter 'UI' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of UI)()
~~~~~~~~
BC32084: Type parameter 'UA' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter 'T'.
A.M(Of UA)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32086ERR_DuplicateRawGenericTypeImport1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="DuplicateRawGenericTypeImport1">
<file name="a.vb"><![CDATA[
Imports ns1.c1(Of String)
Imports ns1.c1(Of Integer)
Namespace ns1
Public Class c1(Of t)
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32086: Generic type 'c1(Of t)' cannot be imported more than once.
Imports ns1.c1(Of Integer)
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32089ERR_NameSameAsMethodTypeParam1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NameSameAsMethodTypeParam1">
<file name="a.vb"><![CDATA[
Class c1
Function fun(Of T1, T2) (ByVal t1 As T1, ByVal t2 As T2) As Integer
Return 5
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32089: 't1' is already declared as a type parameter of this method.
Function fun(Of T1, T2) (ByVal t1 As T1, ByVal t2 As T2) As Integer
~~
BC32089: 't2' is already declared as a type parameter of this method.
Function fun(Of T1, T2) (ByVal t1 As T1, ByVal t2 As T2) As Integer
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32089ERR_NameSameAsMethodTypeParam1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NameSameAsMethodTypeParam1">
<file name="a.vb"><![CDATA[
Class c1
Sub sub1(Of T1, T2 As T1) (ByVal p1 As T1, ByVal t2 As T2)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32089: 't2' is already declared as a type parameter of this method.
Sub sub1(Of T1, T2 As T1) (ByVal p1 As T1, ByVal t2 As T2)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(543642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543642")>
Public Sub BC32090ERR_TypeParamNameFunctionNameCollision()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="TypeParamNameFunctionNameCollision">
<file name="a.vb"><![CDATA[
Module M
Function Goo(Of Goo)()
Return Nothing
End Function
' Allowed for Sub -- should not generate error below.
Sub Bar(Of Bar)()
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32090: Type parameter cannot have the same name as its defining function.
Function Goo(Of Goo)()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32101ERR_MultipleReferenceConstraints()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {Class, Class})
Sub M(Of U As {Class, New, Class})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32101: 'Class' constraint cannot be specified multiple times for the same type parameter.
Class C(Of T As {Class, Class})
~~~~~
BC32101: 'Class' constraint cannot be specified multiple times for the same type parameter.
Sub M(Of U As {Class, New, Class})()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32102ERR_MultipleValueConstraints()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class C(Of T As {Structure, Structure})
Sub M(Of U As {Structure, I, Structure})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32102: 'Structure' constraint cannot be specified multiple times for the same type parameter.
Class C(Of T As {Structure, Structure})
~~~~~~~~~
BC32102: 'Structure' constraint cannot be specified multiple times for the same type parameter.
Sub M(Of U As {Structure, I, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32103ERR_NewAndValueConstraintsCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {Structure, New})
Sub M(Of U As {New, Structure})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32103: 'New' constraint and 'Structure' constraint cannot be combined.
Class C(Of T As {Structure, New})
~~~
BC32103: 'New' constraint and 'Structure' constraint cannot be combined.
Sub M(Of U As {New, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32104ERR_RefAndValueConstraintsCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As {Structure, Class})
Sub M(Of U As {Class, Structure})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32104: 'Class' constraint and 'Structure' constraint cannot be combined.
Class C(Of T As {Structure, Class})
~~~~~
BC32104: 'Class' constraint and 'Structure' constraint cannot be combined.
Sub M(Of U As {Class, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Class B(Of T As Structure)
End Class
Class C
Shared Sub F(Of U As Structure)()
End Sub
Shared Sub M1(Of T1)()
Dim o = New B(Of T1)()
F(Of T1)()
End Sub
Shared Sub M2(Of T2 As Class)()
Dim o = New B(Of T2)()
F(Of T2)()
End Sub
Shared Sub M3(Of T3 As Structure)()
Dim o = New B(Of T3)()
F(Of T3)()
End Sub
Shared Sub M4(Of T4 As New)()
Dim o = New B(Of T4)()
F(Of T4)()
End Sub
Shared Sub M5(Of T5 As I)()
Dim o = New B(Of T5)()
F(Of T5)()
End Sub
Shared Sub M6(Of T6 As A)()
Dim o = New B(Of T6)()
F(Of T6)()
End Sub
Shared Sub M7(Of T7 As U, U)()
Dim o = New B(Of T7)()
F(Of T7)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'T1' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T1)()
~~
BC32105: Type argument 'T1' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T1)()
~~~~~~~~
BC32105: Type argument 'T2' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T2)()
~~
BC32105: Type argument 'T2' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T2)()
~~~~~~~~
BC32105: Type argument 'T4' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T4)()
~~
BC32105: Type argument 'T4' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T4)()
~~~~~~~~
BC32105: Type argument 'T5' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T5)()
~~
BC32105: Type argument 'T5' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T5)()
~~~~~~~~
BC32105: Type argument 'T6' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T6)()
~~
BC32105: Type argument 'T6' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T6)()
~~~~~~~~
BC32105: Type argument 'T7' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim o = New B(Of T7)()
~~
BC32105: Type argument 'T7' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of T7)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C
Shared Sub F(Of T As Structure, U As Structure)(a As T, b As U)
End Sub
Shared Sub M(a As Integer, b As Object)
F(b, a)
F(a, b)
F(Of Integer, Object)(a, b)
End Sub
End Class
]]></file>
</compilation>)
' TODO: Dev10 highlights the first type parameter or argument that
' violates a generic method constraint, not the entire expression.
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
F(b, a)
~
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(a, b)
~
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'U'.
F(Of Integer, Object)(a, b)
~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports N.A(Of Object).B(Of String)
Imports C = N.A(Of Object).B(Of String)
Namespace N
Class A(Of T As Structure)
Friend Class B(Of U As Structure)
End Class
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
Imports N.A(Of Object).B(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'U'.
Imports N.A(Of Object).B(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
Imports C = N.A(Of Object).B(Of String)
~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'U'.
Imports C = N.A(Of Object).B(Of String)
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I(Of T As Structure)
Sub M(Of U As I(Of U))()
End Interface
Class A(Of T As Structure)
Friend Interface I
End Interface
End Class
Class B(Of T As I(Of T), U As A(Of U).I)
Sub M(Of V As A(Of V).I)()
End Sub
End Class
]]></file>
</compilation>)
' TODO: Dev10 reports errors on the type argument violating the
' constraint rather than the type with type argument (reporting
' error in U in I(Of U) rather than entire I(Of U) for instance).
Dim expectedErrors1 = <errors><![CDATA[
BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T'.
Sub M(Of U As I(Of U))()
~~~~~~~
BC32105: Type argument 'T' does not satisfy the 'Structure' constraint for type parameter 'T'.
Class B(Of T As I(Of T), U As A(Of U).I)
~~~~~~~
BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T'.
Class B(Of T As I(Of T), U As A(Of U).I)
~~~~~~~~~
BC32105: Type argument 'V' does not satisfy the 'Structure' constraint for type parameter 'T'.
Sub M(Of V As A(Of V).I)()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32105ERR_BadTypeArgForStructConstraint2_4()
Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"N.A(Of Object).B(Of String)", "C=N.A(Of N.B).B(Of Object)"}))
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Class A(Of T As Structure)
Friend Class B(Of U As Structure)
End Class
End Class
Class B
End Class
End Namespace
]]></file>
</compilation>, options)
Dim expectedErrors = <errors><![CDATA[
BC32105: Error in project-level import 'C=N.A(Of N.B).B(Of Object)' at 'C=N.A(Of N.B).B(Of Object)' : Type argument 'B' does not satisfy the 'Structure' constraint for type parameter 'T'.
BC32105: Error in project-level import 'C=N.A(Of N.B).B(Of Object)' at 'C=N.A(Of N.B).B(Of Object)' : Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'U'.
BC32105: Error in project-level import 'N.A(Of Object).B(Of String)' at 'N.A(Of Object).B(Of String)' : Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T'.
BC32105: Error in project-level import 'N.A(Of Object).B(Of String)' at 'N.A(Of Object).B(Of String)' : Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'U'.
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC32106ERR_BadTypeArgForRefConstraint2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
End Interface
Class A
End Class
Class B(Of T As Class)
End Class
Class C
Shared Sub F(Of T As Class)()
End Sub
Shared Sub M1(Of T1)()
Dim o = New B(Of T1)()
F(Of T1)()
End Sub
Shared Sub M2(Of T2 As Class)()
Dim o = New B(Of T2)()
F(Of T2)()
End Sub
Shared Sub M3(Of T3 As Structure)()
Dim o = New B(Of T3)()
F(Of T3)()
End Sub
Shared Sub M4(Of T4 As New)()
Dim o = New B(Of T4)()
F(Of T4)()
End Sub
Shared Sub M5(Of T5 As I)()
Dim o = New B(Of T5)()
F(Of T5)()
End Sub
Shared Sub M6(Of T6 As A)()
Dim o = New B(Of T6)()
F(Of T6)()
End Sub
Shared Sub M7(Of T7 As U, U)()
Dim o = New B(Of T7)()
F(Of T7)()
End Sub
Shared Sub M8()
Dim o = New B(Of Integer?)()
F(Of Integer?)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32106: Type argument 'T1' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T1)()
~~
BC32106: Type argument 'T1' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T1)()
~~~~~~~~
BC32106: Type argument 'T3' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T3)()
~~
BC32106: Type argument 'T3' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T3)()
~~~~~~~~
BC32106: Type argument 'T4' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T4)()
~~
BC32106: Type argument 'T4' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T4)()
~~~~~~~~
BC32106: Type argument 'T5' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T5)()
~~
BC32106: Type argument 'T5' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T5)()
~~~~~~~~
BC32106: Type argument 'T7' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of T7)()
~~
BC32106: Type argument 'T7' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of T7)()
~~~~~~~~
BC32106: Type argument 'Integer?' does not satisfy the 'Class' constraint for type parameter 'T'.
Dim o = New B(Of Integer?)()
~~~~~~~~
BC32106: Type argument 'Integer?' does not satisfy the 'Class' constraint for type parameter 'T'.
F(Of Integer?)()
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32107ERR_RefAndClassTypeConstrCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
Inherits A
End Class
Interface IA(Of T, U As {A, T, Class})
End Interface
Interface IB
Sub M(Of T, U As {T, Class, A})()
End Interface
MustInherit Class C(Of T, U)
MustOverride Sub M(Of V As {T, Class, U})()
End Class
MustInherit Class D
Inherits C(Of A, B)
Public Overrides Sub M(Of V As {A, Class, B})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32107: 'Class' constraint and a specific class type constraint cannot be combined.
Interface IA(Of T, U As {A, T, Class})
~~~~~
BC32107: 'Class' constraint and a specific class type constraint cannot be combined.
Sub M(Of T, U As {T, Class, A})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32108ERR_ValueAndClassTypeConstrCombined()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
Inherits A
End Class
Interface IA(Of T, U As {A, T, Structure})
End Interface
Interface IB
Sub M(Of T, U As {T, Structure, A})()
End Interface
MustInherit Class C(Of T, U)
MustOverride Sub M(Of V As {T, Structure, U})()
End Class
MustInherit Class D
Inherits C(Of A, B)
Public Overrides Sub M(Of V As {A, Structure, B})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32108: 'Structure' constraint and a specific class type constraint cannot be combined.
Interface IA(Of T, U As {A, T, Structure})
~~~~~~~~~
BC32108: 'Structure' constraint and a specific class type constraint cannot be combined.
Sub M(Of T, U As {T, Structure, A})()
~
BC32119: Constraint 'Structure' conflicts with the constraint 'Class A' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {A, Structure, B})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32109ERR_ConstraintClashIndirectIndirect4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Interface IA(Of T As A, U As B, V As U, W As {T, U, V})
End Interface
Interface IB(Of T1 As A, T2 As B)
Sub M1(Of T3 As {T1, T2})()
Sub M2(Of T3 As {T2, T1})()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32109: Indirect constraint 'Class B' obtained from the type parameter constraint 'U' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T'.
Interface IA(Of T As A, U As B, V As U, W As {T, U, V})
~
BC32109: Indirect constraint 'Class B' obtained from the type parameter constraint 'V' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T'.
Interface IA(Of T As A, U As B, V As U, W As {T, U, V})
~
BC32109: Indirect constraint 'Class B' obtained from the type parameter constraint 'T2' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Sub M1(Of T3 As {T1, T2})()
~~
BC32109: Indirect constraint 'Class A' obtained from the type parameter constraint 'T1' conflicts with the indirect constraint 'Class B' obtained from the type parameter constraint 'T2'.
Sub M2(Of T3 As {T2, T1})()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32110ERR_ConstraintClashDirectIndirect3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Interface IA(Of T1 As A, T2 As B, T3 As {Structure, T1, T2})
End Interface
Interface IB(Of T1 As A)
Sub M(Of T2, T3 As {T2, B, T1})()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32110: Constraint 'Structure' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Interface IA(Of T1 As A, T2 As B, T3 As {Structure, T1, T2})
~~~~~~~~~
BC32110: Constraint 'Structure' conflicts with the indirect constraint 'Class B' obtained from the type parameter constraint 'T2'.
Interface IA(Of T1 As A, T2 As B, T3 As {Structure, T1, T2})
~~~~~~~~~
BC32110: Constraint 'Class B' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Sub M(Of T2, T3 As {T2, B, T1})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32110ERR_ConstraintClashDirectIndirect3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Class C
End Class
Class D(Of T1 As A, T2 As B)
Sub M(Of U1 As T1, U2 As T2, V As {C, T1, T2})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32110: Constraint 'Class C' conflicts with the indirect constraint 'Class A' obtained from the type parameter constraint 'T1'.
Sub M(Of U1 As T1, U2 As T2, V As {C, T1, T2})()
~
BC32110: Constraint 'Class C' conflicts with the indirect constraint 'Class B' obtained from the type parameter constraint 'T2'.
Sub M(Of U1 As T1, U2 As T2, V As {C, T1, T2})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32110ERR_ConstraintClashDirectIndirect3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Enum E
A
End Enum
MustInherit Class A(Of T1, T2)
MustOverride Sub M(Of U1 As T1, U2 As {T2, U1})()
End Class
Class B0
Inherits A(Of Integer, Integer)
Public Overrides Sub M(Of U1 As Integer, U2 As {Integer, U1})()
End Sub
End Class
Class B1
Inherits A(Of Integer, Object)
Public Overrides Sub M(Of U1 As Integer, U2 As {Object, U1})()
End Sub
End Class
Class B2
Inherits A(Of Integer, Short)
Public Overrides Sub M(Of U1 As Integer, U2 As {Short, U1})()
End Sub
End Class
Class B3
Inherits A(Of Integer, Long)
Public Overrides Sub M(Of U1 As Integer, U2 As {Long, U1})()
End Sub
End Class
Class B4
Inherits A(Of Integer, UInteger)
Public Overrides Sub M(Of U1 As Integer, U2 As {UInteger, U1})()
End Sub
End Class
Class B5
Inherits A(Of Integer, E)
Public Overrides Sub M(Of U1 As Integer, U2 As {E, U1})()
End Sub
End Class
Class C0
Inherits A(Of Object(), Object())
Public Overrides Sub M(Of U1 As Object(), U2 As {Object(), U1})()
End Sub
End Class
Class C1
Inherits A(Of Object(), String())
Public Overrides Sub M(Of U1 As Object(), U2 As {String(), U1})()
End Sub
End Class
Class C2
Inherits A(Of Integer(), Integer())
Public Overrides Sub M(Of U1 As Integer(), U2 As {Integer(), U1})()
End Sub
End Class
Class C3
Inherits A(Of Integer(), E())
Public Overrides Sub M(Of U1 As Integer(), U2 As {E(), U1})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32110: Constraint 'Short' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {Short, U1})()
~~~~~
BC32110: Constraint 'Long' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {Long, U1})()
~~~~
BC32110: Constraint 'UInteger' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {UInteger, U1})()
~~~~~~~~
BC32110: Constraint 'Enum E' conflicts with the indirect constraint 'Integer' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer, U2 As {E, U1})()
~
BC32110: Constraint 'E()' conflicts with the indirect constraint 'Integer()' obtained from the type parameter constraint 'U1'.
Public Overrides Sub M(Of U1 As Integer(), U2 As {E(), U1})()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32111ERR_ConstraintClashIndirectDirect3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
Class C
End Class
Interface IA(Of T As A, U As {T, Structure})
End Interface
Interface IB(Of T1 As A)
Sub M(Of T2, T3 As {T2, T1, B})()
End Interface
MustInherit Class D(Of T1, T2)
MustOverride Sub M(Of U As C, V As {U, T1, T2})()
End Class
Class E
Inherits D(Of A, B)
Public Overrides Sub M(Of U As C, V As {U, A, B})()
End Sub
End Class
]]></file>
</compilation>)
' Note: Dev10 never seems to generate BC32111. Instead, Dev10 generates
' BC32110 in the following cases, which is essentially the same error
' with arguments reordered, but with the other constraint highlighted.
Dim expectedErrors1 = <errors><![CDATA[
BC32111: Indirect constraint 'Class A' obtained from the type parameter constraint 'T' conflicts with the constraint 'Structure'.
Interface IA(Of T As A, U As {T, Structure})
~
BC32111: Indirect constraint 'Class A' obtained from the type parameter constraint 'T1' conflicts with the constraint 'Class B'.
Sub M(Of T2, T3 As {T2, T1, B})()
~~
BC32111: Indirect constraint 'Class C' obtained from the type parameter constraint 'U' conflicts with the constraint 'Class A'.
Public Overrides Sub M(Of U As C, V As {U, A, B})()
~
BC32111: Indirect constraint 'Class C' obtained from the type parameter constraint 'U' conflicts with the constraint 'Class B'.
Public Overrides Sub M(Of U As C, V As {U, A, B})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32113ERR_ConstraintCycle2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ConstraintCycle2">
<file name="a.vb"><![CDATA[
Class A(Of T1 As T2, T2 As T3, T3 As T4, T4 As T1)
End Class
Class B
Sub M(Of T As T)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32113: Type parameter 'T1' cannot be constrained to itself:
'T1' is constrained to 'T2'.
'T2' is constrained to 'T3'.
'T3' is constrained to 'T4'.
'T4' is constrained to 'T1'.
Class A(Of T1 As T2, T2 As T3, T3 As T4, T4 As T1)
~~
BC32113: Type parameter 'T' cannot be constrained to itself:
'T' is constrained to 'T'.
Sub M(Of T As T)()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32114ERR_TypeParamWithStructConstAsConst()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeParamWithStructConstAsConst">
<file name="a.vb"><![CDATA[
Interface I
End Interface
Interface IA(Of T As Structure, U As V, V As {T, New})
End Interface
Interface IB
Sub M(Of T As U, U As {I, V}, V As {I, Structure})()
End Interface
Interface IC(Of T1 As {I, Structure})
Sub M(Of T2 As T3, T3 As T1)()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32114: Type parameter with a 'Structure' constraint cannot be used as a constraint.
Interface IA(Of T As Structure, U As V, V As {T, New})
~
BC32114: Type parameter with a 'Structure' constraint cannot be used as a constraint.
Sub M(Of T As U, U As {I, V}, V As {I, Structure})()
~
BC32114: Type parameter with a 'Structure' constraint cannot be used as a constraint.
Sub M(Of T2 As T3, T3 As T1)()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub M()
Dim n1? As Nullable(Of Integer) = New Nullable(Of Nullable(Of Integer))
Dim n2 As Nullable(Of Integer)? = New Nullable(Of Integer)?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n1? As Nullable(Of Integer) = New Nullable(Of Nullable(Of Integer))
~~~~~~~~~~~~~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n1? As Nullable(Of Integer) = New Nullable(Of Nullable(Of Integer))
~~~~~~~~~~~~~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n2 As Nullable(Of Integer)? = New Nullable(Of Integer)?
~~~~~~~~~~~~~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim n2 As Nullable(Of Integer)? = New Nullable(Of Integer)?
~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As Structure)
Shared Sub F(Of U As Structure)()
End Sub
Shared Sub M()
Dim o = New C(Of Integer?)()
F(Of T?)()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o = New C(Of Integer?)()
~~~~~~~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'U'. Only non-nullable 'Structure' types are allowed.
F(Of T?)()
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class C(Of T As Structure)
Shared Sub F(Of U As Structure)()
End Sub
Shared Function M() As System.Action
Return AddressOf F(Of T?)
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'U'. Only non-nullable 'Structure' types are allowed.
Return AddressOf F(Of T?)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32115ERR_NullableDisallowedForStructConstr1_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Structure S
End Structure
MustInherit Class A(Of T)
Friend MustOverride Sub M(Of U As T)()
End Class
Class B
Inherits A(Of S?)
Friend Overrides Sub M(Of U As S?)()
Dim o1? As U
Dim o2 As Nullable(Of U) = New Nullable(Of U)
Dim o3 As U? = New U?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC42024: Unused local variable: 'o1'.
Dim o1? As U
~~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o1? As U
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o2 As Nullable(Of U) = New Nullable(Of U)
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o2 As Nullable(Of U) = New Nullable(Of U)
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o3 As U? = New U?
~
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim o3 As U? = New U?
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32117ERR_NoAccessibleNonGeneric1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoAccessibleNonGeneric1">
<file name="a.vb"><![CDATA[
Module M1
Dim x As New C1.C2
End Module
Public Class C1
Public Class C2(Of T)
End Class
Public Class C2(Of U, V)
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32042: Too few type arguments to 'C1.C2(Of T)'.
Dim x As New C1.C2
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32118ERR_NoAccessibleGeneric1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoAccessibleGeneric1">
<file name="a.vb"><![CDATA[
Module M1
Dim x As New C1(Of Object).C2(Of SByte, Byte)
End Module
Public Class C1
Public Class C2(Of T)
End Class
Public Class C2(Of U, V)
End Class
End Class
Public Class C1(Of T)
Public Class C2
End Class
Public Class C2(Of X)
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32045: 'C1(Of Object).C2' has no type parameters and so cannot have type arguments.
Dim x As New C1(Of Object).C2(Of SByte, Byte)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32119ERR_ConflictingDirectConstraints3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A(Of T1, T2, T3)
MustOverride Sub M(Of U As {T1, T2, T3, Structure})()
End Class
Class B
Inherits A(Of C1, C2, C3)
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
End Sub
End Class
Class C1
End Class
Class C2
End Class
Class C3
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32119: Constraint 'Class C2' conflicts with the constraint 'Class C1' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
~~
BC32119: Constraint 'Class C3' conflicts with the constraint 'Class C1' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
~~
BC32119: Constraint 'Structure' conflicts with the constraint 'Class C1' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {C1, C2, C3, Structure})()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32119ERR_ConflictingDirectConstraints3_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
End Class
Class B
End Class
MustInherit Class C(Of T1, T2)
MustOverride Sub M(Of U As {T1, T2})()
End Class
Class D
Inherits C(Of A, B)
Public Overrides Sub M(Of U As {A, B})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32119: Constraint 'Class B' conflicts with the constraint 'Class A' already specified for type parameter 'U'.
Public Overrides Sub M(Of U As {A, B})()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32119ERR_ConflictingDirectConstraints3_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Enum E
A
End Enum
MustInherit Class A(Of T, U)
MustOverride Sub M(Of V As {T, U})()
End Class
Class B0
Inherits A(Of Integer, Integer)
Public Overrides Sub M(Of V As {Integer})()
End Sub
End Class
Class B1
Inherits A(Of Integer, Object)
Public Overrides Sub M(Of V As {Integer, Object})()
End Sub
End Class
Class B2
Inherits A(Of Integer, Short)
Public Overrides Sub M(Of V As {Integer, Short})()
End Sub
End Class
Class B3
Inherits A(Of Integer, Long)
Public Overrides Sub M(Of V As {Integer, Long})()
End Sub
End Class
Class B4
Inherits A(Of Integer, UInteger)
Public Overrides Sub M(Of V As {Integer, UInteger})()
End Sub
End Class
Class B5
Inherits A(Of Integer, E)
Public Overrides Sub M(Of V As {Integer, E})()
End Sub
End Class
Class C0
Inherits A(Of Object(), Object())
Public Overrides Sub M(Of V As {Object()})()
End Sub
End Class
Class C1
Inherits A(Of Object(), String())
Public Overrides Sub M(Of V As {Object(), String()})()
End Sub
End Class
Class C2
Inherits A(Of Integer(), Integer())
Public Overrides Sub M(Of V As {Integer()})()
End Sub
End Class
Class C3
Inherits A(Of Integer(), E())
Public Overrides Sub M(Of V As {Integer(), E()})()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32119: Constraint 'Short' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, Short})()
~~~~~
BC32119: Constraint 'Long' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, Long})()
~~~~
BC32119: Constraint 'UInteger' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, UInteger})()
~~~~~~~~
BC32119: Constraint 'Enum E' conflicts with the constraint 'Integer' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer, E})()
~
BC32119: Constraint 'E()' conflicts with the constraint 'Integer()' already specified for type parameter 'V'.
Public Overrides Sub M(Of V As {Integer(), E()})()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543643")>
Public Sub BC32120ERR_InterfaceUnifiesWithInterface2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnifiesWithInterface2">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Interface derivedInterface(Of t1, t2)
Inherits interfaceA(Of t1), interfaceA(Of t2)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32120: Cannot inherit interface 'interfaceA(Of t2)' because it could be identical to interface 'interfaceA(Of t1)' for some type arguments.
Inherits interfaceA(Of t1), interfaceA(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(1042692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042692")>
<Fact()>
Public Sub BC32120ERR_InterfaceUnifiesWithInterface2_SubstituteWithOtherTypeParameter()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA(Of T, U)
End Interface
Interface IB(Of T, U)
Inherits IA(Of U, Object), IA(Of T, U)
End Interface
]]></file>
</compilation>)
compilation1.AssertTheseDeclarationDiagnostics(
<errors><![CDATA[
BC32120: Cannot inherit interface 'IA(Of T, U)' because it could be identical to interface 'IA(Of U, Object)' for some type arguments.
Inherits IA(Of U, Object), IA(Of T, U)
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact(), WorkItem(543726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543726")>
Public Sub BC32121ERR_BaseUnifiesWithInterfaces3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseUnifiesWithInterfaces3">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
Sub goo(Of G As T)(ByVal x As G)
End Interface
Interface I2(Of T)
Inherits I1(Of T)
End Interface
Interface I02(Of T, G)
Inherits I1(Of T), I2(Of G)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32121: Cannot inherit interface 'I2(Of G)' because the interface 'I1(Of G)' from which it inherits could be identical to interface 'I1(Of T)' for some type arguments.
Inherits I1(Of T), I2(Of G)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543727")>
Public Sub BC32122ERR_InterfaceBaseUnifiesWithBase4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceBaseUnifiesWithBase4">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Interface interfaceX(Of v)
Inherits interfaceA(Of v)
End Interface
Public Interface interfaceY(Of w)
Inherits interfaceA(Of w)
End Interface
Public Interface derivedInterface(Of t1, t2)
Inherits interfaceX(Of t1), interfaceY(Of t2)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32122: Cannot inherit interface 'interfaceY(Of t2)' because the interface 'interfaceA(Of t2)' from which it inherits could be identical to interface 'interfaceA(Of t1)' from which the interface 'interfaceX(Of t1)' inherits for some type arguments.
Inherits interfaceX(Of t1), interfaceY(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543729")>
Public Sub BC32123ERR_InterfaceUnifiesWithBase3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceUnifiesWithBase3">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
Inherits interfaceX(Of u)
End Interface
Public Interface interfaceX(Of v)
End Interface
Public Interface derivedInterface(Of t1, t2)
Inherits interfaceA(Of t1), interfaceX(Of t2)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32123: Cannot inherit interface 'interfaceX(Of t2)' because it could be identical to interface 'interfaceX(Of t1)' from which the interface 'interfaceA(Of t1)' inherits for some type arguments.
Inherits interfaceA(Of t1), interfaceX(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543643")>
Public Sub BC32072ERR_InterfacePossiblyImplTwice2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfacePossiblyImplTwice2">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Class derivedClass(Of t1, t2)
Implements interfaceA(Of t1), interfaceA(Of t2)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32072: Cannot implement interface 'interfaceA(Of t2)' because its implementation could conflict with the implementation of another implemented interface 'interfaceA(Of t1)' for some type arguments.
Implements interfaceA(Of t1), interfaceA(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543726")>
Public Sub BC32131ERR_ClassInheritsBaseUnifiesWithInterfaces3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassInheritsBaseUnifiesWithInterfaces3">
<file name="a.vb"><![CDATA[
Interface I1(Of T)
End Interface
Interface I2(Of T)
Inherits I1(Of T)
End Interface
Class I02(Of T, G)
Implements I1(Of T), I2(Of G)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32131: Cannot implement interface 'I2(Of G)' because the interface 'I1(Of G)' from which it inherits could be identical to implemented interface 'I1(Of T)' for some type arguments.
Implements I1(Of T), I2(Of G)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543727")>
Public Sub BC32132ERR_ClassInheritsInterfaceBaseUnifiesWithBase4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassInheritsInterfaceBaseUnifiesWithBase4">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
End Interface
Public Interface interfaceX(Of v)
Inherits interfaceA(Of v)
End Interface
Public Interface interfaceY(Of w)
Inherits interfaceA(Of w)
End Interface
Public Class derivedClass(Of t1, t2)
Implements interfaceX(Of t1), interfaceY(Of t2)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32132: Cannot implement interface 'interfaceY(Of t2)' because the interface 'interfaceA(Of t2)' from which it inherits could be identical to interface 'interfaceA(Of t1)' from which the implemented interface 'interfaceX(Of t1)' inherits for some type arguments.
Implements interfaceX(Of t1), interfaceY(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543729")>
Public Sub BC32133ERR_ClassInheritsInterfaceUnifiesWithBase3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassInheritsInterfaceUnifiesWithBase3">
<file name="a.vb"><![CDATA[
Public Interface interfaceA(Of u)
Inherits interfaceX(Of u)
End Interface
Public Interface interfaceX(Of v)
End Interface
Public Class derivedClass(Of t1, t2)
Implements interfaceA(Of t1), interfaceX(Of t2)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32133: Cannot implement interface 'interfaceX(Of t2)' because it could be identical to interface 'interfaceX(Of t1)' from which the implemented interface 'interfaceA(Of t1)' inherits for some type arguments.
Implements interfaceA(Of t1), interfaceX(Of t2)
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32125ERR_InterfaceMethodImplsUnify3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InterfaceMethodImplsUnify3">
<file name="a.vb"><![CDATA[
Public Interface iFace1(Of t)
Sub testSub()
End Interface
Public Interface iFace2(Of u)
Inherits iFace1(Of u)
End Interface
Public Class testClass(Of y, z)
Implements iFace1(Of y), iFace2(Of z)
Public Sub testSuby() Implements iFace1(Of y).testSub
End Sub
Public Sub testSubz() Implements iFace1(Of z).testSub
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32131: Cannot implement interface 'iFace2(Of z)' because the interface 'iFace1(Of z)' from which it inherits could be identical to implemented interface 'iFace1(Of y)' for some type arguments.
Implements iFace1(Of y), iFace2(Of z)
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32200ERR_ShadowingTypeOutsideClass1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingTypeOutsideClass1">
<file name="a.vb"><![CDATA[
Public Shadows Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32200: 'C1' cannot be declared 'Shadows' outside of a class, structure, or interface.
Public Shadows Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32201ERR_PropertySetParamCollisionWithValue()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PropertySetParamCollisionWithValue">
<file name="a.vb"><![CDATA[
Interface IA
ReadOnly Property Goo(ByVal value As String) As String
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32201: Property parameters cannot have the name 'Value'.
ReadOnly Property Goo(ByVal value As String) As String
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32201ERR_PropertySetParamCollisionWithValue_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="PropertySetParamCollisionWithValue">
<file name="a.vb"><![CDATA[
Structure S
Property P(Index, Value)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Structure
Class C
WriteOnly Property P(value)
Set(val)
End Set
End Property
ReadOnly Property Value(Value)
Get
Return Nothing
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32201: Property parameters cannot have the name 'Value'.
Property P(Index, Value)
~~~~~
BC32201: Property parameters cannot have the name 'Value'.
WriteOnly Property P(value)
~~~~~
BC32201: Property parameters cannot have the name 'Value'.
ReadOnly Property Value(Value)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC32205ERR_WithEventsNameTooLong()
Dim witheventname = New String("A"c, 1020)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Module Program
' Declare a WithEvents variable.
Dim WithEvents <%= witheventname %> As New EventClass
' Call the method that raises the object's events.
Sub TestEvents()
<%= witheventname %>.RaiseEvents()
End Sub
' Declare an event handler that handles multiple events.
Sub EClass_EventHandler() Handles <%= witheventname %>.XEvent, <%= witheventname %>.YEvent
Console.WriteLine("Received Event.")
End Sub
Class EventClass
Public Event XEvent()
Public Event YEvent()
' RaiseEvents raises both events.
Sub RaiseEvents()
RaiseEvent XEvent()
RaiseEvent YEvent()
End Sub
End Class
End Module
</file>
</compilation>)
Dim squiggle As New String("~"c, witheventname.Length())
Dim expectedErrors1 = <errors>
BC37220: Name 'get_<%= witheventname %>' exceeds the maximum length allowed in metadata.
Dim WithEvents <%= witheventname %> As New EventClass
<%= squiggle %>
BC37220: Name 'set_<%= witheventname %>' exceeds the maximum length allowed in metadata.
Dim WithEvents <%= witheventname %> As New EventClass
<%= squiggle %>
</errors>
CompilationUtils.AssertNoDeclarationDiagnostics(compilation1)
CompilationUtils.AssertTheseEmitDiagnostics(compilation1, expectedErrors1)
End Sub
' BC32206ERR_SxSIndirectRefHigherThanDirectRef1: See ReferenceManagerTests.ReferenceBinding_SymbolUsed
' BC32208ERR_DuplicateReference2: See ReferenceManagerTests.BC32208ERR_DuplicateReference2
' BC32208ERR_DuplicateReference2_2: See ReferenceManagerTests.BC32208ERR_DuplicateReference2_2
<Fact()>
Public Sub BC32501ERR_ComClassAndReservedAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassAndReservedAttribute1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
<ComClass("287E43DD-5282-452C-91AF-8F1B34290CA3"), System.Runtime.InteropServices.ComSourceInterfaces(GetType(a), GetType(a))> _
Public Class c
Public Sub GOO()
End Sub
End Class
Public Interface a
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class.
Public Class c
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32504ERR_ComClassRequiresPublicClass2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassRequiresPublicClass2">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
Class C
Protected Class C1
<ComClass()>
Class C2
End Class
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'C2' because its container 'C1' is not declared 'Public'.
Class C2
~~
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C2' but 'C2' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Class C2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32507ERR_ComClassDuplicateGuids1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassDuplicateGuids1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
<ComClass("22904D63-46C2-47b6-97A7-8970D8EC789A", "22904D63-46C2-47b6-97A7-8970D8EC789A", "22904D63-46C2-47b6-97A7-8970D8EC789A")>
Public Class Class11
Sub test()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32507: 'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on 'Class11' cannot have the same value.
Public Class Class11
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32508ERR_ComClassCantBeAbstract0()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassCantBeAbstract0">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
<ComClass()>
Public MustInherit Class C
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32508: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.
Public MustInherit Class C
~
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C' but 'C' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Public MustInherit Class C
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC32509ERR_ComClassRequiresPublicClass1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassRequiresPublicClass1">
<file name="a.vb"><![CDATA[
Imports Microsoft.VisualBasic
Class C
<ComClass()>
Protected Class C1
End Class
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32509: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'C1' because it is not declared 'Public'.
Protected Class C1
~~
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C1' but 'C1' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Protected Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC33009ERR_ParamArrayIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamArrayIllegal1">
<file name="a.vb"><![CDATA[
Class C1
Delegate Sub Goo(ByVal ParamArray args() As String)
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC33009: 'Delegate' parameters cannot be declared 'ParamArray'.
Delegate Sub Goo(ByVal ParamArray args() As String)
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33010ERR_OptionalIllegal1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OptionalIllegal1">
<file name="a.vb"><![CDATA[
Class C1
Event E(Optional ByVal z As String = "")
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC33010: 'Event' parameters cannot be declared 'Optional'.
Event E(Optional ByVal z As String = "")
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33011ERR_OperatorMustBePublic()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorMustBePublic">
<file name="a.vb"><![CDATA[
Public Structure S1
Private Shared Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorMustBePublic, "Private").WithArguments("Private"))
End Sub
<Fact()>
Public Sub BC33012ERR_OperatorMustBeShared()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorMustBeShared">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorMustBeShared, "IsFalse"))
End Sub
<Fact()>
Public Sub BC33013ERR_BadOperatorFlags1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadOperatorFlags1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Overridable Shared Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BadOperatorFlags1, "Overridable").WithArguments("Overridable"))
End Sub
<Fact()>
Public Sub BC33014ERR_OneParameterRequired1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OneParameterRequired1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator IsFalse(ByVal z As S1, ByVal x As S1) As Boolean
Dim b As Boolean
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As S1, ByVal x As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_OneParameterRequired1, "IsFalse").WithArguments("IsFalse"),
Diagnostic(ERRID.ERR_OneParameterRequired1, "IsTrue").WithArguments("IsTrue"))
End Sub
<Fact()>
Public Sub BC33015ERR_TwoParametersRequired1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="TwoParametersRequired1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator And(ByVal x As S1) As S1
Dim r As New S1
Return r
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_TwoParametersRequired1, "And").WithArguments("And"))
End Sub
' Roslyn extra errors
<Fact()>
Public Sub BC33016ERR_OneOrTwoParametersRequired1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OneOrTwoParametersRequired1">
<file name="a.vb"><![CDATA[
Public Class C1
Public Shared Operator +
(ByVal p1 As C1, ByVal p2 As Integer) As Integer
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExpectedLparen, ""),
Diagnostic(ERRID.ERR_ExpectedRparen, ""),
Diagnostic(ERRID.ERR_Syntax, "("),
Diagnostic(ERRID.ERR_OneOrTwoParametersRequired1, "+").WithArguments("+"),
Diagnostic(ERRID.WRN_DefAsgNoRetValOpRef1, "End Operator").WithArguments("+"))
' Dim expectedErrors1 = <errors><![CDATA[
'BC30199: '(' expected.
' Public Shared Operator +
' ~
'BC33016: Operator '+' must have either one or two parameters.
' Public Shared Operator +
' ~
'BC30035: Syntax error.
' (ByVal p1 As C1, ByVal p2 As Integer) As Integer
' ~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33017ERR_ConvMustBeWideningOrNarrowing()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConvMustBeWideningOrNarrowing">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator CType(ByVal x As S1) As Integer
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConvMustBeWideningOrNarrowing, "CType"))
End Sub
<Fact()>
Public Sub BC33019ERR_InvalidSpecifierOnNonConversion1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="InvalidSpecifierOnNonConversion1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator And(ByVal x As S1, ByVal y As S1) As Integer
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidSpecifierOnNonConversion1, "Widening").WithArguments("Widening"))
End Sub
<Fact()>
Public Sub BC33020ERR_UnaryParamMustBeContainingType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnaryParamMustBeContainingType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator IsTrue(ByVal x As Integer) As Boolean
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_UnaryParamMustBeContainingType1, "IsTrue").WithArguments("S1"))
End Sub
<Fact()>
Public Sub BC33021ERR_BinaryParamMustBeContainingType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BinaryParamMustBeContainingType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator And(ByVal x As Integer, ByVal y As Integer) As Boolean
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_BinaryParamMustBeContainingType1, "And").WithArguments("S1"))
End Sub
<Fact()>
Public Sub BC33022ERR_ConvParamMustBeContainingType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConvParamMustBeContainingType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator CType(ByVal x As Integer) As Boolean
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConvParamMustBeContainingType1, "CType").WithArguments("S1"))
End Sub
<Fact()>
Public Sub BC33023ERR_OperatorRequiresBoolReturnType1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorRequiresBoolReturnType1">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Operator IsTrue(ByVal x As S1) As Integer
Return 1
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorRequiresBoolReturnType1, "IsTrue").WithArguments("IsTrue"))
End Sub
<Fact()>
Public Sub BC33024ERR_ConversionToSameType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToSameType">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator CType(ByVal x As S1) As S1
Return Nothing
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToSameType, "CType"))
End Sub
<Fact()>
Public Sub BC33025ERR_ConversionToInterfaceType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToInterfaceType">
<file name="a.vb"><![CDATA[
Interface I1
End Interface
Public Structure S1
Public Shared Widening Operator CType(ByVal x As S1) As I1
Return Nothing
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_AccessMismatchOutsideAssembly4, "I1").WithArguments("op_Implicit", "I1", "structure", "S1"),
Diagnostic(ERRID.ERR_ConversionToInterfaceType, "CType"))
End Sub
<Fact()>
Public Sub BC33026ERR_ConversionToBaseType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToBaseType">
<file name="a.vb"><![CDATA[
Class C1
End Class
Class S1
Inherits C1
Public Shared Widening Operator CType(ByVal x As S1) As C1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToBaseType, "CType"))
End Sub
<Fact()>
Public Sub BC33027ERR_ConversionToDerivedType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToDerivedType">
<file name="a.vb"><![CDATA[
Class C1
Inherits S1
End Class
Class S1
Public Shared Widening Operator CType(ByVal x As S1) As C1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToDerivedType, "CType"))
End Sub
<Fact()>
Public Sub BC33028ERR_ConversionToObject()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionToObject">
<file name="a.vb"><![CDATA[
Public Structure S1
Public Shared Widening Operator CType(ByVal x As S1) As Object
Return Nothing
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionToObject, "CType"))
End Sub
<Fact()>
Public Sub BC33029ERR_ConversionFromInterfaceType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromInterfaceType">
<file name="a.vb"><![CDATA[
Interface I1
End Interface
Class S1
Public Shared Widening Operator CType(ByVal x As I1) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromInterfaceType, "CType"))
End Sub
<Fact()>
Public Sub BC33030ERR_ConversionFromBaseType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromBaseType">
<file name="a.vb"><![CDATA[
Class C1
End Class
Class S1
Inherits C1
Public Shared Widening Operator CType(ByVal x As C1) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromBaseType, "CType"))
End Sub
<Fact()>
Public Sub BC33031ERR_ConversionFromDerivedType()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromDerivedType">
<file name="a.vb"><![CDATA[
Class C1
Inherits S1
End Class
Class S1
Public Shared Widening Operator CType(ByVal x As C1) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromDerivedType, "CType"))
End Sub
<Fact()>
Public Sub BC33032ERR_ConversionFromObject()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ConversionFromObject">
<file name="a.vb"><![CDATA[
Class S1
Public Shared Widening Operator CType(ByVal x As Object) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ConversionFromObject, "CType"))
End Sub
<Fact()>
Public Sub BC33033ERR_MatchingOperatorExpected2()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MatchingOperatorExpected2">
<file name="a.vb"><![CDATA[
Public Structure S1
Dim d As Date
Public Shared Operator IsFalse(ByVal z As S1) As Boolean
Dim b As Boolean
Return b
End Operator
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_MatchingOperatorExpected2, "IsFalse").WithArguments("IsTrue", "Public Shared Operator IsFalse(z As S1) As Boolean"))
End Sub
<Fact()>
Public Sub BC33041ERR_OperatorRequiresIntegerParameter1()
CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OperatorRequiresIntegerParameter1">
<file name="a.vb"><![CDATA[
Class S1
Public Shared Operator >>(ByVal x As S1, ByVal y As String) As S1
Return Nothing
End Operator
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_OperatorRequiresIntegerParameter1, ">>").WithArguments(">>"))
End Sub
<Fact()>
Public Sub BC33101ERR_BadTypeArgForStructConstraintNull()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation name="BadTypeArgForStructConstraintNull">
<file name="a.vb"><![CDATA[
Imports System
Interface I
End Interface
Structure S
End Structure
Class A
End Class
Class B(Of T)
Shared Sub M1(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As T)()
Dim o? As Object
Dim s? As S
Dim _1? As T1
Dim _2? As T2
Dim _3? As T3
Dim _4? As T4
Dim _5? As T5
Dim _6? As T6
Dim _7? As T7
End Sub
Shared Sub M2(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As T)()
Dim o As Nullable(Of Object) = New Nullable(Of Object)
Dim s As Nullable(Of S) = New Nullable(Of S)
Dim _1 As Nullable(Of T1) = New Nullable(Of T1)
Dim _2 As Nullable(Of T2) = New Nullable(Of T2)
Dim _3 As Nullable(Of T3) = New Nullable(Of T3)
Dim _4 As Nullable(Of T4) = New Nullable(Of T4)
Dim _5 As Nullable(Of T5) = New Nullable(Of T5)
Dim _6 As Nullable(Of T6) = New Nullable(Of T6)
Dim _7 As Nullable(Of T7) = New Nullable(Of T7)
End Sub
Shared Sub M3(Of T1, T2 As Class, T3 As Structure, T4 As New, T5 As I, T6 As A, T7 As T)()
Dim o As Object? = New Object?
Dim s As S? = New S?
Dim _1 As T1? = New T1?
Dim _2 As T2? = New T2?
Dim _3 As T3? = New T3?
Dim _4 As T4? = New T4?
Dim _5 As T5? = New T5?
Dim _6 As T6? = New T6?
Dim _7 As T7? = New T7?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC42024: Unused local variable: 'o'.
Dim o? As Object
~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o? As Object
~~
BC42024: Unused local variable: 's'.
Dim s? As S
~
BC42024: Unused local variable: '_1'.
Dim _1? As T1
~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1? As T1
~~~
BC42024: Unused local variable: '_2'.
Dim _2? As T2
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2? As T2
~~~
BC42024: Unused local variable: '_3'.
Dim _3? As T3
~~
BC42024: Unused local variable: '_4'.
Dim _4? As T4
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4? As T4
~~~
BC42024: Unused local variable: '_5'.
Dim _5? As T5
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5? As T5
~~~
BC42024: Unused local variable: '_6'.
Dim _6? As T6
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6? As T6
~~~
BC42024: Unused local variable: '_7'.
Dim _7? As T7
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7? As T7
~~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Nullable(Of Object) = New Nullable(Of Object)
~~~~~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Nullable(Of Object) = New Nullable(Of Object)
~~~~~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As Nullable(Of T1) = New Nullable(Of T1)
~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As Nullable(Of T1) = New Nullable(Of T1)
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As Nullable(Of T2) = New Nullable(Of T2)
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As Nullable(Of T2) = New Nullable(Of T2)
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As Nullable(Of T4) = New Nullable(Of T4)
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As Nullable(Of T4) = New Nullable(Of T4)
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As Nullable(Of T5) = New Nullable(Of T5)
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As Nullable(Of T5) = New Nullable(Of T5)
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As Nullable(Of T6) = New Nullable(Of T6)
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As Nullable(Of T6) = New Nullable(Of T6)
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As Nullable(Of T7) = New Nullable(Of T7)
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As Nullable(Of T7) = New Nullable(Of T7)
~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Object? = New Object?
~~~~~~
BC33101: Type 'Object' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim o As Object? = New Object?
~~~~~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As T1? = New T1?
~~
BC33101: Type 'T1' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _1 As T1? = New T1?
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As T2? = New T2?
~~
BC33101: Type 'T2' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _2 As T2? = New T2?
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As T4? = New T4?
~~
BC33101: Type 'T4' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _4 As T4? = New T4?
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As T5? = New T5?
~~
BC33101: Type 'T5' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _5 As T5? = New T5?
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As T6? = New T6?
~~
BC33101: Type 'T6' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _6 As T6? = New T6?
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As T7? = New T7?
~~
BC33101: Type 'T7' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim _7 As T7? = New T7?
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33102ERR_CantSpecifyArrayAndNullableOnBoth()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantSpecifyArrayAndNullableOnBoth">
<file name="a.vb"><![CDATA[
Class S1
Sub goo()
Dim numbers? As Integer()
Dim values() As Integer?
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC42024: Unused local variable: 'numbers'.
Dim numbers? As Integer()
~~~~~~~
BC33101: Type 'Integer()' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
Dim numbers? As Integer()
~~~~~~~~
BC42024: Unused local variable: 'values'.
Dim values() As Integer?
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC33109ERR_CantSpecifyAsNewAndNullable()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CantSpecifyAsNewAndNullable">
<file name="a.vb"><![CDATA[
Imports System
Class C
Shared Sub M()
Dim x? As New Guid()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC33109: Nullable modifier cannot be specified in variable declarations with 'As New'.
Dim x? As New Guid()
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC33112ERR_NullableImplicit()
Dim expectedErrors As New Dictionary(Of String, XElement) From {
{"On",
<expected><![CDATA[
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field1?()
~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field2?(,)
~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field3?()()
~~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Public field4?
~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local1?()
~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local2?(,)
~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local3?()()
~~~~~~~~~~~
BC33112: Nullable modifier cannot be used with a variable whose implicit type is 'Object'.
Dim local4?
~~~~~~~
]]></expected>},
{"Off",
<expected><![CDATA[
BC36629: Nullable type inference is not supported in this context.
Dim local5? = 23 ' this is ok for Option Infer On
~~~~~~~
]]></expected>}}
For Each infer In {"On", "Off"}
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NullableImplicit">
<file name="a.vb">
Option Infer <%= infer %>
Class C1
Public field1?()
Public field2?(,)
Public field3?()()
Public field4?
'Public field5? = 23 ' this is _NOT_ ok for Option Infer On, but it gives another diagnostic.
Public field6?(1) ' this is ok for Option Infer On
Public field7?(1)() ' this is ok for Option Infer On
Sub goo()
Dim local1?()
Dim local2?(,)
Dim local3?()()
Dim local4?
Dim local5? = 23 ' this is ok for Option Infer On
Dim local6?(1) ' this is ok for Option Infer On
Dim local7?(1)() ' this is ok for Option Infer On
local1 = nothing
local2 = nothing
local3 = nothing
local4 = nothing
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors(infer))
Next
End Sub
<Fact(), WorkItem(651624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651624")>
Public Sub NestedNullableWithAttemptedConversion()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb">
Imports System
Class C
Public Sub Main()
Dim x As Nullable(Of Nullable(Of Integer)) = Nothing
Dim y As Nullable(Of Integer) = Nothing
Console.WriteLine(x Is Nothing)
Console.WriteLine(y Is Nothing)
Console.WriteLine(x = y)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(comp,
<errors><![CDATA[
BC32115: 'System.Nullable' does not satisfy the 'Structure' constraint for type parameter 'T'. Only non-nullable 'Structure' types are allowed.
Dim x As Nullable(Of Nullable(Of Integer)) = Nothing
~~~~~~~~~~~~~~~~~~~~
BC30452: Operator '=' is not defined for types 'Integer??' and 'Integer?'.
Console.WriteLine(x = y)
~~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub BC36015ERR_PropertyNameConflictInMyCollection()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="PropertyNameConflictInMyCollection">
<file name="a.vb"><![CDATA[
Module module1
Public f As New GRBB
End Module
<Global.Microsoft.VisualBasic.MyGroupCollection("base", "create", "DisposeI", "Module1.f")> _
Public NotInheritable Class GRBB
Private Shared Function Create(Of T As {New, base})(ByVal Instance As T) As T
Return Nothing
End Function
Private Sub DisposeI(Of T As base)(ByRef Instance As T)
End Sub
Public m_derived As Short
End Class
Public Class base
Public i As Integer
End Class
Public Class disposei
Inherits base
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36015: 'Private Sub DisposeI(Of T As base)(ByRef Instance As T)' has the same name as a member used for type 'disposei' exposed in a 'My' group. Rename the type or its enclosing namespace.
<Global.Microsoft.VisualBasic.MyGroupCollection("base", "create", "DisposeI", "Module1.f")> _
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36551ERR_ExtensionMethodNotInModule()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ExtensionMethodNotInModule">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Imports System
Class C1
<Extension()> _
Public Sub Print(ByVal str As String)
End Sub
End Class
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36551: Extension methods can be defined only in modules.
<Extension()> _
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36552ERR_ExtensionMethodNoParams()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="ExtensionMethodNoParams">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Module C1
<Extension()> _
Public Sub Print()
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36552: Extension methods must declare at least one parameter. The first parameter specifies which type to extend.
Public Sub Print()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36553ERR_ExtensionMethodOptionalFirstArg()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="ExtensionMethodOptionalFirstArg">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Module C1
<Extension()> _
Public Sub Print(Optional ByVal str As String = "hello")
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36553: 'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.
Public Sub Print(Optional ByVal str As String = "hello")
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36554ERR_ExtensionMethodParamArrayFirstArg()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="ExtensionMethodParamArrayFirstArg">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Module C1
<Extension()> _
Public Sub Print(ByVal ParamArray str() As String)
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36554: 'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.
Public Sub Print(ByVal ParamArray str() As String)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36561ERR_ExtensionMethodUncallable1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
Interface I(Of T)
End Interface
Module M
<Extension()>
Sub M1(Of T, U As T)(o As T)
End Sub
<Extension()>
Sub M2(Of T As I(Of U), U)(o As T)
End Sub
<Extension()>
Sub M3(Of T, U As T)(o As U)
End Sub
<Extension()>
Sub M4(Of T As I(Of U), U)(o As U)
End Sub
End Module
]]></file>
</compilation>, {Net40.SystemCore})
Dim expectedErrors1 = <errors><![CDATA[
BC36561: Extension method 'M2' has type constraints that can never be satisfied.
Sub M2(Of T As I(Of U), U)(o As T)
~~
BC36561: Extension method 'M3' has type constraints that can never be satisfied.
Sub M3(Of T, U As T)(o As U)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36632ERR_NullableParameterMustSpecifyType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NullableParameterMustSpecifyType">
<file name="a.vb"><![CDATA[
Imports System
Public Module M
Delegate Sub Del(x?)
Sub Main()
Dim x As Action(Of Integer?) = Sub(y?) Console.WriteLine()
End Sub
Sub goo(x?)
End Sub
Sub goo2(Of T)(x?)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36632: Nullable parameters must specify a type.
Delegate Sub Del(x?)
~~
BC36632: Nullable parameters must specify a type.
Dim x As Action(Of Integer?) = Sub(y?) Console.WriteLine()
~~
BC36632: Nullable parameters must specify a type.
Sub goo(x?)
~~
BC36632: Nullable parameters must specify a type.
Sub goo2(Of T)(x?)
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36634ERR_LambdasCannotHaveAttributes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LambdasCannotHaveAttributes">
<file name="a.vb"><![CDATA[
Public Module M
Sub LambdaAttribute()
Dim add1 = _
Function(<System.Runtime.InteropServices.InAttribute()> m As Integer) _
m + 1
End Sub
End Module
]]></file>
</compilation>)
compilation1.VerifyDiagnostics(Diagnostic(ERRID.ERR_LambdasCannotHaveAttributes, "<System.Runtime.InteropServices.InAttribute()>"))
End Sub
<WorkItem(528712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528712")>
<Fact()>
Public Sub BC36643ERR_CantSpecifyParamsOnLambdaParamNoType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CantSpecifyParamsOnLambdaParamNoType">
<file name="a.vb"><![CDATA[
Imports System
Public Module M
Sub Main()
Dim x As Action(Of String()) = Sub(y()) Console.WriteLine()
End Sub
End Module
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_CantSpecifyParamsOnLambdaParamNoType, "y()"))
End Sub
<Fact()>
Public Sub BC36713ERR_AutoPropertyInitializedInStructure()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Structure S1(Of T As IEnumerable(Of T))
Property AP() As New T
End Structure
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_AutoPropertyInitializedInStructure, "AP"),
Diagnostic(ERRID.ERR_NewIfNullOnGenericParam, "T"))
End Sub
<WorkItem(542471, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542471")>
<Fact>
Public Sub BC36713ERR_AutoPropertyInitializedInStructure_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Structure S1
Public Property age1() As Integer = 10
Public Shared Property age2() As Integer = 10
End Structure
Module M1
Public Property age3() As Integer = 10
End Module
Class C1
Public Property age4() As Integer = 10
Public Shared Property age5() As Integer = 10
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36713: Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.
Public Property age1() As Integer = 10
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540702")>
<Fact>
Public Sub BC36759ERR_AutoPropertyCantHaveParams()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Imports System
Class A
Public Property Item(index As Integer) As String
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36759: Auto-implemented properties cannot have parameters.
Public Property Item(index As Integer) As String
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540702")>
<Fact>
Public Sub BC36759ERR_AutoPropertyCantHaveParams_MustOverride()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Imports System
Class A
Public MustOverride Property P(index As Integer) As T
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31411: 'A' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.
Class A
~
BC30002: Type 'T' is not defined.
Public MustOverride Property P(index As Integer) As T
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(540702, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540702")>
<Fact>
Public Sub BC36759ERR_AutoPropertyCantHaveParams_Default()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="AutoPropertyInitializedInStructure">
<file name="a.vb"><![CDATA[
Class C
Default Public Property P(a As Integer) As T
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30025: Property missing 'End Property'.
Default Public Property P(a As Integer) As T
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Default Public Property P(a As Integer) As T
~
BC30002: Type 'T' is not defined.
Default Public Property P(a As Integer) As T
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36722ERR_VarianceDisallowedHere()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceDisallowedHere">
<file name="a.vb"><![CDATA[
Class C1
Structure Z(Of T, In U, Out V)
End Structure
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure Z(Of T, In U, Out V)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Structure Z(Of T, In U, Out V)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36723ERR_VarianceInterfaceNesting()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInterfaceNesting">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Class C : End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36723: Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.
Class C : End Class
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36724ERR_VarianceOutParamDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub GOO(ByVal x As R(Of Tout))
End Interface
Interface R(Of Out T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36724: Type 'Tout' cannot be used in this context because 'Tout' is an 'Out' type parameter.
Sub GOO(ByVal x As R(Of Tout))
~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36725ERR_VarianceInParamDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As W(Of Tin))
End Interface
Interface W(Of In T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36725: Type 'Tin' cannot be used in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As W(Of Tin))
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36726ERR_VarianceOutParamDisallowedForGeneric3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowedForGeneric3">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of Tout, Tout))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36726: Type 'Tout' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because 'Tout' is an 'Out' type parameter.
Sub goo(ByVal x As RW(Of Tout, Tout))
~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36727ERR_VarianceInParamDisallowedForGeneric3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowedForGeneric3">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of Tin, Tin))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36727: Type 'Tin' cannot be used for the 'T2' in 'RW(Of T1, T2)' in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As RW(Of Tin, Tin))
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36728ERR_VarianceOutParamDisallowedHere2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowedHere2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As R(Of R(Of Tout)))
End Interface
Interface R(Of Out T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36728: Type 'Tout' cannot be used in 'R(Of Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub goo(ByVal x As R(Of R(Of Tout)))
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36729ERR_VarianceInParamDisallowedHere2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowedHere2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As W(Of R(Of Tin)))
End Interface
Interface R(Of Out T) : End Interface
Interface W(Of In T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36729: Type 'Tin' cannot be used in 'R(Of Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As W(Of R(Of Tin)))
~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36730ERR_VarianceOutParamDisallowedHereForGeneric4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutParamDisallowedHereForGeneric4">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin)))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36730: Type 'Tout' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of Tout, Tout)' in this context because 'Tout' is an 'Out' type parameter.
Sub goo(ByVal x As RW(Of RW(Of Tout, Tout), RW(Of Tout, Tin)))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36731ERR_VarianceInParamDisallowedHereForGeneric4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInParamDisallowedHereForGeneric4">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin)))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36731: Type 'Tin' cannot be used for the 'T2' of 'RW(Of T1, T2)' in 'RW(Of Tin, Tin)' in this context because 'Tin' is an 'In' type parameter.
Sub goo(ByVal x As RW(Of RW(Of Tin, Tin), RW(Of Tout, Tin)))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36732ERR_VarianceTypeDisallowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowed2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As J)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36732: Type 'J' cannot be used in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As J)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36733ERR_VarianceTypeDisallowedForGeneric4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowedForGeneric4">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As RW(Of J, Tout))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36733: Type 'J' cannot be used for the 'T1' in 'RW(Of T1, T2)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As RW(Of J, Tout))
~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36735ERR_VarianceTypeDisallowedHere3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowedHere3">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As R(Of R(Of J)))
End Interface
Interface R(Of Out T) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36735: Type 'J' cannot be used in 'R(Of I(Of Tout, Tin, TSout, TSin).J)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As R(Of R(Of J)))
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36736ERR_VarianceTypeDisallowedHereForGeneric5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceTypeDisallowedHereForGeneric5">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Interface J : End Interface
Sub goo(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin)))
End Interface
Interface RW(Of Out T1, In T2) : End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36736: Type 'J' cannot be used for the 'T1' of 'RW(Of T1, T2)' in 'RW(Of I(Of Tout, Tin, TSout, TSin).J, Tout)' in this context because both the context and the definition of 'J' are nested within interface 'I(Of Tout, Tin, TSout, TSin)', and 'I(Of Tout, Tin, TSout, TSin)' has 'In' or 'Out' type parameters. Consider moving the definition of 'J' outside of 'I(Of Tout, Tin, TSout, TSin)'.
Sub goo(ByVal x As RW(Of RW(Of J, Tout), RW(Of Tout, Tin)))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36738ERR_VariancePreventsSynthesizedEvents2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VariancePreventsSynthesizedEvents2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Event e()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36738: Event definitions with parameters are not allowed in an interface such as 'I(Of Tout, Tin, TSout, TSin)' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within 'I(Of Tout, Tin, TSout, TSin)'. For example, 'Event e As Action(Of ...)'.
Event e()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36740ERR_VarianceOutNullableDisallowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutNullableDisallowed2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Function goo() As TSout?
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36740: Type 'TSout' cannot be used in 'TSout?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSout' is an 'Out' type parameter.
Function goo() As TSout?
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36741ERR_VarianceInNullableDisallowed2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInNullableDisallowed2">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub goo(ByVal x As TSin?)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36741: Type 'TSin' cannot be used in 'TSin?' because 'In' and 'Out' type parameters cannot be made nullable, and 'TSin' is an 'In' type parameter.
Sub goo(ByVal x As TSin?)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36742ERR_VarianceOutByValDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutByValDisallowed1">
<file name="a.vb"><![CDATA[
Interface IVariance(Of Out T)
Sub Goo(ByVal a As T)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36742: Type 'T' cannot be used as a ByVal parameter type because 'T' is an 'Out' type parameter.
Sub Goo(ByVal a As T)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36743ERR_VarianceInReturnDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInReturnDisallowed1">
<file name="a.vb"><![CDATA[
Interface IVariance(Of In T)
Function Goo() As T
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36743: Type 'T' cannot be used as a return type because 'T' is an 'In' type parameter.
Function Goo() As T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36744ERR_VarianceOutConstraintDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutConstraintDisallowed1">
<file name="a.vb"><![CDATA[
Interface IVariance(Of Out T)
Function Goo(Of U As T)() As T
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36744: Type 'T' cannot be used as a generic type constraint because 'T' is an 'Out' type parameter.
Function Goo(Of U As T)() As T
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36745ERR_VarianceInReadOnlyPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInReadOnlyPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
ReadOnly Property p() As Tin
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36745: Type 'Tin' cannot be used as a ReadOnly property type because 'Tin' is an 'In' type parameter.
ReadOnly Property p() As Tin
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36746ERR_VarianceOutWriteOnlyPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutWriteOnlyPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
WriteOnly Property p() As Tout
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36746: Type 'Tout' cannot be used as a WriteOnly property type because 'Tout' is an 'Out' type parameter.
WriteOnly Property p() As Tout
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36747ERR_VarianceOutPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Property p() As Tout
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36747: Type 'Tout' cannot be used as a property type in this context because 'Tout' is an 'Out' type parameter and the property is not marked ReadOnly.
Property p() As Tout
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36748ERR_VarianceInPropertyDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInPropertyDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Property p() As Tin
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36748: Type 'Tin' cannot be used as a property type in this context because 'Tin' is an 'In' type parameter and the property is not marked WriteOnly.
Property p() As Tin
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36749ERR_VarianceOutByRefDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceOutByRefDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub f(ByRef x As Tout)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36749: Type 'Tout' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tout' is an 'Out' type parameter.
Sub f(ByRef x As Tout)
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC36750ERR_VarianceInByRefDisallowed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="VarianceInByRefDisallowed1">
<file name="a.vb"><![CDATA[
Interface I(Of Out Tout, In Tin, Out TSout As Structure, In TSin As Structure)
Sub f(ByRef x As Tin)
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36750: Type 'Tin' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and 'Tin' is an 'In' type parameter.
Sub f(ByRef x As Tin)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC36917ERR_OverloadsModifierInModule()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OverloadsModifierInModule">
<file name="a.vb"><![CDATA[
Module M1
Overloads Function goo(x as integer) as double
return nothing
End Function
Overloads Function goo(ByVal x As Long) As Double
Return Nothing
End Function
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Function goo(x as integer) as double
~~~~~~~~~
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Function goo(ByVal x As Long) As Double
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' Old name"MethodErrorsOverloadsInModule"
<Fact>
Public Sub BC36917ERR_OverloadsModifierInModule_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Overloads Sub S()
End Sub
Overloads Property P
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Sub S()
~~~~~~~~~
BC36917: Inappropriate use of 'Overloads' keyword in a module.
Overloads Property P
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
#End Region
#Region "Targeted Warning Tests"
<Fact>
Public Sub BC40000WRN_UseOfObsoleteSymbol2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UseOfObsoleteSymbol2">
<file name="a.vb"><![CDATA[
Imports System.Net
Module Module1
Sub Main()
Dim RemoteEndPoint As EndPoint = Nothing
Dim x As Long
x = CType(CType(RemoteEndPoint, IPEndPoint).Address.Address Mod 256, Byte)
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40000: 'Public Overloads Property Address As Long' is obsolete: 'This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202'.
x = CType(CType(RemoteEndPoint, IPEndPoint).Address.Address Mod 256, Byte)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40003WRN_MustOverloadBase4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustOverloadBase4">
<file name="a.vb"><![CDATA[
Interface I
Sub S()
End Interface
Class C1
Implements I
Public Sub S() Implements I.S
End Sub
End Class
Class C2
Inherits C1
Public Sub S()
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: sub 'S' shadows an overloadable member declared in the base class 'C1'. If you want to overload the base method, this method must be declared 'Overloads'.
Public Sub S()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40004WRN_OverrideType5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="OverrideType5">
<file name="a.vb"><![CDATA[
Public Class Base
Public i As Integer = 10
End Class
Public Class C1
Inherits Base
Public i As String = "hi"
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40004: variable 'i' conflicts with variable 'i' in the base class 'Base' and should be declared 'Shadows'.
Public i As String = "hi"
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40005WRN_MustOverride2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustOverride2">
<file name="a.vb"><![CDATA[
Class C1
Overridable ReadOnly Property Goo(ByVal x As Integer) As Integer
Get
Return 1
End Get
End Property
End Class
Class C2
Inherits C1
ReadOnly Property Goo(ByVal x As Integer) As Integer
Get
Return 1
End Get
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40005: property 'Goo' shadows an overridable method in the base class 'C1'. To override the base method, this method must be declared 'Overrides'.
ReadOnly Property Goo(ByVal x As Integer) As Integer
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(543734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543734")>
<WorkItem(561748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/561748")>
<Fact>
Public Sub BC40007WRN_DefaultnessShadowed4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Namespace N1
Class base
Default Public ReadOnly Property Item(ByVal i As Integer) As Integer
Get
Return i
End Get
End Property
End Class
Class base2
Inherits base
End Class
Class derive
Inherits base
Default Public Overloads ReadOnly Property Item1(ByVal i As Integer) As Integer
Get
Return 2 * i
End Get
End Property
End Class
Class derive2
Inherits base2
Default Public Overloads ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
Get
Return 2 * i
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40007: Default property 'Item1' conflicts with the default property 'Item' in the base class 'base'. 'Item1' will be the default property. 'Item1' should be declared 'Shadows'.
Default Public Overloads ReadOnly Property Item1(ByVal i As Integer) As Integer
~~~~~
BC40007: Default property 'Item3' conflicts with the default property 'Item' in the base class 'base'. 'Item3' will be the default property. 'Item3' should be declared 'Shadows'.
Default Public Overloads ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(546773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546773")>
Public Sub BC40007WRN_DefaultnessShadowed4_NoErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Base
Default Public ReadOnly Property TeamName(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
Class Derived
Inherits Base
Default Public Shadows ReadOnly Property TeamProject(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, <errors><![CDATA[]]></errors>)
End Sub
<Fact, WorkItem(546773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546773")>
Public Sub BC40007WRN_DefaultnessShadowed4_TwoErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Base
Default Public ReadOnly Property TeamName(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
Class Derived
Inherits Base
Default Public ReadOnly Property TeamProject(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
Default Public ReadOnly Property TeamProject(ByVal index As String) As String
Get
Return ""
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40007: Default property 'TeamProject' conflicts with the default property 'TeamName' in the base class 'Base'. 'TeamProject' will be the default property. 'TeamProject' should be declared 'Shadows'.
Default Public ReadOnly Property TeamProject(ByVal index As Integer) As String
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(546773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546773")>
Public Sub BC40007WRN_DefaultnessShadowed4_MixedErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Base
Default Public ReadOnly Property TeamName(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
End Class
Class Derived
Inherits Base
Default Public Shadows ReadOnly Property TeamProject(ByVal index As Integer) As String
Get
Return ""
End Get
End Property
Default Public ReadOnly Property TeamProject(ByVal index As String) As String
Get
Return ""
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC30695: property 'TeamProject' must be declared 'Shadows' because another member with this name is declared 'Shadows'.
Default Public ReadOnly Property TeamProject(ByVal index As String) As String
~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(543734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543734")>
<Fact>
Public Sub BC40007WRN_DefaultnessShadowed4_DifferentCasing()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Namespace N1
Class base
Default Public ReadOnly Property Item(ByVal i As Integer) As Integer
Get
Return i
End Get
End Property
End Class
Class derive
Inherits base
Default Public Overloads ReadOnly Property item(ByVal i As Integer, j as Integer) As Integer
Get
Return 2 * i
End Get
End Property
End Class
End Namespace
]]></file>
</compilation>)
' Differs only by case, shouldn't have errors.
Dim expectedErrors1 = <errors><![CDATA[
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(543734, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543734")>
<WorkItem(561748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/561748")>
<Fact>
Public Sub BC40007WRN_DefaultnessShadowed4_Interface()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Interface base1
End Interface
Interface base2
Default ReadOnly Property Item2(ByVal i As Integer) As Integer
End Interface
Interface base3
Inherits base2
End Interface
Interface derive1
Inherits base1, base2
Default ReadOnly Property Item1(ByVal i As Integer) As Integer
End Interface
Interface derive2
Inherits base3
Default ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40007: Default property 'Item1' conflicts with the default property 'Item2' in the base interface 'base2'. 'Item1' will be the default property. 'Item1' should be declared 'Shadows'.
Default ReadOnly Property Item1(ByVal i As Integer) As Integer
~~~~~
BC40007: Default property 'Item3' conflicts with the default property 'Item2' in the base interface 'base2'. 'Item3' will be the default property. 'Item3' should be declared 'Shadows'.
Default ReadOnly Property Item3(ByVal i As Integer) As Integer ' No warning in Dev11
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC40011WRN_ComClassNoMembers1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ComClassNoMembers1">
<file name="a.vb"><![CDATA[
<Microsoft.VisualBasic.ComClassAttribute()>
Public Class C1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'C1' but 'C1' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.
Public Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40012WRN_SynthMemberShadowsMember5_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
Public Sub get_P()
End Sub
Public Sub set_P()
End Sub
Public Function get_Q()
Return Nothing
End Function
Public Sub set_Q()
End Sub
Public Function get_R(value)
Return Nothing
End Function
Public Sub set_R(value)
End Sub
Public Function get_S()
Return Nothing
End Function
Public Function set_S()
Return Nothing
End Function
Public get_T
Public Interface set_T
End Interface
Public Enum get_U
A
End Enum
Public Structure set_U
End Structure
End Class
MustInherit Class B
Inherits A
Public Property P
Public ReadOnly Property Q
Get
Return Nothing
End Get
End Property
Friend WriteOnly Property R
Set(value)
End Set
End Property
Protected MustOverride Property S
Public Property T
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Public Property U
End Class
MustInherit Class C
Inherits A
Public Shadows Property P
Public Shadows ReadOnly Property Q
Get
Return Nothing
End Get
End Property
Friend Shadows WriteOnly Property R
Set(value)
End Set
End Property
Protected MustOverride Shadows Property S
Public Shadows Property T
Get
Return Nothing
End Get
Set(value)
End Set
End Property
Public Shadows Property U
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40012: property 'P' implicitly declares 'get_P', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property P
~
BC40012: property 'P' implicitly declares 'set_P', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property P
~
BC40012: property 'Q' implicitly declares 'get_Q', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public ReadOnly Property Q
~
BC40012: property 'R' implicitly declares 'set_R', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Friend WriteOnly Property R
~
BC40012: property 'S' implicitly declares 'get_S', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Protected MustOverride Property S
~
BC40012: property 'S' implicitly declares 'set_S', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Protected MustOverride Property S
~
BC40012: property 'T' implicitly declares 'get_T', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property T
~
BC40012: property 'T' implicitly declares 'set_T', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property T
~
BC40012: property 'U' implicitly declares 'get_U', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property U
~
BC40012: property 'U' implicitly declares 'set_U', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property U
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(541355, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541355")>
<Fact>
Public Sub BC40012WRN_SynthMemberShadowsMember5_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
Private _P1
Protected _P2
Friend _P3
Public Sub _Q1()
End Sub
Public Interface _Q2
End Interface
Public Enum _Q3
A
End Enum
Public _R1
Public _R2
Public _R3
Public _R4
End Class
MustInherit Class B
Inherits A
Friend Property P1
Protected Property P2
Private Property P3
Public Property Q1
Public Property Q2
Public Property Q3
Public ReadOnly Property R1
Get
Return Nothing
End Get
End Property
Public WriteOnly Property R2
Set(value)
End Set
End Property
Public MustOverride Property R3
Public Property R4
End Class
MustInherit Class C
Inherits A
Friend Shadows Property P1
Protected Shadows Property P2
Private Shadows Property P3
Public Shadows Property Q1
Public Shadows Property Q2
Public Shadows Property Q3
Public Shadows ReadOnly Property R1
Get
Return Nothing
End Get
End Property
Public Shadows WriteOnly Property R2
Set(value)
End Set
End Property
Public MustOverride Shadows Property R3
Public Shadows Property R4
End Class
MustInherit Class D
Friend Property P1
Protected Property P2
Private Property P3
Public Property Q1
Public Property Q2
Public Property Q3
Public ReadOnly Property R1
Get
Return Nothing
End Get
End Property
Public WriteOnly Property R2
Set(value)
End Set
End Property
Public MustOverride Property R3
End Class
MustInherit Class E
Inherits D
Private _P1
Protected _P2
Friend _P3
Public Sub _Q1()
End Sub
Public Interface _Q2
End Interface
Public Enum _Q3
A
End Enum
Public _R1
Public _R2
Public _R3
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40012: property 'P2' implicitly declares '_P2', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Protected Property P2
~~
BC40012: property 'P3' implicitly declares '_P3', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Private Property P3
~~
BC40012: property 'Q1' implicitly declares '_Q1', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property Q1
~~
BC40012: property 'Q2' implicitly declares '_Q2', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property Q2
~~
BC40012: property 'Q3' implicitly declares '_Q3', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property Q3
~~
BC40012: property 'R4' implicitly declares '_R4', which conflicts with a member in the base class 'A', and so the property should be declared 'Shadows'.
Public Property R4
~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539827")>
<Fact>
Public Sub BC40012WRN_SynthMemberShadowsMember5_3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IA
Function get_Goo() As String
End Interface
Interface IB
Inherits IA
ReadOnly Property Goo() As Integer
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 =
<errors><![CDATA[
BC40012: property 'Goo' implicitly declares 'get_Goo', which conflicts with a member in the base interface 'IA', and so the property should be declared 'Shadows'.
ReadOnly Property Goo() As Integer
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC40012WRN_SynthMemberShadowsMember5_4()
CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public add_E
Public remove_E
Public EEvent
Public EEventHandler
End Class
Class B
Inherits A
Public Event E()
End Class
Class C
Inherits A
Public Shadows Event E()
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "EEventHandler", "class", "A"),
Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "EEvent", "class", "A"),
Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "add_E", "class", "A"),
Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "E").WithArguments("event", "E", "remove_E", "class", "A"))
End Sub
<Fact>
Public Sub BC40014WRN_MemberShadowsSynthMember6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
MustInherit Class A
Public Property P
Public ReadOnly Property Q
Get
Return Nothing
End Get
End Property
Friend WriteOnly Property R
Set(value)
End Set
End Property
Protected MustOverride Property S
End Class
MustInherit Class B
Inherits A
Public Sub get_P()
End Sub
Public Sub set_P()
End Sub
Public Function get_Q()
Return Nothing
End Function
Public Sub set_Q()
End Sub
Public Function get_R(value)
Return Nothing
End Function
Public Sub set_R(value)
End Sub
Public Function get_S()
Return Nothing
End Function
Public Function set_S()
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40014: sub 'get_P' conflicts with a member implicitly declared for property 'P' in the base class 'A' and should be declared 'Shadows'.
Public Sub get_P()
~~~~~
BC40014: sub 'set_P' conflicts with a member implicitly declared for property 'P' in the base class 'A' and should be declared 'Shadows'.
Public Sub set_P()
~~~~~
BC40014: function 'get_Q' conflicts with a member implicitly declared for property 'Q' in the base class 'A' and should be declared 'Shadows'.
Public Function get_Q()
~~~~~
BC40014: sub 'set_R' conflicts with a member implicitly declared for property 'R' in the base class 'A' and should be declared 'Shadows'.
Public Sub set_R(value)
~~~~~
BC40014: function 'get_S' conflicts with a member implicitly declared for property 'S' in the base class 'A' and should be declared 'Shadows'.
Public Function get_S()
~~~~~
BC40014: function 'set_S' conflicts with a member implicitly declared for property 'S' in the base class 'A' and should be declared 'Shadows'.
Public Function set_S()
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40019WRN_UseOfObsoletePropertyAccessor3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UseOfObsoletePropertyAccessor3">
<file name="a.vb"><![CDATA[
Imports System
Class C1
ReadOnly Property p As String
<Obsolete("hello", False)>
Get
Return "hello"
End Get
End Property
End Class
Class C2
Sub goo()
Dim s As C1 = New C1()
Dim a = s.p
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40019: 'Get' accessor of 'Public ReadOnly Property p As String' is obsolete: 'hello'.
Dim a = s.p
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40025WRN_FieldNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="FieldNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(True)> Public Class GenCompClass(Of T)
<CLSCompliant(False)> Public Structure NonCompStruct
Public a As UInteger
End Structure
<CLSCompliant(False)> Class cls1
End Class
End Class
Public Class C(Of t)
Inherits GenCompClass(Of String)
Public x As GenCompClass(Of String).cls1
Public y As GenCompClass(Of String).NonCompStruct
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40025: Type of member 'x' is not CLS-compliant.
Public x As GenCompClass(Of String).cls1
~
BC40025: Type of member 'y' is not CLS-compliant.
Public y As GenCompClass(Of String).NonCompStruct
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40026WRN_BaseClassNotCLSCompliant2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BaseClassNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class MyCompliantClass
Inherits BASE
End Class
Public Class BASE
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40026: 'MyCompliantClass' is not CLS-compliant because it derives from 'BASE', which is not CLS-compliant.
Public Class MyCompliantClass
~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40027WRN_ProcTypeNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ProcTypeNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class MyCompliantClass
Public Function ChangeValue() As UInt32
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40027: Return type of function 'ChangeValue' is not CLS-compliant.
Public Function ChangeValue() As UInt32
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40028WRN_ParamNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ParamNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class MyCompliantClass
Public Sub ChangeValue(ByVal value As UInt32)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40028: Type of parameter 'value' is not CLS-compliant.
Public Sub ChangeValue(ByVal value As UInt32)
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40029WRN_InheritedInterfaceNotCLSCompliant2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="InheritedInterfaceNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<assembly: clscompliant(true)>
<CLSCompliant(False)> Public Interface i1
End Interface
Public Interface i2
Inherits i1
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40029: 'i2' is not CLS-compliant because the interface 'i1' it inherits from is not CLS-compliant.
Public Interface i2
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40030WRN_CLSMemberInNonCLSType3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CLSMemberInNonCLSType3">
<file name="a.vb"><![CDATA[
Imports System
Public Module M1
<CLSCompliant(True)> Class C1
End Class
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40030: class 'M1.C1' cannot be marked CLS-compliant because its containing type 'M1' is not CLS-compliant.
<CLSCompliant(True)> Class C1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40031WRN_NameNotCLSCompliant1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NameNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Namespace _NS
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40031: Name '_NS' is not CLS-compliant.
Namespace _NS
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40032WRN_EnumUnderlyingTypeNotCLS1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EnumUnderlyingTypeNotCLS1">
<file name="a.vb"><![CDATA[
<Assembly: System.CLSCompliant(True)>
Public Class c1
Public Enum COLORS As UInteger
RED
GREEN
BLUE
End Enum
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40032: Underlying type 'UInteger' of Enum is not CLS-compliant.
Public Enum COLORS As UInteger
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40033WRN_NonCLSMemberInCLSInterface1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NonCLSMemberInCLSInterface1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)> Public Interface IFace
<CLSCompliant(False)> Property Prop1() As Long
<CLSCompliant(False)> Function F2() As Integer
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
<CLSCompliant(False)> Sub Sub4()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40033: Non CLS-compliant 'Property Prop1 As Long' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Property Prop1() As Long
~~~~~
BC40033: Non CLS-compliant 'Function F2() As Integer' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Function F2() As Integer
~~
BC40033: Non CLS-compliant 'Event EV3(i3 As Integer)' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
~~~
BC40033: Non CLS-compliant 'Sub Sub4()' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Sub Sub4()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40034WRN_NonCLSMustOverrideInCLSType1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NonCLSMustOverrideInCLSType1">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)> Public MustInherit Class QuiteCompliant
<CLSCompliant(False)> Public MustOverride Sub Sub1()
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
<CLSCompliant(False)> Friend MustOverride Function Fun4(ByVal x As Long) As Long
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Public MustOverride Sub Sub1()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40035WRN_ArrayOverloadsNonCLS2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ArrayOverloadsNonCLS2">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public MustInherit Class QuiteCompliant
Public Sub goo(Of t)(ByVal p1()()() As Integer)
End Sub
Public Sub goo(Of t)(ByVal p1()()()()() As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40035: 'Public Sub goo(Of t)(p1 As Integer()()()()())' is not CLS-compliant because it overloads 'Public Sub goo(Of t)(p1 As Integer()()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub goo(Of t)(ByVal p1()()()()() As Integer)
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40038WRN_RootNamespaceNotCLSCompliant1()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("_CLS")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RootNamespaceNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Module M1
End Module
]]></file>
</compilation>, opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40038: Root namespace '_CLS' is not CLS-compliant.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40039WRN_RootNamespaceNotCLSCompliant2()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("A._B")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RootNamespaceNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Module M1
End Module
]]></file>
</compilation>, opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40039: Name '_B' in the root namespace 'A._B' is not CLS-compliant.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40041WRN_TypeNotCLSCompliant1()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="TypeNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(True)> Public Class GenCompClass(Of T)
End Class
Public Class C(Of t)
Inherits GenCompClass(Of UInteger)
End Class
]]></file>
</compilation>, options:=opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Class C(Of t)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40042WRN_OptionalValueNotCLSCompliant1()
Dim opt = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="OptionalValueNotCLSCompliant1">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Module M1
Public Sub goo(Of t)(Optional ByVal p1 As Object = 3UI)
End Sub
End Module
]]></file>
</compilation>, opt)
Dim expectedErrors1 = <errors><![CDATA[
BC40042: Type of optional value for optional parameter 'p1' is not CLS-compliant.
Public Sub goo(Of t)(Optional ByVal p1 As Object = 3UI)
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40043WRN_CLSAttrInvalidOnGetSet()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CLSAttrInvalidOnGetSet">
<file name="a.vb"><![CDATA[
Imports System
Class C1
Property PROP As String
<CLSCompliant(True)>
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40046WRN_TypeConflictButMerged6()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Interface ii
End Interface
Structure teststruct
Implements ii
End Structure
Partial Structure teststruct
End Structure
Structure teststruct
Dim a As String
End Structure
Partial Interface ii
End Interface
Interface ii ' 3
End Interface
Module m
End Module
Partial Module m
End Module
Module m ' 3
End Module
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40046: interface 'ii' and partial interface 'ii' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Interface ii
~~
BC40046: structure 'teststruct' and partial structure 'teststruct' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Structure teststruct
~~~~~~~~~~
BC40046: structure 'teststruct' and partial structure 'teststruct' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Structure teststruct
~~~~~~~~~~
BC40046: interface 'ii' and partial interface 'ii' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Interface ii ' 3
~~
BC40046: module 'm' and partial module 'm' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Module m
~
BC40046: module 'm' and partial module 'm' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Module m ' 3
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40046WRN_TypeConflictButMerged6_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace N
Partial Class C
Private F
End Class
Class C ' Warning 1
Private G
End Class
Class C ' Warning 2
Private H
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40046: class 'C' and partial class 'C' conflict in namespace 'N', but are being merged because one of them is declared partial.
Class C ' Warning 1
~
BC40046: class 'C' and partial class 'C' conflict in namespace 'N', but are being merged because one of them is declared partial.
Class C ' Warning 2
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40048WRN_ShadowingGenericParamWithParam1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingGenericParamWithParam1">
<file name="a.vb"><![CDATA[
Interface I1(Of V)
Class C1(Of V)
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40048: Type parameter 'V' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Class C1(Of V)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact(), WorkItem(543528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543528")>
Public Sub BC40048WRN_ShadowingGenericParamWithParam1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ShadowingGenericParamWithParam1">
<file name="a.vb"><![CDATA[
Class base(Of T)
Function TEST(Of T)(ByRef X As T)
Return Nothing
End Function
End Class
]]></file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.WRN_ShadowingGenericParamWithParam1, "T").WithArguments("T"))
End Sub
<Fact>
Public Sub BC40050WRN_EventDelegateTypeNotCLSCompliant2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EventDelegateTypeNotCLSCompliant2">
<file name="a.vb"><![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class ETester
<CLSCompliant(False)> Public Delegate Sub abc(ByVal n As Integer)
Public Custom Event E As abc
AddHandler(ByVal Value As abc)
End AddHandler
RemoveHandler(ByVal Value As abc)
End RemoveHandler
RaiseEvent(ByVal n As Integer)
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40050: Delegate type 'ETester.abc' of event 'E' is not CLS-compliant.
Public Custom Event E As abc
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40053WRN_CLSEventMethodInNonCLSType3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="CLSEventMethodInNonCLSType3">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(False)> _
Public Class cls1
Delegate Sub del1()
Custom Event e1 As del1
AddHandler(ByVal value As del1)
End AddHandler
<CLSCompliant(True)> _
RemoveHandler(ByVal value As del1)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40053: 'RemoveHandler' method for event 'e1' cannot be marked CLS compliant because its containing type 'cls1' is not CLS compliant.
<CLSCompliant(True)> _
~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539496")>
<Fact>
Public Sub BC40055WRN_NamespaceCaseMismatch3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NamespaceCaseMismatch3">
<file name="a.vb"><![CDATA[
Namespace ns1
End Namespace
Namespace Ns1
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'Ns1' in 'a.vb'.
Namespace ns1
~~~
]]></errors>)
compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NamespaceCaseMismatch3">
<file name="a.vb"><![CDATA[
Namespace ns1
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Namespace Ns1
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40055: Casing of namespace name 'ns1' does not match casing of namespace name 'Ns1' in 'b.vb'.
Namespace ns1
~~~
]]></errors>)
compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="NamespaceCaseMismatch3">
<file name="a.vb"><![CDATA[
Namespace Ns
End Namespace
Namespace ns.AB
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Namespace NS.Ab
End Namespace
Namespace Ns
Namespace Ab
End Namespace
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1,
<errors><![CDATA[
BC40055: Casing of namespace name 'Ns' does not match casing of namespace name 'NS' in 'b.vb'.
Namespace Ns
~~
BC40055: Casing of namespace name 'Ab' does not match casing of namespace name 'AB' in 'a.vb'.
Namespace NS.Ab
~~
]]></errors>)
End Sub
<WorkItem(545727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545727")>
<Fact()>
Public Sub BC40055_WRN_NamespaceCaseMismatch3_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="ConsoleApplicationVB"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'CONSOLEAPPLICATIONVB' does not match casing of namespace name 'ConsoleApplicationVB' in '<project settings>'.
Namespace CONSOLEAPPLICATIONVB
~~~~~~~~~~~~~~~~~~~~
]]></expected>)
' different casing to see that best name has no influence on error
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace consoleapplicationvb
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="CONSOLEAPPLICATIONVB"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'consoleapplicationvb' does not match casing of namespace name 'CONSOLEAPPLICATIONVB' in '<project settings>'.
Namespace consoleapplicationvb
~~~~~~~~~~~~~~~~~~~~
]]></expected>)
' passing nested ns to rootnamespace
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace GOO
Namespace BAR
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="GOO.bar"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'BAR' does not match casing of namespace name 'bar' in '<project settings>'.
Namespace BAR
~~~
]]></expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace GOO
Namespace bar
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="GOO.BAR"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'bar' does not match casing of namespace name 'BAR' in '<project settings>'.
Namespace bar
~~~
]]></expected>)
' passing nested ns to rootnamespace
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace goo
Namespace BAR
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="GOO.BAR"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'goo' does not match casing of namespace name 'GOO' in '<project settings>'.
Namespace goo
~~~
]]></expected>)
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace GOO
Namespace BAR
Class H
End Class
End Namespace
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="goo.BAR"))
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC40055: Casing of namespace name 'GOO' does not match casing of namespace name 'goo' in '<project settings>'.
Namespace GOO
~~~
]]></expected>)
' no warnings if spelling is correct
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace:="CONSOLEAPPLICATIONVB"))
compilation.AssertNoErrors()
' no warnings if no root namespace is given
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace Global
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>)
compilation.AssertNoErrors()
' no warnings for global namespace itself
compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Namespace GLObAl
Namespace CONSOLEAPPLICATIONVB
Class H
End Class
End Namespace
End Namespace
]]></file>
</compilation>)
compilation.AssertNoErrors()
End Sub
<WorkItem(528713, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528713")>
<Fact>
Public Sub BC40056WRN_UndefinedOrEmptyNamespaceOrClass1()
Dim options = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithRootNamespace("BC40056WRN_UndefinedOrEmptyNamespaceOrClass1")
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedOrEmptyNamespaceOrClass1">
<file name="a.vb"><![CDATA[
Imports alias1 = ns1.GenStruct(Of String)
Structure GenStruct(Of T)
End Structure
]]></file>
</compilation>,
options:=options
)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'ns1.GenStruct' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports alias1 = ns1.GenStruct(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40056WRN_UndefinedOrEmptyNamespaceOrClass1_1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UndefinedOrEmptyNamespaceOrClass1">
<file name="a.vb"><![CDATA[
Imports ns1.GOO
Namespace ns1
Module M1
Sub GOO()
End Sub
End Module
End Namespace
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'ns1.GOO' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports ns1.GOO
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40056WRN_UndefinedOrEmptyNamespaceOrClass1_2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedOrEmptyNamespaceOrClass1">
<file name="a.vb"><![CDATA[
Imports Alias2 = System
Imports N12 = Alias2
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'Alias2' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports N12 = Alias2
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC40057WRN_UndefinedOrEmptyProjectNamespaceOrClass1()
Dim globalImports = GlobalImport.Parse({"Alias2 = System", "N12 = Alias2"})
Dim options = TestOptions.ReleaseExe.WithGlobalImports(globalImports)
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="UndefinedOrEmpyProjectNamespaceOrClass1">
<file name="a.vb"><![CDATA[
]]></file>
</compilation>, options:=options)
Dim expectedErrors1 = <errors><![CDATA[
BC40057: Namespace or type specified in the project-level Imports 'N12 = Alias2' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(545385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545385")>
<Fact>
Public Sub BC41005WRN_MissingAsClauseinOperator()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Class D
Shared Operator +(ByVal x As D) ' BC41005 -> BC42021. "Operator without an 'As' clause; type of Object assumed."
Return Nothing
End Operator
End Class
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict:=OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42021: Operator without an 'As' clause; type of Object assumed.
Shared Operator +(ByVal x As D) ' BC41005 -> BC42021. "Operator without an 'As' clause; type of Object assumed."
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(528714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528714"), WorkItem(1070286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070286")>
<Fact()>
Public Sub BC42000WRN_MustShadowOnMultipleInheritance2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MustShadowOnMultipleInheritance2">
<file name="a.vb"><![CDATA[
Interface I1
Sub goo(ByVal arg As Integer)
End Interface
Interface I2
Sub goo(ByVal arg As Integer)
End Interface
Interface I3
Inherits I1, I2
Sub goo()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: sub 'goo' shadows an overloadable member declared in the base interface 'I1'. If you want to overload the base method, this method must be declared 'Overloads'.
Sub goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub BC42014WRN_IndirectlyImplementedBaseMember5()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="IndirectlyImplementedBaseMember5">
<file name="a.vb"><![CDATA[
Interface I1
Sub goo()
End Interface
Interface I2
Inherits I1
End Interface
Class C1
Implements I1
Public Sub goo() Implements I1.goo
End Sub
End Class
Class C2
Inherits C1
Implements I2
Public Shadows Sub goo() Implements I1.goo
End Sub
End Class
]]></file>
</compilation>)
' BC42014 is deprecated
Dim expectedErrors1 = <errors></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub BC42015WRN_ImplementedBaseMember4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ImplementedBaseMember4">
<file name="a.vb"><![CDATA[
Imports System
Class c1
Implements IDisposable
Public Sub Dispose1() Implements System.IDisposable.Dispose
End Sub
End Class
Class c2
Inherits c1
Implements IDisposable
Public Sub Dispose1() Implements System.IDisposable.Dispose
End Sub
End Class
]]></file>
</compilation>)
' BC42015 is deprecated
Dim expectedErrors1 = <errors><![CDATA[
BC40003: sub 'Dispose1' shadows an overloadable member declared in the base class 'c1'. If you want to overload the base method, this method must be declared 'Overloads'.
Public Sub Dispose1() Implements System.IDisposable.Dispose
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(539499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539499")>
<Fact>
Public Sub BC42020WRN_ObjectAssumedVar1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Dim y() = New Object() {3}
End Sub
Public Fld
Public Function Goo(ByVal x) As Integer
Return 1
End Function
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe.WithOptionInfer(False).WithOptionStrict(OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42020: Variable declaration without an 'As' clause; type of Object assumed.
Dim y() = New Object() {3}
~
BC42020: Variable declaration without an 'As' clause; type of Object assumed.
Public Fld
~~~
BC42020: Variable declaration without an 'As' clause; type of Object assumed.
Public Function Goo(ByVal x) As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
compilation1 = compilation1.WithOptions(TestOptions.ReleaseExe.WithOptionInfer(False).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(compilation1)
End Sub
<WorkItem(539499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539499")>
<WorkItem(529849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529849")>
<Fact()>
Public Sub BC42020WRN_ObjectAssumedVar1WithStaticLocal()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Static x = 3
End Sub
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42020: Static variable declared without an 'As' clause; type of Object assumed.
Static x = 3
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
compilation1 = compilation1.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.Off))
CompilationUtils.AssertNoErrors(compilation1)
compilation1 = compilation1.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static x = 3
~
]]></expected>)
End Sub
<Fact>
Public Sub ValidTypeNameAsVariableNameInAssignment()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Compilation">
<file name="a.vb"><![CDATA[
Imports System
Namespace NS
End Namespace
Module Program2
Sub Main2(args As System.String())
DateTime = "hello"
NS = "hello"
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors><![CDATA[
BC30110: 'Date' is a structure type and cannot be used as an expression.
DateTime = "hello"
~~~~~~~~
BC30112: 'NS' is a namespace and cannot be used as an expression.
NS = "hello"
~~
]]></errors>)
End Sub
<Fact>
Public Sub BC30209ERR_StrictDisallowImplicitObject()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Public Fld
End Module
]]></file>
</compilation>, TestOptions.ReleaseDll.WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation1,
<errors><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Public Fld
~~~
]]></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Dim y() = New Object() {3}
End Sub
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe.WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation2, <errors/>)
compilation2 = compilation2.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(False).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation2,
<errors><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim y() = New Object() {3}
~
]]></errors>)
End Sub
<WorkItem(529849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529849")>
<Fact>
Public Sub BC30209ERR_StrictDisallowImplicitObjectWithStaticLocals()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BC30209ERR_StrictDisallowImplicitObjectWithStaticLocals">
<file name="a.vb"><![CDATA[
Module M1
Sub Main()
Static x = 3
End Sub
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithOptionStrict(OptionStrict.On))
CompilationUtils.AssertTheseDiagnostics(compilation1,
<errors><![CDATA[
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Static x = 3
~
]]></errors>)
End Sub
<WorkItem(539501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539501")>
<Fact>
Public Sub BC42021WRN_ObjectAssumed1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Function Func1()
Return 3
End Function
Sub Main()
End Sub
Delegate Function Func2()
ReadOnly Property Prop3
Get
Return Nothing
End Get
End Property
End Module
]]></file>
</compilation>, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom).WithOptionInfer(True))
Dim expectedErrors1 = <errors><![CDATA[
BC42021: Function without an 'As' clause; return type of Object assumed.
Function Func1()
~~~~~
BC42021: Function without an 'As' clause; return type of Object assumed.
Delegate Function Func2()
~~~~~
BC42022: Property without an 'As' clause; type of Object assumed.
ReadOnly Property Prop3
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
compilation1 = compilation1.WithOptions(New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off).WithOptionInfer(True))
CompilationUtils.AssertNoErrors(compilation1)
End Sub
<Fact>
Public Sub BC30210ERR_StrictDisallowsImplicitProc_4()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinVarDecl">
<file name="a.vb"><![CDATA[
Module M1
Function Func1()
Return 3
End Function
Sub Main()
End Sub
Delegate Function Func2()
ReadOnly Property Prop3
Get
Return Nothing
End Get
End Property
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On).WithOptionInfer(True))
Dim expectedErrors1 = <errors><![CDATA[
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Function Func1()
~~~~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Delegate Function Func2()
~~~~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
ReadOnly Property Prop3
~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' vbc Module1.vb /target:library /noconfig /optionstrict:custom
<Fact()>
Public Sub BC42022WRN_ObjectAssumedProperty1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ObjectAssumedProperty1">
<file name="a.vb"><![CDATA[
Module Module1
ReadOnly Property p()
Get
Return 2
End Get
End Property
End Module
]]></file>
</compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42022: Property without an 'As' clause; type of Object assumed.
ReadOnly Property p()
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
' EDMAURER: tested elsewhere
' <Fact()>
' Public Sub BC42102WRN_ComClassPropertySetObject1()
' Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib(
' <compilation name="ComClassPropertySetObject1">
' <file name="a.vb"><![CDATA[
' Imports Microsoft.VisualBasic
' <ComClass()> Public Class Class1
' Public WriteOnly Property prop2(ByVal x As String) As Object
' Set(ByVal Value As Object)
' End Set
' End Property
' End Class
' ]]></file>
' </compilation>)
' Dim expectedErrors1 = <errors><![CDATA[
'BC42102: 'Public WriteOnly Property prop2(x As String) As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.
' Public WriteOnly Property prop2(ByVal x As String) As Object
' ~~~~~
' ]]></errors>
' CompilationUtils.AssertTheseDeclarationErrors(compilation1, expectedErrors1)
' End Sub
<Fact()>
Public Sub BC42309WRN_XMLDocCrefAttributeNotFound1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocCrefAttributeNotFound1">
<file name="a.vb">
<![CDATA[
''' <see cref="System.Collections.Generic.List(Of _)"/>
Class E
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocCrefAttributeNotFound1">
<file name="a.vb">
<![CDATA[
''' <see cref="System.Collections.Generic.List(Of _)"/>
Class E
End Class
]]></file>
</compilation>, parseOptions:=VisualBasic.VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors = <errors><![CDATA[
BC42309: XML comment has a tag with a 'cref' attribute 'System.Collections.Generic.List(Of _)' that could not be resolved.
''' <see cref="System.Collections.Generic.List(Of _)"/>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42310WRN_XMLMissingFileOrPathAttribute1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLMissingFileOrPathAttribute1">
<file name="a.vb"><![CDATA[
'''<include/>
Class E
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLMissingFileOrPathAttribute1">
<file name="a.vb"><![CDATA[
'''<include/>
Class E
End Class
]]></file>
</compilation>, parseOptions:=VisualBasic.VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42310: XML comment tag 'include' must have a 'file' attribute. XML comment will be ignored.
'''<include/>
~~~~~~~~~~
BC42310: XML comment tag 'include' must have a 'path' attribute. XML comment will be ignored.
'''<include/>
~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42312WRN_XMLDocWithoutLanguageElement()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocWithoutLanguageElement">
<file name="a.vb"><![CDATA[
Class E
ReadOnly Property quoteForTheDay() As String
''' <summary>
Get
Return "hello"
End Get
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocWithoutLanguageElement">
<file name="a.vb"><![CDATA[
Class E
ReadOnly Property quoteForTheDay() As String
''' <summary>
Get
Return "hello"
End Get
End Property
End Class
]]></file>
</compilation>, parseOptions:=VisualBasic.VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
CompilationUtils.AssertTheseDiagnostics(compilation2,
<errors>
<![CDATA[
BC42312: XML documentation comments must precede member or type declarations.
''' <summary>
~~~~~~~~~~~
BC42304: XML documentation parse error: Element is missing an end tag. XML comment will be ignored.
''' <summary>
~~~~~~~~~
BC42304: XML documentation parse error: '>' expected. XML comment will be ignored.
''' <summary>
~
BC42304: XML documentation parse error: Expected beginning '<' for an XML tag. XML comment will be ignored.
''' <summary>
~
]]>
</errors>)
End Sub
<Fact()>
Public Sub BC42313WRN_XMLDocReturnsOnWriteOnlyProperty()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocReturnsOnWriteOnlyProperty">
<file name="a.vb"><![CDATA[
Class E
''' <returns></returns>
WriteOnly Property quoteForTheDay() As String
set
End set
End Property
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocReturnsOnWriteOnlyProperty">
<file name="a.vb"><![CDATA[
Class E
''' <returns></returns>
WriteOnly Property quoteForTheDay() As String
set
End set
End Property
End Class
]]></file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors = <errors><![CDATA[
BC42313: XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.
''' <returns></returns>
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42314WRN_XMLDocOnAPartialType()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="XMLDocOnAPartialType">
<file name="a.vb"><![CDATA[
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="XMLDocOnAPartialType">
<file name="a.vb"><![CDATA[
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary>
''' </summary>
''' <remarks></remarks>
partial Class E
End Class
''' <summary> 3
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary> 4
''' </summary>
''' <remarks></remarks>
partial Interface I
End Interface
''' <summary> 5
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
''' <summary> 6
''' </summary>
''' <remarks></remarks>
partial Module M
End Module
]]></file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors = <errors><![CDATA[
BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored.
''' <summary>
~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial class. XML comments for this class will be ignored.
''' <summary>
~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial interface. XML comments for this interface will be ignored.
''' <summary> 3
~~~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial interface. XML comments for this interface will be ignored.
''' <summary> 4
~~~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial module. XML comments for this module will be ignored.
''' <summary> 5
~~~~~~~~~~~~~
BC42314: XML comment cannot be applied more than once on a partial module. XML comments for this module will be ignored.
''' <summary> 6
~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42317WRN_XMLDocBadGenericParamTag2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocBadGenericParamTag2">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam name="X">typeparam E1</typeparam>
''' <summary>summary - E1</summary>
''' <remarks>remarks - E1</remarks>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocBadGenericParamTag2">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam name="X">typeparam E1</typeparam>
''' <summary>summary - E1</summary>
''' <remarks>remarks - E1</remarks>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42317: XML comment type parameter 'X' does not match a type parameter on the corresponding 'sub' statement.
''' <typeparam name="X">typeparam E1</typeparam>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42318WRN_XMLDocGenericParamTagWithoutName()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocGenericParamTagWithoutName">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam>typeparam E1</typeparam>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocGenericParamTagWithoutName">
<file name="a.vb">
<![CDATA[
Class C1(Of X)
''' <typeparam>typeparam E1</typeparam>
Sub E1(Of T)(ByVal p As X)
End Sub
End Class
]]>
</file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42318: XML comment type parameter must have a 'name' attribute.
''' <typeparam>typeparam E1</typeparam>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<Fact()>
Public Sub BC42319WRN_XMLDocExceptionTagWithoutCRef()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocExceptionTagWithoutCRef">
<file name="a.vb"><![CDATA[
Class Myexception
''' <exception></exception>
Sub Test()
End Sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1, <errors></errors>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="XMLDocExceptionTagWithoutCRef">
<file name="a.vb"><![CDATA[
Class Myexception
''' <exception></exception>
Sub Test()
End Sub
End Class
]]></file>
</compilation>, parseOptions:=VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
Dim expectedErrors =
<errors>
<![CDATA[
BC42319: XML comment exception must have a 'cref' attribute.
''' <exception></exception>
~~~~~~~~~~~~~~~~~~~~~~~
]]>
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation2, expectedErrors)
End Sub
<WorkItem(541661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541661")>
<Fact()>
Public Sub BC42333WRN_VarianceDeclarationAmbiguous3()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="VarianceDeclarationAmbiguous3">
<file name="a.vb"><![CDATA[
Imports System.Xml.Linq
Imports System.Linq
Module M1
Class C1
'COMPILEWARNING : BC42333, "System.Collections.Generic.IEnumerable(Of XDocument)", BC42333, "System.Collections.Generic.IEnumerable(Of XElement)"
Implements System.Collections.Generic.IEnumerable(Of XDocument), System.Collections.Generic.IEnumerable(Of XElement)
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Xml.Linq.XDocument) Implements System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XDocument).GetEnumerator
Return Nothing
End Function
Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator(Of System.Xml.Linq.XElement) Implements System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement).GetEnumerator
Return Nothing
End Function
Public Function GetEnumerator2() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return Nothing
End Function
End Class
End Module
]]></file>
</compilation>, XmlReferences)
Dim expectedErrors1 = <errors><![CDATA[
BC42333: Interface 'System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)' is ambiguous with another implemented interface 'System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XDocument)' due to the 'In' and 'Out' parameters in 'Interface IEnumerable(Of Out T)'.
Implements System.Collections.Generic.IEnumerable(Of XDocument), System.Collections.Generic.IEnumerable(Of XElement)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
' vbc Module1.vb /target:library /noconfig /optionstrict:custom
<Fact()>
Public Sub BC42347WRN_MissingAsClauseinFunction()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MissingAsClauseinFunction">
<file name="a.vb"><![CDATA[
Module M1
Function Goo()
Return Nothing
End Function
End Module
]]></file>
</compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict:=OptionStrict.Custom))
Dim expectedErrors1 = <errors><![CDATA[
BC42021: Function without an 'As' clause; return type of Object assumed.
Function Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
#End Region
' Check that errors are reported for type parameters.
<Fact>
Public Sub TypeParameterErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class X(Of T$)
End Class
Partial Class Y(Of T, U)
End Class
Class Z(Of T, In U, Out V)
End Class
Interface IZ(Of T, In U, Out V)
End Interface
]]></file>
<file name="b.vb"><![CDATA[
Partial Class Y(Of T, V)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32041: Type character cannot be used in a type parameter declaration.
Class X(Of T$)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class Z(Of T, In U, Out V)
~~
BC36722: Keywords 'Out' and 'In' can only be used in interface and delegate declarations.
Class Z(Of T, In U, Out V)
~~~
BC30931: Type parameter name 'V' does not match the name 'U' of the corresponding type parameter defined on one of the other partial types of 'Y'.
Partial Class Y(Of T, V)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
'Check that errors are reported for multiple type arguments
<Fact>
Public Sub MultipleTypeArgumentErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections
Class G(Of T)
Dim x As G(Of System.Int64,
System.Collections.Hashtable)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32043: Too many type arguments to 'G(Of T)'.
Dim x As G(Of System.Int64,
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
' Check that errors are reported for duplicate option statements in a single file.
<Fact>
Public Sub BC30225ERR_DuplicateOption1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Compare Text
Option Infer On
Option Compare On
]]></file>
<file name="b.vb"><![CDATA[
Option Strict On
Option Infer On
Option Strict On
Option Explicit
Option Explicit Off
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30225: 'Option Compare' statement can only appear once per file.
Option Compare On
~~~~~~~~~~~~~~~
BC30207: 'Option Compare' must be followed by 'Text' or 'Binary'.
Option Compare On
~~
BC30225: 'Option Strict' statement can only appear once per file.
Option Strict On
~~~~~~~~~~~~~~~~
BC30225: 'Option Explicit' statement can only appear once per file.
Option Explicit Off
~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BC31393ERR_ExpressionHasTheTypeWhichIsARestrictedType()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Sub M(tr As System.TypedReference)
Dim t = tr.GetType()
End Sub
End Module
]]></file>
</compilation>).VerifyDiagnostics()
End Sub
' Check that errors are reported for import statements in a single file.
<Fact>
Public Sub ImportErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports N1(Of String)
Imports A = N1
Imports B = N1
Imports N1.M1
Imports N1.M1
Imports A = N1.N2.C
Imports N3
Imports N1.N2
Imports N1.Gen(Of C)
Imports N1.Gen(Of Integer, String)
Imports System$.Collections%
Imports D$ = System.Collections
Imports N3
Imports System.Cheesecake.Frosting
]]></file>
<file name="b.vb"><![CDATA[
Namespace N1
Class Gen(Of T)
End Class
Module M1
End Module
End Namespace
Namespace N1.N2
Class C
End Class
End Namespace
Namespace N3
Class D
End Class
End Namespace
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32045: 'N1' has no type parameters and so cannot have type arguments.
Imports N1(Of String)
~~~~~~~~~~~~~
BC31051: Namespace or type 'M1' has already been imported.
Imports N1.M1
~~~~~
BC30572: Alias 'A' is already declared.
Imports A = N1.N2.C
~
BC30002: Type 'C' is not defined.
Imports N1.Gen(Of C)
~
BC32043: Too many type arguments to 'Gen(Of T)'.
Imports N1.Gen(Of Integer, String)
~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30468: Type declaration characters are not valid in this context.
Imports System$.Collections%
~~~~~~~
BC30468: Type declaration characters are not valid in this context.
Imports System$.Collections%
~~~~~~~~~~~~
BC31398: Type characters are not allowed on Imports aliases.
Imports D$ = System.Collections
~~
BC31051: Namespace or type 'N3' has already been imported.
Imports N3
~~
BC40056: Namespace or type specified in the Imports 'System.Cheesecake.Frosting' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports System.Cheesecake.Frosting
~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
' Check that errors are reported for import statements in a single file.
<Fact>
Public Sub ProjectImportErrors()
Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing
Dim globalImports = GlobalImport.Parse({
"N1(Of String)",
"A = N1",
"B = N1",
"N1.M1",
"N1.M1",
"A = N1.N2.C",
"N3",
"N1.N2",
"N1.Gen(Of C)",
"N1.Gen(Of Integer, String)",
"System$.Collections%",
"D$ = System.Collections",
"N3",
"System.Cheesecake.Frosting"
}, diagnostics)
Assert.NotEqual(diagnostics, Nothing)
CompilationUtils.AssertTheseDiagnostics(diagnostics,
<errors><![CDATA[
BC31398: Error in project-level import 'D$ = System.Collections' at 'D$' : Type characters are not allowed on Imports aliases.
]]></errors>)
' only include the imports with correct syntax:
Dim options = TestOptions.ReleaseDll.WithGlobalImports(globalImports)
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="b.vb"><![CDATA[
Namespace N1
Class Gen(Of T)
End Class
Module M1
End Module
End Namespace
Namespace N1.N2
Class C
End Class
End Namespace
Namespace N3
Class D
End Class
End Namespace
]]></file>
</compilation>, options)
Dim expectedErrors = <errors><![CDATA[
BC30002: Error in project-level import 'N1.Gen(Of C)' at 'C' : Type 'C' is not defined.
BC30468: Error in project-level import 'System$.Collections%' at 'Collections%' : Type declaration characters are not valid in this context.
BC30468: Error in project-level import 'System$.Collections%' at 'System$' : Type declaration characters are not valid in this context.
BC30572: Error in project-level import 'A = N1.N2.C' at 'A' : Alias 'A' is already declared.
BC32043: Error in project-level import 'N1.Gen(Of Integer, String)' at 'N1.Gen(Of Integer, String)' : Too many type arguments to 'Gen(Of T)'.
BC32045: Error in project-level import 'N1(Of String)' at 'N1(Of String)' : 'N1' has no type parameters and so cannot have type arguments.
BC40057: Namespace or type specified in the project-level Imports 'System.Cheesecake.Frosting' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub ModifierErrorsInsideNamespace()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Namespace n1
Shadows Enum e6
x
End Enum
Private Enum e7
x
End Enum
End Namespace
Shadows Enum e8
x
End Enum
Private Enum e9
x
End Enum
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC32200: 'e6' cannot be declared 'Shadows' outside of a class, structure, or interface.
Shadows Enum e6
~~
BC31089: Types declared 'Private' must be inside another type.
Private Enum e7
~~
BC32200: 'e8' cannot be declared 'Shadows' outside of a class, structure, or interface.
Shadows Enum e8
~~
BC31089: Types declared 'Private' must be inside another type.
Private Enum e9
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub ModifierErrorsInsideInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface i
Private Class c1
End Class
Shared Class c2
End Class
MustInherit Class c3
End Class
MustOverride Class c4
End Class
End Interface
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31070: Class in an interface cannot be declared 'Private'.
Private Class c1
~~~~~~~
BC30461: Classes cannot be declared 'Shared'.
Shared Class c2
~~~~~~
BC30461: Classes cannot be declared 'MustOverride'.
MustOverride Class c4
~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
' Checks for accessibility across partial types
<Fact>
Public Sub ModifierErrorsAcrossPartialTypes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Partial public Class c1
End Class
Partial friend Class c1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30925: Specified access 'Friend' for 'c1' does not match the access 'Public' specified on one of its other partial types.
Partial friend Class c1
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
NotInheritable class A
end class
Partial MustInherit Class A
End class
]]></file>
</compilation>)
Dim expectedErrors2 = <errors><![CDATA[
BC30926: 'MustInherit' cannot be specified for partial type 'A' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.
Partial MustInherit Class A
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation2, expectedErrors2)
End Sub
' Checks for missing partial on classes
<Fact>
Public Sub ModifierWarningsAcrossPartialTypes()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class cc1
End Class
Class cC1
End Class
partial Class Cc1
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40046: class 'cc1' and partial class 'Cc1' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Class cc1
~~~
BC40046: class 'cC1' and partial class 'Cc1' conflict in namespace '<Default>', but are being merged because one of them is declared partial.
Class cC1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class cc1
End Class
Class cC1
End Class
Class Cc1
End Class
]]></file>
</compilation>)
Dim expectedErrors2 = <errors><![CDATA[
BC30179: class 'cC1' and class 'cc1' conflict in namespace '<Default>'.
Class cC1
~~~
BC30179: class 'Cc1' and class 'cc1' conflict in namespace '<Default>'.
Class Cc1
~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation2, expectedErrors2)
End Sub
<Fact>
Public Sub ErrorTypeNotDefineType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim errs = compilation.GetDeclarationDiagnostics()
Assert.Equal(1, errs.Length())
Dim err = DirectCast(errs.Single(), Diagnostic)
Assert.Equal(DirectCast(ERRID.ERR_UndefinedType1, Integer), err.Code)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers()(1), FieldSymbol)
Dim sym = fsym.Type
Assert.Equal(SymbolKind.ErrorType, sym.Kind)
Assert.Equal("B", sym.Name)
Assert.Null(sym.ContainingAssembly)
Assert.Null(sym.ContainingSymbol)
Assert.Equal(Accessibility.Public, sym.DeclaredAccessibility)
Assert.False(sym.IsShared)
Assert.False(sym.IsMustOverride)
Assert.False(sym.IsNotOverridable)
Assert.False(sym.IsValueType)
Assert.True(sym.IsReferenceType)
Assert.Equal(0, sym.Interfaces.Length())
Assert.Null(sym.BaseType)
Assert.Equal("B", DirectCast(sym, ErrorTypeSymbol).ConstructedFrom.ToTestDisplayString())
Assert.Equal(0, sym.GetAttributes().Length()) ' Enumerable.Empty<SymbolAttribute>()
Assert.Equal(0, sym.GetMembers().Length()) ' Enumerable.Empty<Symbol>()
Assert.Equal(0, sym.GetMembers(String.Empty).Length())
Assert.Equal(0, sym.GetTypeMembers().Length()) ' Enumerable.Empty<NamedTypeSymbol>()
Assert.Equal(0, sym.GetTypeMembers(String.Empty).Length())
Assert.Equal(0, sym.GetTypeMembers(String.Empty, 0).Length())
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClass()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31447: Class 'B' cannot reference itself in Inherits clause.
Inherits B.C.X
~
]]></errors>)
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClass2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
Public Class A
End Class
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31447: Class 'B' cannot reference itself in Inherits clause.
Inherits B.C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
Public Class A
End Class
End Class
End Class
Class B
Inherits C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface A
Class X
End Class
End Interface
Class B
Inherits C.X
Public Interface C
Inherits A
End Interface
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits C.X
~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass6()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
End Class
End Class
Class B
Inherits C(Of Integer).X
Public Class C(Of T)
Inherits A
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C(Of Integer)' in Inherits clause.
Inherits C(Of Integer).X
~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass7()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
Class A
End Class
End Class
End Class
Class B
Inherits D.X
Public Class C
Inherits A
End Class
End Class
Class D
Inherits B.C
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31449: Inherits clause of class 'B' causes cyclic dependency:
'B.C' is nested in 'B'.
Base type of 'B' needs 'B.C' to be resolved.
Inherits D.X
~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass8()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
Class A
End Class
End Class
End Class
Class B
Inherits D
Public Class C
Inherits A
End Class
End Class
Class D
Inherits B.C.X
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31449: Inherits clause of class 'B.C' causes cyclic dependency:
Base type of 'D' needs 'B.C' to be resolved.
Base type of 'B.C' needs 'D' to be resolved.
Inherits A
~
BC30002: Type 'B.C.X' is not defined.
Inherits B.C.X
~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClass9()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Class X
Class A
End Class
End Class
End Class
Class B
Inherits D.C.X
Public Class C
Inherits A
End Class
End Class
Class D
Inherits B
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'B' cannot reference its nested type 'B.C' in Inherits clause.
Inherits D.C.X
~~~
]]></errors>)
End Sub
<Fact>
Public Sub AccessBaseClassThroughNestedClassA()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface IIndia(Of T)
End Interface
Class Alpha
Class Bravo
End Class
End Class
Class Charlie
Inherits Alpha
Implements IIndia(Of Charlie.Bravo)
End Class
Class Echo
Implements IIndia(Of Echo)
End Class
Class Golf
Implements IIndia(Of Golf.Hotel)
Class Hotel
End Class
End Class
Class Juliet
Implements IIndia(Of Juliet.Kilo.Lima)
Class Kilo
Class Lima
End Class
End Class
End Class
Class November(Of T)
End Class
Class Oscar
Inherits November(Of Oscar)
End Class
Class Papa
Inherits November(Of Papa.Quebec)
Class Quebec
End Class
End Class
Class Romeo
Inherits November(Of Romeo.Sierra.Tango)
Class Sierra
Class Tango
End Class
End Class
End Class
Class Uniform
Implements Uniform.IIndigo
Interface IIndigo
End Interface
End Class
Interface IBlah
Inherits Victor.IIdiom
End Interface
Class Victor
Implements IBlah
Interface IIdiom
End Interface
End Class
Class Xray
Implements Yankee.IIda
Class Yankee
Inherits Xray
Interface IIda
End Interface
End Class
End Class
Class Beta
Inherits Gamma
Class Gamma
End Class
End Class
Class Delta
Inherits Delta.Epsilon
Class Epsilon
End Class
End Class
Class Zeta(Of T)
Inherits Eta(Of Beta)
End Class
Class Eta(Of T)
Inherits Zeta(Of Delta)
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31446: Class 'Beta' cannot reference its nested type 'Beta.Gamma' in Inherits clause.
Inherits Gamma
~~~~~
BC31447: Class 'Delta' cannot reference itself in Inherits clause.
Inherits Delta.Epsilon
~~~~~
BC30257: Class 'Zeta(Of T)' cannot inherit from itself:
'Zeta(Of T)' inherits from 'Eta(Of Beta)'.
'Eta(Of Beta)' inherits from 'Zeta(Of T)'.
Inherits Eta(Of Beta)
~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessInterfaceThroughNestedClass()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Interface X
End Interface
End Class
Class B
Implements B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClassSemantic_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve X from 'Inherits B.C.X' first, then 'Inherits A'
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessBaseClassThroughNestedClassSemantic_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Class X
End Class
End Class
Class B
Inherits B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve 'Inherits A', then X from 'Inherits B.C.X' first
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessInterfaceThroughNestedClassSemantic_1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Interface X
End Interface
End Class
Class B
Implements B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve X from 'Inherits B.C.X' first, then 'Implements A'
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
End Sub
<WorkItem(539568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539568")>
<Fact>
Public Sub AccessInterfaceThroughNestedClassSemantic_2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class A
Public Interface X
End Interface
End Class
Class B
Implements B.C.X
Public Class C
Inherits A
End Class
End Class
]]></file>
</compilation>
)
' resolve 'Inherits A', then X from 'Implements B.C.X' first
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 8).Parent, ExpressionSyntax))
model.GetSemanticInfoSummary(CType(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierToken, 6).Parent, ExpressionSyntax))
End Sub
<Fact>
Public Sub InterfaceModifierErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Static Interface i1
End Interface
Static Class c1
End Class
Static Structure s1
End Structure
Static Enum e1
dummy
End Enum
Static Delegate Sub s()
Static Module m
End Module
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30397: 'Static' is not valid on an Interface declaration.
Static Interface i1
~~~~~~
BC30461: Classes cannot be declared 'Static'.
Static Class c1
~~~~~~
BC30395: 'Static' is not valid on a Structure declaration.
Static Structure s1
~~~~~~
BC30396: 'Static' is not valid on an Enum declaration.
Static Enum e1
~~~~~~
BC30385: 'Static' is not valid on a Delegate declaration.
Static Delegate Sub s()
~~~~~~
BC31052: Modules cannot be declared 'Static'.
Static Module m
~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub BaseClassErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="1.vb"><![CDATA[
Option Strict On
Class C1
Inherits Object, Object
End Class
Class C11
Inherits System.Exception
Inherits System.Exception
End Class
Class C2
Inherits System.Collections.ArrayList, System.Collections.Generic.List(Of Integer)
End Class
Class C3(Of T)
Inherits T
End Class
Partial Class C4
Inherits System.Collections.ArrayList
End Class
NotInheritable Class NI
End class
]]></file>
<file name="a.vb"><![CDATA[
Option Strict Off
Public Partial Class C4
Inherits System.Collections.Generic.List(Of Integer)
End Class
Interface I1
End Interface
Class C5
Inherits I1
End Class
Class C6
Inherits System.Guid
End Class
Class C7
Inherits NI
End Class
Class C8
Inherits System.Delegate
End Class
Module M1
Inherits System.Object
End Module
Structure S1
Inherits System.Collections.Hashtable
End Structure
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits Object, Object
~~~~~~~~~~~~~~~~~~~~~~~
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits System.Exception
~~~~~~~~~~~~~~~~~~~~~~~~~
BC30121: 'Inherits' can appear only once within a 'Class' statement and can only specify one class.
Inherits System.Collections.ArrayList, System.Collections.Generic.List(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC32055: Class 'C3' cannot inherit from a type parameter.
Inherits T
~
BC30928: Base class 'List(Of Integer)' specified for class 'C4' cannot be different from the base class 'ArrayList' of one of its other partial types.
Inherits System.Collections.Generic.List(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30258: Classes can inherit only from other classes.
Inherits I1
~~
BC30258: Classes can inherit only from other classes.
Inherits System.Guid
~~~~~~~~~~~
BC30299: 'C7' cannot inherit from class 'NI' because 'NI' is declared 'NotInheritable'.
Inherits NI
~~
BC30015: Inheriting from '[Delegate]' is not valid.
Inherits System.Delegate
~~~~~~~~~~~~~~~
BC30230: 'Inherits' not valid in Modules.
Inherits System.Object
~~~~~~~~~~~~~~~~~~~~~~
BC30628: Structures cannot have 'Inherits' statements.
Inherits System.Collections.Hashtable
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BaseClassErrors2a()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class B(Of T)
Class Inner
End Class
End Class
Class D1
Inherits B(Of Integer)
Dim x As B(Of D1.Inner)
End Class
Class D2
Inherits B(Of D2.Inner)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30002: Type 'D2.Inner' is not defined.
Inherits B(Of D2.Inner)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact()>
Public Sub BaseClassErrors2b()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class XC
Inherits XB(Of XD.Inner2)
End Class
Class XD
Inherits XB(Of XC.Inner2)
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC31449: Inherits clause of class 'XC' causes cyclic dependency:
Base type of 'XD' needs 'XC' to be resolved.
Base type of 'XC' needs 'XD' to be resolved.
Inherits XB(Of XD.Inner2)
~~~~~~~~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XB(Of XC.Inner2)
~~~~~~~~~
]]></errors>)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2c()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class X0
Inherits XB(Of X1.Inner2)
End Class
Class X1
Inherits XB(Of X2.Inner2)
End Class
Class X2
Inherits XB(Of X3.Inner2)
End Class
Class X3
Inherits XB(Of X4.Inner2)
End Class
Class X4
Inherits XB(Of X5.Inner2)
End Class
Class X5
Inherits XB(Of X6.Inner2)
End Class
Class X6
Inherits XB(Of X7.Inner2)
End Class
Class X7
Inherits XB(Of X8.Inner2)
End Class
Class X8
Inherits XB(Of X9.Inner2)
End Class
Class X9
Inherits XB(Of X0.Inner2)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31449: Inherits clause of class 'X0' causes cyclic dependency:
Base type of 'X1' needs 'X2' to be resolved.
Base type of 'X2' needs 'X3' to be resolved.
Base type of 'X3' needs 'X4' to be resolved.
Base type of 'X4' needs 'X5' to be resolved.
Base type of 'X5' needs 'X6' to be resolved.
Base type of 'X6' needs 'X7' to be resolved.
Base type of 'X7' needs 'X8' to be resolved.
Base type of 'X8' needs 'X9' to be resolved.
Base type of 'X9' needs 'X0' to be resolved.
Base type of 'X0' needs 'X1' to be resolved.
Inherits XB(Of X1.Inner2)
~~~~~~~~~~~~~~~~
BC30002: Type 'X0.Inner2' is not defined.
Inherits XB(Of X0.Inner2)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2d()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class X0
Inherits XB(Of X9.Inner2) ' X0
End Class
Class X1
Inherits XB(Of X9.Inner2) ' X1
End Class
Class X2
Inherits XB(Of X1.Inner2)
End Class
Class X3
Inherits XB(Of X2.Inner2)
End Class
Class X4
Inherits XB(Of X3.Inner2)
End Class
Class X5
Inherits XB(Of X4.Inner2)
End Class
Class X6
Inherits XB(Of X5.Inner2)
End Class
Class X7
Inherits XB(Of X6.Inner2)
End Class
Class X8
Inherits XB(Of X7.Inner2)
End Class
Class X9
Inherits XB(Of X8.Inner2)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31449: Inherits clause of class 'X1' causes cyclic dependency:
Base type of 'X9' needs 'X8' to be resolved.
Base type of 'X8' needs 'X7' to be resolved.
Base type of 'X7' needs 'X6' to be resolved.
Base type of 'X6' needs 'X5' to be resolved.
Base type of 'X5' needs 'X4' to be resolved.
Base type of 'X4' needs 'X3' to be resolved.
Base type of 'X3' needs 'X2' to be resolved.
Base type of 'X2' needs 'X1' to be resolved.
Base type of 'X1' needs 'X9' to be resolved.
Inherits XB(Of X9.Inner2) ' X1
~~~~~~~~~~~~~~~~
BC30002: Type 'X1.Inner2' is not defined.
Inherits XB(Of X1.Inner2)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2e()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XB(Of T)
Class Inner2
End Class
End Class
Class XC
Inherits XB(Of XD.Inner2)
End Class
Class XD
Inherits XB(Of XC.Inner2)
End Class
Class XE
Inherits XB(Of XC.Inner2)
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC31449: Inherits clause of class 'XC' causes cyclic dependency:
Base type of 'XD' needs 'XC' to be resolved.
Base type of 'XC' needs 'XD' to be resolved.
Inherits XB(Of XD.Inner2)
~~~~~~~~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XB(Of XC.Inner2)
~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XB(Of XC.Inner2)
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2f()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XC
Inherits XD.Inner2
End Class
Class XD
Inherits XC.Inner2
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC30002: Type 'XD.Inner2' is not defined.
Inherits XD.Inner2
~~~~~~~~~
BC31449: Inherits clause of class 'XC' causes cyclic dependency:
Base type of 'XD' needs 'XC' to be resolved.
Base type of 'XC' needs 'XD' to be resolved.
Inherits XD.Inner2
~~~~~~~~~
BC30002: Type 'XC.Inner2' is not defined.
Inherits XC.Inner2
~~~~~~~~~
]]></errors>)
Next
End Sub
<Fact()>
Public Sub BaseClassErrors2g()
' There is a race known in base type detection
For i = 0 To 50
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb"><![CDATA[
Class XC
Inherits XD.Inner2
End Class
Class XD
Inherits XC.Inner2
Class Inner2
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<errors><![CDATA[
BC30002: Type 'XC.Inner2' is not defined.
Inherits XC.Inner2
~~~~~~~~~
BC31449: Inherits clause of class 'XD' causes cyclic dependency:
'XD.Inner2' is nested in 'XD'.
Base type of 'XD' needs 'XD.Inner2' to be resolved.
Inherits XC.Inner2
~~~~~~~~~
]]></errors>)
Next
End Sub
<Fact>
Public Sub FieldErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Partial Class C
Public Public p as Integer
Public Private q as Integer
Private MustOverride r as Integer
Dim s
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict On
Public Partial Class C
Dim x% As Integer
Dim t ' error only if Option Strict is on
Dim u? as Integer?
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30178: Specifier is duplicated.
Public Public p as Integer
~~~~~~
BC30176: Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.
Public Private q as Integer
~~~~~~~
BC30235: 'MustOverride' is not valid on a member variable declaration.
Private MustOverride r as Integer
~~~~~~~~~~~~
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Dim x% As Integer
~~
BC30209: Option Strict On requires all variable declarations to have an 'As' clause.
Dim t ' error only if Option Strict is on
~
BC33100: Nullable modifier cannot be specified on both a variable and its type.
Dim u? as Integer?
~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MethodErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Partial Class C
Protected Private Sub m1()
End Sub
NotOverridable MustOverride Sub m2()
NotOverridable Overridable Sub m3()
End Sub
Overridable Overrides Sub m4()
End Sub
Overridable Shared Sub m5()
End Sub
Public Function m6()
End Function
Public Function m7%() as string
End Function
Shadows Overloads Sub m8()
End Sub
Sub m9(Of T$)()
End Sub
Public MustInherit Sub m10()
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Partial Class C
Public Sub x$()
End Sub
End Class
]]></file>
</compilation>, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15))
Dim expectedErrors = <errors><![CDATA[
BC36716: Visual Basic 15.0 does not support Private Protected.
Protected Private Sub m1()
~~~~~~~
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
NotOverridable MustOverride Sub m2()
~~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
NotOverridable MustOverride Sub m2()
~~
BC30177: Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.
NotOverridable Overridable Sub m3()
~~~~~~~~~~~
BC31088: 'NotOverridable' cannot be specified for methods that do not override another method.
NotOverridable Overridable Sub m3()
~~
BC30730: Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.
Overridable Overrides Sub m4()
~~~~~~~~~
BC30501: 'Shared' cannot be combined with 'Overridable' on a method declaration.
Overridable Shared Sub m5()
~~~~~~~~~~~
BC30210: Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.
Public Function m6()
~~
BC30302: Type character '%' cannot be used in a declaration with an explicit type.
Public Function m7%() as string
~~~
BC31408: 'Overloads' and 'Shadows' cannot be combined.
Shadows Overloads Sub m8()
~~~~~~~~~
BC32041: Type character cannot be used in a type parameter declaration.
Sub m9(Of T$)()
~~
BC30242: 'MustInherit' is not valid on a method declaration.
Public MustInherit Sub m10()
~~~~~~~~~~~
BC30303: Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.
Public Sub x$()
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MethodErrorsInInNotInheritableClass()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
NotInheritable Class c
Overridable Sub s1()
End Sub
NotOverridable Sub s2()
End Sub
MustOverride Sub s3()
Default Sub s4()
End Sub
Protected Sub s5()
End Sub
Protected Friend Sub s6()
End Sub
Overridable Sub New()
End Sub
NotOverridable Sub New(ByVal i1 As Integer)
End Sub
MustOverride Sub New(ByVal i1 As Integer, ByVal i2 As Integer)
Default Sub s4(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer)
End Sub
Protected Sub s5(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal i4 As Integer)
End Sub
Protected Friend Sub s6(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer, ByVal i4 As Integer, ByVal i5 As Integer)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Sub s1()
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Sub s2()
~~~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Sub s3()
~~~~~~~~~~~~
BC30242: 'Default' is not valid on a method declaration.
Default Sub s4()
~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'Overridable'.
Overridable Sub New()
~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'NotOverridable'.
NotOverridable Sub New(ByVal i1 As Integer)
~~~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
MustOverride Sub New(ByVal i1 As Integer, ByVal i2 As Integer)
~~~~~~~~~~~~
BC30242: 'Default' is not valid on a method declaration.
Default Sub s4(ByVal i1 As Integer, ByVal i2 As Integer, ByVal i3 As Integer)
~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MethodErrorsInInterfaces1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports System.Collections.Generic
Public Interface i1
Private Sub m1()
Protected Sub m2()
Friend Sub m3()
Static Sub m4()
Shared Sub m5()
Shadows Sub m6()
MustInherit Sub m7()
Overloads Sub m8()
NotInheritable Sub m9()
Overrides Sub m10()
NotOverridable Sub m11()
MustOverride Sub m12()
ReadOnly Sub m13()
WriteOnly Sub m14()
Dim Sub m15()
Const Sub m16()
Default Sub m17()
WithEvents Sub m18()
Widening Sub m19()
Narrowing Sub m20()
sub m21 implements IEnumerator.MoveNext
sub m22 handles DownButton.Click
Iterator Function I1() as IEnumerable(of Integer)
End Interface
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30270: 'Private' is not valid on an interface method declaration.
Private Sub m1()
~~~~~~~
BC30270: 'Protected' is not valid on an interface method declaration.
Protected Sub m2()
~~~~~~~~~
BC30270: 'Friend' is not valid on an interface method declaration.
Friend Sub m3()
~~~~~~
BC30242: 'Static' is not valid on a method declaration.
Static Sub m4()
~~~~~~
BC30270: 'Shared' is not valid on an interface method declaration.
Shared Sub m5()
~~~~~~
BC30242: 'MustInherit' is not valid on a method declaration.
MustInherit Sub m7()
~~~~~~~~~~~
BC30242: 'NotInheritable' is not valid on a method declaration.
NotInheritable Sub m9()
~~~~~~~~~~~~~~
BC30270: 'Overrides' is not valid on an interface method declaration.
Overrides Sub m10()
~~~~~~~~~
BC30270: 'NotOverridable' is not valid on an interface method declaration.
NotOverridable Sub m11()
~~~~~~~~~~~~~~
BC30270: 'MustOverride' is not valid on an interface method declaration.
MustOverride Sub m12()
~~~~~~~~~~~~
BC30242: 'ReadOnly' is not valid on a method declaration.
ReadOnly Sub m13()
~~~~~~~~
BC30242: 'WriteOnly' is not valid on a method declaration.
WriteOnly Sub m14()
~~~~~~~~~
BC30242: 'Dim' is not valid on a method declaration.
Dim Sub m15()
~~~
BC30242: 'Const' is not valid on a method declaration.
Const Sub m16()
~~~~~
BC30242: 'Default' is not valid on a method declaration.
Default Sub m17()
~~~~~~~
BC30242: 'WithEvents' is not valid on a method declaration.
WithEvents Sub m18()
~~~~~~~~~~
BC30242: 'Widening' is not valid on a method declaration.
Widening Sub m19()
~~~~~~~~
BC30242: 'Narrowing' is not valid on a method declaration.
Narrowing Sub m20()
~~~~~~~~~
BC30270: 'implements' is not valid on an interface method declaration.
sub m21 implements IEnumerator.MoveNext
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30270: 'handles' is not valid on an interface method declaration.
sub m22 handles DownButton.Click
~~~~~~~~~~~~~~~~~~~~~~~~
BC30506: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
sub m22 handles DownButton.Click
~~~~~~~~~~
BC30270: 'Iterator' is not valid on an interface method declaration.
Iterator Function I1() as IEnumerable(of Integer)
~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_01()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Shared Sub Handler() Handles EventHost.SomeEvent
End Sub
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Shared Sub Handler() Handles EventHost.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_02()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Sub Handler() Handles EventHost.SomeEvent
End Sub
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30594: Events of shared WithEvents variables cannot be handled by non-shared methods.
Private Sub Handler() Handles EventHost.SomeEvent
~~~~~~~~~
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Sub Handler() Handles EventHost.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_03()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Shared Sub Handler() Handles EventHost.SomeEvent, EventHost2.SomeEvent
End Sub
Protected Shared WithEvents EventHost2 As EventHost
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Shared Sub Handler() Handles EventHost.SomeEvent, EventHost2.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
<WorkItem(50472, "https://github.com/dotnet/roslyn/issues/50472")>
<WorkItem(1263908, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1263908")>
Public Sub UnsupportedHandles_04()
Dim compilation = CompilationUtils.CreateCompilation(
<compilation>
<file name="a.vb"><![CDATA[
Public Class DerivedClass
Inherits BaseClass
Private Shared Sub Handler() Handles EventHost2.SomeEvent, EventHost.SomeEvent
End Sub
Protected Shared WithEvents EventHost2 As EventHost
End Class
Public MustInherit Class BaseClass
Protected Shared WithEvents EventHost As EventHost
End Class
Public Class EventHost
Public Event SomeEvent()
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC36611: Events of shared WithEvents variables cannot be handled by methods in a different type.
Private Shared Sub Handler() Handles EventHost2.SomeEvent, EventHost.SomeEvent
~~~~~~~~~
]]></errors>
compilation.AssertTheseDeclarationDiagnostics(expectedErrors)
compilation.AssertTheseEmitDiagnostics(expectedErrors)
End Sub
<Fact>
Public Sub ErrorTypeSymbol_DefaultMember_CodeCoverageItems()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Coverage">
<file name="a.vb"><![CDATA[
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim errs = compilation.GetDeclarationDiagnostics()
Assert.Equal(1, Enumerable.Count(Of Diagnostic)(errs))
Dim err As Diagnostic = Enumerable.Single(Of Diagnostic)(errs)
Assert.Equal(&H7532, err.Code)
Dim fieldSymb As FieldSymbol = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single.GetMembers.Item(1), FieldSymbol)
Dim symbType As TypeSymbol = fieldSymb.Type
Dim errTypeSym As ErrorTypeSymbol = DirectCast(symbType, ErrorTypeSymbol)
Assert.Equal(SymbolKind.ErrorType, errTypeSym.Kind)
Assert.Equal("B", errTypeSym.Name)
Assert.Null(errTypeSym.ContainingAssembly)
Assert.Null(errTypeSym.ContainingSymbol)
Assert.Equal(Accessibility.Public, errTypeSym.DeclaredAccessibility)
Assert.False(errTypeSym.IsShared)
Assert.False(errTypeSym.IsMustOverride)
Assert.False(errTypeSym.IsNotOverridable)
Assert.False(errTypeSym.IsValueType)
Assert.True(errTypeSym.IsReferenceType)
Assert.Equal(SpecializedCollections.EmptyCollection(Of String), errTypeSym.MemberNames)
Assert.Equal(ImmutableArray.Create(Of Symbol)(), errTypeSym.GetMembers)
Assert.Equal(ImmutableArray.Create(Of Symbol)(), errTypeSym.GetMembers("B"))
Assert.Equal(ImmutableArray.Create(Of NamedTypeSymbol)(), errTypeSym.GetTypeMembers)
Assert.Equal(ImmutableArray.Create(Of NamedTypeSymbol)(), errTypeSym.GetTypeMembers("B"))
Assert.Equal(ImmutableArray.Create(Of NamedTypeSymbol)(), errTypeSym.GetTypeMembers("B", 1))
Assert.Equal(TypeKind.Error, errTypeSym.TypeKind)
Assert.Equal(ImmutableArray.Create(Of Location)(), errTypeSym.Locations)
Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), errTypeSym.DeclaringSyntaxReferences)
Assert.Equal(0, errTypeSym.Arity)
Assert.Null(errTypeSym.EnumUnderlyingType)
Assert.Equal("B", errTypeSym.Name)
Assert.Equal(0, errTypeSym.TypeArguments.Length)
Assert.Equal(0, errTypeSym.TypeParameters.Length)
Assert.Equal(errTypeSym.CandidateSymbols.Length, errTypeSym.IErrorTypeSymbol_CandidateSymbols.Length)
End Sub
<Fact>
Public Sub ConstructorErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Partial Class C
Public Overridable Sub New(x as Integer)
End Sub
MustOverride Sub New(y as String)
NotOverridable Friend Sub New(z as Object)
End Sub
Private Shadows Sub New(z as Object, a as integer)
End Sub
Protected Overloads Sub New(z as Object, a as string)
End Sub
Public Static Sub New(z as string, a as Object)
End Sub
Overrides Sub New()
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Partial Class C
End Class
Public Interface I
Sub New()
End Interface
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30364: 'Sub New' cannot be declared 'Overridable'.
Public Overridable Sub New(x as Integer)
~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'MustOverride'.
MustOverride Sub New(y as String)
~~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'NotOverridable'.
NotOverridable Friend Sub New(z as Object)
~~~~~~~~~~~~~~
BC30364: 'Sub New' cannot be declared 'Shadows'.
Private Shadows Sub New(z as Object, a as integer)
~~~~~~~
BC32040: The 'Overloads' keyword is used to overload inherited members; do not use the 'Overloads' keyword when overloading 'Sub New'.
Protected Overloads Sub New(z as Object, a as string)
~~~~~~~~~
BC30242: 'Static' is not valid on a method declaration.
Public Static Sub New(z as string, a as Object)
~~~~~~
BC30283: 'Sub New' cannot be declared 'Overrides'.
Overrides Sub New()
~~~~~~~~~
BC30363: 'Sub New' cannot be declared in an interface.
Sub New()
~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub SharedConstructorErrors1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Class C
Public Shared Sub New() '1
End Sub
Private Shared Sub New() '2
End Sub
Friend Shared Sub New() '3
End Sub
Shared Protected Sub New() '4
End Sub
Shared Protected Friend Sub New() '5
End Sub
Shared Sub New(x as integer) '6
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Module M
Public Sub New() '8
End Sub
Private Sub New() '9
End Sub
Friend Sub New() '10
End Sub
Protected Sub New() '11
End Sub
Protected Friend Sub New() '12
End Sub
Sub New(x as Integer, byref y as string) '13
End Sub
End Module
]]></file>
</compilation>)
Dim expectedErrors =
<errors><![CDATA[
BC30480: Shared 'Sub New' cannot be declared 'Public'.
Public Shared Sub New() '1
~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Public Shared Sub New() '1
~~~
BC30480: Shared 'Sub New' cannot be declared 'Private'.
Private Shared Sub New() '2
~~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Private Shared Sub New() '2
~~~
BC30480: Shared 'Sub New' cannot be declared 'Friend'.
Friend Shared Sub New() '3
~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Friend Shared Sub New() '3
~~~
BC30480: Shared 'Sub New' cannot be declared 'Protected'.
Shared Protected Sub New() '4
~~~~~~~~~
BC30269: 'Private Shared Sub New()' has multiple definitions with identical signatures.
Shared Protected Sub New() '4
~~~
BC30480: Shared 'Sub New' cannot be declared 'Protected Friend'.
Shared Protected Friend Sub New() '5
~~~~~~~~~~~~~~~~
BC30479: Shared 'Sub New' cannot have any parameters.
Shared Sub New(x as integer) '6
~~~~~~~~~~~~~~
BC30480: Shared 'Sub New' cannot be declared 'Public'.
Public Sub New() '8
~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Public Sub New() '8
~~~
BC30480: Shared 'Sub New' cannot be declared 'Private'.
Private Sub New() '9
~~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Private Sub New() '9
~~~
BC30480: Shared 'Sub New' cannot be declared 'Friend'.
Friend Sub New() '10
~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Friend Sub New() '10
~~~
BC30433: Methods in a Module cannot be declared 'Protected'.
Protected Sub New() '11
~~~~~~~~~
BC30269: 'Private Sub New()' has multiple definitions with identical signatures.
Protected Sub New() '11
~~~
BC30433: Methods in a Module cannot be declared 'Protected Friend'.
Protected Friend Sub New() '12
~~~~~~~~~~~~~~~~
BC30479: Shared 'Sub New' cannot have any parameters.
Sub New(x as Integer, byref y as string) '13
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub ParameterErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Public Partial Class C
Public Sub m1(x)
End Sub
Public Sub m2(byref byval k as Integer)
End Sub
Public Sub m3(byref byref k as Integer)
End Sub
Public Sub m4(ByRef ParamArray x() as string)
End Sub
Public Sub m5(ParamArray q as Integer)
End Sub
End Class
]]></file>
<file name="b.vb"><![CDATA[
Option Strict Off
Public Partial Class C
Public Sub m8(x, y$)
End Sub
Public Sub m9(x, z As String, w)
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors = <errors><![CDATA[
BC30211: Option Strict On requires that all method parameters have an 'As' clause.
Public Sub m1(x)
~
BC30641: 'ByVal' and 'ByRef' cannot be combined.
Public Sub m2(byref byval k as Integer)
~~~~~
BC30785: Parameter specifier is duplicated.
Public Sub m3(byref byref k as Integer)
~~~~~
BC30667: ParamArray parameters must be declared 'ByVal'.
Public Sub m4(ByRef ParamArray x() as string)
~~~~~~~~~~
BC30050: ParamArray parameter must be an array.
Public Sub m5(ParamArray q as Integer)
~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Public Sub m8(x, y$)
~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Public Sub m9(x, z As String, w)
~
BC30529: All parameters must be explicitly typed if any of them are explicitly typed.
Public Sub m9(x, z As String, w)
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors)
End Sub
<Fact>
Public Sub MoreParameterErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MoreParameterErrors">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1(f1 as integer) as Integer
return 0
End Function
Function F1(i1 as integer, I1 as integer) as Integer
return 0
End Function
Function F1(of T1) (i1 as integer, t1 as integer) as Integer
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30530: Parameter cannot have the same name as its defining function.
Function F1(f1 as integer) as Integer
~~
BC30237: Parameter already declared with name 'I1'.
Function F1(i1 as integer, I1 as integer) as Integer
~~
BC32089: 't1' is already declared as a type parameter of this method.
Function F1(of T1) (i1 as integer, t1 as integer) as Integer
~~
]]></expected>)
End Sub
<Fact>
Public Sub LocalDeclarationSameAsFunctionNameError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalDeclarationSameAsFunctionNameError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1() as Integer
dim f1 as integer = 0
do
dim f1 As integer = 0
loop
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30290: Local variable cannot have the same name as the function containing it.
dim f1 as integer = 0
~~
BC30290: Local variable cannot have the same name as the function containing it.
dim f1 As integer = 0
~~
]]></expected>)
End Sub
<Fact>
Public Sub DuplicateLocalDeclarationError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalDeclarationError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1() as Integer
dim i as long = 0
dim i as integer = 0
dim j,j as integer
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30288: Local variable 'i' is already declared in the current block.
dim i as integer = 0
~
BC42024: Unused local variable: 'j'.
dim j,j as integer
~
BC30288: Local variable 'j' is already declared in the current block.
dim j,j as integer
~
BC42024: Unused local variable: 'j'.
dim j,j as integer
~
]]></expected>)
End Sub
<Fact>
Public Sub LocalDeclarationTypeParameterError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalDeclarationError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1(of T)() as Integer
dim t as integer = 0
do
dim t as integer = 0
loop
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC32089: 't' is already declared as a type parameter of this method.
dim t as integer = 0
~
BC30616: Variable 't' hides a variable in an enclosing block.
dim t as integer = 0
~
]]></expected>)
End Sub
<Fact>
Public Sub LocalDeclarationParameterError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="DuplicateLocalDeclarationError">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Function F1(p as integer) as Integer
dim p as integer = 0
do
dim p as integer = 0
loop
return 0
End Function
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30734: 'p' is already declared as a parameter of this method.
dim p as integer = 0
~
BC30616: Variable 'p' hides a variable in an enclosing block.
dim p as integer = 0
~
]]></expected>)
End Sub
' Checks for duplicate type parameters
<Fact>
Public Sub DuplicateMethodTypeParameterErrors()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class BB(Of T)
Class A(Of t1)
Public t1 As Integer
Sub f(Of t, t)()
End Sub
End Class
End Class
Class a(Of t)
Inherits BB(Of t)
Class b
Class c(Of t)
End Class
End Class
End Class
Class base(Of T)
Function TEST(Of T)(ByRef X As T)
Return Nothing
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32054: 't1' has the same name as a type parameter.
Public t1 As Integer
~~
BC40048: Type parameter 't' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Sub f(Of t, t)()
~
BC32049: Type parameter already declared with name 't'.
Sub f(Of t, t)()
~
BC40048: Type parameter 't' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Class c(Of t)
~
BC40048: Type parameter 'T' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.
Function TEST(Of T)(ByRef X As T)
~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(527182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527182")>
Public Sub DuplicatedNameWithDifferentCases()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AAA">
<file name="a.vb"><![CDATA[
Module Module1
Dim S1 As String
Dim s1 As String
Dim S1 As Integer
Function MyFunc() As Integer
Return 0
End Function
Function MYFUNC() As Integer
Return 0
End Function
Sub Main()
End Sub
End Module
Namespace NS
Partial Public Class AAA
Public BBB As Integer
Friend BBb As Integer
Sub SSS()
End Sub
End Class
Partial Public Class AaA
Public Structure ST1
Shared CH1, ch1 As Char
End Structure
Structure st1
Shared ch1, ch2 As Char
End Structure
End Class
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Namespace Ns
Partial Public Class Aaa
Private Bbb As Integer
Sub Sss()
End Sub
End Class
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim myMod = DirectCast(globalNS.GetMembers("module1").Single(), NamedTypeSymbol)
' no merge for non-namespace/type members
Dim mem1 = myMod.GetMembers("S1")
Assert.Equal(3, mem1.Length) ' 3
mem1 = myMod.GetMembers("myfunc")
Assert.Equal(2, mem1.Length) ' 2
Dim myNS = DirectCast(globalNS.GetMembers("ns").Single(), NamespaceSymbol)
Dim types = myNS.GetMembers("aaa")
Assert.Equal(1, types.Length)
Dim type1 = DirectCast(types.First(), NamedTypeSymbol)
' no merge for fields
Dim mem2 = type1.GetMembers("bbb")
Assert.Equal(3, mem2.Length) ' 3
Dim mem3 = type1.GetMembers("sss")
Assert.Equal(2, mem3.Length) ' 2
Dim mem4 = type1.GetMembers("St1")
Assert.Equal(1, mem4.Length)
Dim type2 = DirectCast(mem4.First(), NamedTypeSymbol)
' from both St1
Dim mem5 = type2.GetMembers("Ch1")
Assert.Equal(3, mem2.Length) ' 3
Dim errs = compilation.GetDeclarationDiagnostics()
' Native compilers 9 errors
Assert.True(errs.Length > 6, "Contain Decl Errors")
End Sub
<WorkItem(537443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537443")>
<Fact>
Public Sub DuplicatedTypes()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Module Module1
Sub sub1()
Dim element1 = <RootEle>
</RootEle>
End Sub
End Module
'COMPILEERROR: BC30179, "Module1"
Module Module1
Sub sub1()
Dim element1 = <RootEle>
</RootEle>
End Sub
End Module
Namespace GenArityErr001
Public Structure ga001Str2 (Of T As Integer)
Dim i As Integer
End Structure
' BC30179: Name conflict
' COMPILEERROR: BC30179, "ga001Str2"
Public Structure ga001Str2 (Of X As New)
Dim i As Integer
End Structure
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.Assembly.GlobalNamespace
Dim modOfNS = DirectCast(globalNS.GetMembers("Module1").Single(), NamedTypeSymbol)
Dim mem1 = DirectCast(modOfNS.GetMembers().First(), MethodSymbol)
Assert.Equal("sub1", mem1.Name)
Dim ns = DirectCast(globalNS.GetMembers("GenArityErr001").First(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetMembers("ga001Str2").First(), NamedTypeSymbol)
Assert.NotEmpty(type1.GetMembers().AsEnumerable())
End Sub
<WorkItem(537443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537443")>
<Fact>
Public Sub InvalidPartialTypes()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit On
Namespace PartialStruct118
Interface ii
Sub abc()
End Interface
'COMPILEWARNING: BC40046, "teststruct"
Structure teststruct
Implements ii
'COMPILEERROR: BC30269, "abc"
Public Sub abc() Implements ii.abc
End Sub
Public Scen5 As String
'COMPILEERROR: BC30269, "Scen6"
Public Sub Scen6(ByVal x As String)
End Sub
'COMPILEERROR: BC30269, "New"
Public Sub New(ByVal x As String)
End Sub
End Structure
'COMPILEERROR: BC32200, "teststruct"
partial Shadows Structure teststruct
End Structure
'COMPILEERROR: BC30395, "MustInherit"
partial MustInherit Structure teststruct
End Structure
'COMPILEERROR: BC30395, "NotInheritable"
partial NotInheritable Structure teststruct
End Structure
'COMPILEERROR: BC30178, "partial"
partial partial structure teststruct
End Structure
partial Structure teststruct
'COMPILEERROR: BC30260, "Scen5"
Public Scen5 As String
Public Sub Scen6(ByVal x As String)
End Sub
End Structure
partial Structure teststruct
'COMPILEERROR: BC30628, "Inherits Scen7"
Inherits scen7
End Structure
partial Structure teststruct
Implements ii
Public Sub New(ByVal x As String)
End Sub
Public Sub abc() Implements ii.abc
End Sub
End Structure
'COMPILEWARNING: BC40046, "teststruct"
Structure teststruct
Dim a As String
End Structure
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.Assembly.GlobalNamespace
Dim ns = DirectCast(globalNS.GetMembers("PartialStruct118").Single(), NamespaceSymbol)
Dim type1 = DirectCast(ns.GetTypeMembers("teststruct").First(), NamedTypeSymbol)
Assert.Equal("teststruct", type1.Name)
Assert.NotEmpty(type1.GetMembers().AsEnumerable)
End Sub
<WorkItem(537680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537680")>
<Fact>
Public Sub ModuleWithTypeParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Err">
<file name="a.vb"><![CDATA[
Namespace Regression139822
'COMPILEERROR: BC32073, "(of T)"
Module Module1(of T)
End Module
End Namespace
]]></file>
</compilation>)
Dim globalNS = compilation.SourceModule.GlobalNamespace
Dim ns = DirectCast(globalNS.GetMembers("Regression139822").Single(), NamespaceSymbol)
Dim myMod = DirectCast(ns.GetMembers("Module1").SingleOrDefault(), NamedTypeSymbol)
Assert.Equal(0, myMod.TypeParameters.Length)
Assert.Equal(0, myMod.Arity)
End Sub
<Fact>
Public Sub Bug4577()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="Bug4577">
<file name="a.vb"><![CDATA[
Namespace A.B
End Namespace
Namespace A
Class B
End Class
Class B(Of T)
End Class
End Namespace
Class C
Class D
End Class
Public d As Integer
Class E(Of T)
End Class
Public e As Integer
Class D '2
End Class
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC30179: class 'B' and namespace 'B' conflict in namespace 'A'.
Class B
~
BC30260: 'd' is already declared as 'Class D' in this class.
Public d As Integer
~
BC30260: 'e' is already declared as 'Class E(Of T)' in this class.
Public e As Integer
~
BC30179: class 'D' and class 'D' conflict in class 'C'.
Class D '2
~
]]></expected>)
End Sub
<Fact>
Public Sub Bug4054()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug4054">
<file name="a.vb"><![CDATA[
Module Program
Sub Main()
Dim x(0# To 2)
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected><![CDATA[
BC32059: Array lower bounds can be only '0'.
Dim x(0# To 2)
~~
]]></expected>)
End Sub
<WorkItem(537507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537507")>
<Fact>
Public Sub ReportErrorTypeCharacterInTypeNameDeclaration()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ReportErrorTypeCharacterInTypeNameDeclaration">
<file name="a.vb"><![CDATA[
Namespace n1#
Class C1#
End Class
Class c2#(of T)
end class
Enum e1#
dummy
end enum
Structure s1#
End structure
End Namespace
Module Program#
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30468: Type declaration characters are not valid in this context.
Namespace n1#
~~~
BC30468: Type declaration characters are not valid in this context.
Class C1#
~~~
BC30468: Type declaration characters are not valid in this context.
Class c2#(of T)
~~~
BC30468: Type declaration characters are not valid in this context.
Enum e1#
~~~
BC30468: Type declaration characters are not valid in this context.
Structure s1#
~~~
BC30468: Type declaration characters are not valid in this context.
Module Program#
~~~~~~~~
]]></errors>)
End Sub
<WorkItem(537507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537507")>
<Fact>
Public Sub ReportErrorTypeCharacterInTypeName()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ReportErrorTypeCharacterInTypeName">
<file name="a.vb"><![CDATA[
Namespace n1
Class C1#
End Class
Class c2#(of T)
public f1 as c1#
end class
End Namespace
Module Program
Dim x1 as C1#
dim x2 as N1.C1#
dim x3 as n1.c2#(of integer)
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30468: Type declaration characters are not valid in this context.
Class C1#
~~~
BC30468: Type declaration characters are not valid in this context.
Class c2#(of T)
~~~
BC30468: Type declaration characters are not valid in this context.
public f1 as c1#
~~~
BC30002: Type 'C1' is not defined.
Dim x1 as C1#
~~~
BC30468: Type declaration characters are not valid in this context.
Dim x1 as C1#
~~~
BC30468: Type declaration characters are not valid in this context.
dim x2 as N1.C1#
~~~
BC30468: Type declaration characters are not valid in this context.
dim x3 as n1.c2#(of integer)
~~~
]]></errors>)
End Sub
<WorkItem(540895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540895")>
<Fact>
Public Sub BC31538ERR_FriendAssemblyBadAccessOverride2()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ClassLibrary1">
<file name="a.vb"><![CDATA[
Imports System
Public Class A
Protected Friend Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
]]></file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="ConsoleApp">
<file name="c.vb"><![CDATA[
Imports System
Imports ClassLibrary1
MustInherit Class B
Inherits A
Protected Friend Overrides Sub G()
End Sub
End Class
]]></file>
</compilation>, {New VisualBasicCompilationReference(compilation1)})
CompilationUtils.AssertTheseDiagnostics(compilation2, <errors><![CDATA[
BC40056: Namespace or type specified in the Imports 'ClassLibrary1' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.
Imports ClassLibrary1
~~~~~~~~~~~~~
BC31538: Member 'Protected Friend Overrides Sub G()' cannot override member 'Protected Friend Overridable Sub G()' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.
Protected Friend Overrides Sub G()
~
]]></errors>)
End Sub
' Note that the candidate symbols infrastructure on error types is tested heavily in
' the SemanticModel tests. The following tests just make sure the public
' API is working correctly.
Public Sub ErrorTypeCandidateSymbols1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Option Strict On
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers("n").First(), FieldSymbol)
Dim typ = fsym.Type
Assert.Equal(SymbolKind.ErrorType, typ.Kind)
Assert.Equal("B", typ.Name)
Dim errortype = DirectCast(typ, ErrorTypeSymbol)
Assert.Equal(CandidateReason.None, errortype.CandidateReason)
Assert.Equal(0, errortype.CandidateSymbols.Length)
End Sub
<Fact()>
Public Sub ErrorTypeCandidateSymbols2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Option Strict On
Class C
Private Class B
End Class
End Class
Class A
Inherits C
Dim n As B
End Class
]]></file>
</compilation>)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim classB = DirectCast(DirectCast(compilation.GlobalNamespace.GetTypeMembers("C").Single(), NamedTypeSymbol).GetTypeMembers("B").Single, NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers("n").First(), FieldSymbol)
Dim typ = fsym.Type
Assert.Equal(SymbolKind.ErrorType, typ.Kind)
Assert.Equal("B", typ.Name)
Dim errortyp = DirectCast(typ, ErrorTypeSymbol)
Assert.Equal(CandidateReason.Inaccessible, errortyp.CandidateReason)
Assert.Equal(1, errortyp.CandidateSymbols.Length)
Assert.Equal(classB, errortyp.CandidateSymbols(0))
End Sub
<Fact()>
Public Sub ErrorTypeCandidateSymbols3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="ErrorType">
<file name="a.vb"><![CDATA[
Option Strict On
Imports N1, N2
Namespace N1
Class B
End Class
End Namespace
Namespace N2
Class B
End Class
End Namespace
Class A
Dim n As B
End Class
]]></file>
</compilation>)
Dim classA = DirectCast(compilation.GlobalNamespace.GetTypeMembers("A").Single(), NamedTypeSymbol)
Dim classB1 = DirectCast(DirectCast(compilation.GlobalNamespace.GetMembers("N1").Single(), NamespaceSymbol).GetTypeMembers("B").Single, NamedTypeSymbol)
Dim classB2 = DirectCast(DirectCast(compilation.GlobalNamespace.GetMembers("N2").Single(), NamespaceSymbol).GetTypeMembers("B").Single, NamedTypeSymbol)
Dim fsym = DirectCast(classA.GetMembers("n").First(), FieldSymbol)
Dim typ = fsym.Type
Assert.Equal(SymbolKind.ErrorType, typ.Kind)
Assert.Equal("B", typ.Name)
Dim errortyp = DirectCast(typ, ErrorTypeSymbol)
Assert.Equal(CandidateReason.Ambiguous, errortyp.CandidateReason)
Assert.Equal(2, errortyp.CandidateSymbols.Length)
Assert.True((TypeSymbol.Equals(classB1, TryCast(errortyp.CandidateSymbols(0), TypeSymbol), TypeCompareKind.ConsiderEverything) AndAlso
TypeSymbol.Equals(classB2, TryCast(errortyp.CandidateSymbols(1), TypeSymbol), TypeCompareKind.ConsiderEverything)) OrElse
(TypeSymbol.Equals(classB2, TryCast(errortyp.CandidateSymbols(0), TypeSymbol), TypeCompareKind.ConsiderEverything) AndAlso
TypeSymbol.Equals(classB1, TryCast(errortyp.CandidateSymbols(1), TypeSymbol), TypeCompareKind.ConsiderEverything)), "should have B1 and B2 in some order")
End Sub
<Fact()>
Public Sub TypeArgumentOfFriendType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="E">
<file name="a.vb"><![CDATA[
Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleTo("goo")>
Friend Class ImmutableStack(Of T)
End Class
]]></file>
</compilation>)
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation name="goo">
<file name="a.vb"><![CDATA[
Friend Class Scanner
Protected Class ConditionalState
End Class
Protected Class PreprocessorState
Friend ReadOnly _conditionals As ImmutableStack(Of ConditionalState)
End Class
End Class
]]></file>
</compilation>, {New VisualBasicCompilationReference(compilation)})
Assert.Empty(compilation2.GetDiagnostics())
End Sub
<Fact, WorkItem(544071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544071")>
Public Sub ProtectedTypeExposureGeneric()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="E">
<file name="a.vb"><![CDATA[
Friend Class B(Of T)
Protected Enum ENM
None
End Enum
End Class
Class D
Inherits B(Of Integer)
Protected Sub proc(p1 As ENM)
End Sub
Protected Sub proc(p1 As B(Of Long).ENM)
End Sub
End Class
]]></file>
</compilation>)
Dim diags = compilation.GetDiagnostics()
Assert.Empty(diags)
End Sub
<Fact, WorkItem(574771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574771")>
Public Sub Bug574771()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Public Interface vbGI6504Int1(Of X)
End Interface
Public Interface vbGI6504Int2(Of T, U)
Function Fun2(ByVal p1 As T, ByVal t2 As U) As Long
End Interface
Public Interface vbGI6504Int3(Of T)
Inherits vbGI6504Int1(Of T)
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
End Interface
Public Class vbGI6504Cls1(Of X)
Implements vbGI6504Int3(Of X)
Public Function Fun2(ByVal p1 As X, ByVal t2 As X) As Long Implements vbGI6504Int2(Of X, X).Fun2
Return 12000L
End Function
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC32042: Too few type arguments to 'vbGI6504Int2(Of T, U)'.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~~~~~~~~~~~~~~~
BC32093: 'Of' required when specifying type arguments for a generic type or method.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC30002: Type 'O' is not defined.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC30198: ')' expected.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC32055: Interface 'vbGI6504Int3' cannot inherit from a type parameter.
Inherits vbGI6504Int2(O T, T) ' f is removed from Of
~
BC31035: Interface 'vbGI6504Int2(Of X, X)' is not implemented by this class.
Public Function Fun2(ByVal p1 As X, ByVal t2 As X) As Long Implements vbGI6504Int2(Of X, X).Fun2
~~~~~~~~~~~~~~~~~~~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(578723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578723")>
Public Sub Bug578723()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I(Of T)
Sub Goo(Optional x As Integer = Nothing)
End Interface
Class C
Implements I(Of Integer)
Public Sub Goo(Optional x As Integer = 0) Implements (Of Integer).Goo
End Sub
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC30149: Class 'C' must implement 'Sub Goo([x As Integer = 0])' for interface 'I(Of Integer)'.
Implements I(Of Integer)
~~~~~~~~~~~~~
BC30203: Identifier expected.
Public Sub Goo(Optional x As Integer = 0) Implements (Of Integer).Goo
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<WorkItem(783920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/783920")>
<Fact()>
Public Sub Bug783920()
Dim comp1 = CreateCompilationWithMscorlib40(
<compilation name="Bug783920_VB">
<file name="a.vb"><![CDATA[
Public Class MyAttribute1
Inherits System.Attribute
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll)
Dim comp2 = CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Public Class MyAttribute2
Inherits MyAttribute1
End Class
]]></file>
</compilation>, {New VisualBasicCompilationReference(comp1)}, TestOptions.ReleaseDll)
Dim source3 =
<compilation>
<file name="a.vb"><![CDATA[
<MyAttribute2>
Public Class Test
End Class
]]></file>
</compilation>
Dim expected =
<expected><![CDATA[
BC30652: Reference required to assembly 'Bug783920_VB, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'MyAttribute1'. Add one to your project.
<MyAttribute2>
~~~~~~~~~~~~
]]></expected>
Dim comp4 = CreateCompilationWithMscorlib40AndReferences(source3, {comp2.EmitToImageReference()}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(comp4, expected)
Dim comp3 = CreateCompilationWithMscorlib40AndReferences(source3, {New VisualBasicCompilationReference(comp2)}, TestOptions.ReleaseDll)
AssertTheseDiagnostics(comp3, expected)
End Sub
<Fact()>
Public Sub BC30166ERR_ExpectedNewableClass1()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Friend Module AttrRegress006mod
' Need this attribute
<System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)>
Class test
End Class
Sub AttrRegress006()
'COMPILEERROR: BC30166, "Test" EDMAURER no longer giving this error.
Dim c As New test
End Sub
End Module]]></file>
</compilation>)
Dim expectedErrors1 = <errors></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(528709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528709")>
Public Sub Bug528709()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Enum TestEnum
One
One
End Enum
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC31421: 'One' is already declared in this enum.
One
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(529327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529327")>
Public Sub Bug529327()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I1
Property Bar As Integer
Sub Goo()
End Interface
Interface I2
Inherits I1
Property Bar As Integer
Sub Goo()
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: property 'Bar' shadows an overloadable member declared in the base interface 'I1'. If you want to overload the base method, this method must be declared 'Overloads'.
Property Bar As Integer
~~~
BC40003: sub 'Goo' shadows an overloadable member declared in the base interface 'I1'. If you want to overload the base method, this method must be declared 'Overloads'.
Sub Goo()
~~~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(531353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531353")>
Public Sub Bug531353()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class c1
Shared Operator +(ByVal x As c1, ByVal y As c2) As Integer
Return 0
End Operator
End Class
Class c2
Inherits c1
'COMPILEWARNING: BC40003, "+"
Shared Operator +(ByVal x As c1, ByVal y As c2) As Integer
Return 0
End Operator
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40003: operator 'op_Addition' shadows an overloadable member declared in the base class 'c1'. If you want to overload the base method, this method must be declared 'Overloads'.
Shared Operator +(ByVal x As c1, ByVal y As c2) As Integer
~
]]></errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(1068209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068209")>
Public Sub Bug1068209_01()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Interface I1
ReadOnly Property P1 As Integer
Sub get_P2()
Event E1 As System.Action
Sub remove_E2()
End Interface
Interface I3
Inherits I1
Overloads Sub get_P1()
Overloads Property P2 As Integer
Overloads Sub add_E1()
Event E2 As System.Action
End Interface
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40014: sub 'get_P1' conflicts with a member implicitly declared for property 'P1' in the base interface 'I1' and should be declared 'Shadows'.
Overloads Sub get_P1()
~~~~~~
BC40012: property 'P2' implicitly declares 'get_P2', which conflicts with a member in the base interface 'I1', and so the property should be declared 'Shadows'.
Overloads Property P2 As Integer
~~
BC40014: sub 'add_E1' conflicts with a member implicitly declared for event 'E1' in the base interface 'I1' and should be declared 'Shadows'.
Overloads Sub add_E1()
~~~~~~
BC40012: event 'E2' implicitly declares 'remove_E2', which conflicts with a member in the base interface 'I1', and so the event should be declared 'Shadows'.
Event E2 As System.Action
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact, WorkItem(1068209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068209")>
Public Sub Bug1068209_02()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Class I1
ReadOnly Property P1 As Integer
Get
return Nothing
End Get
End Property
Sub get_P2()
End Sub
Event E1 As System.Action
Sub remove_E2()
End Sub
End Class
Class I3
Inherits I1
Overloads Sub get_P1()
End Sub
Overloads ReadOnly Property P2 As Integer
Get
return Nothing
End Get
End Property
Overloads Sub add_E1()
End Sub
Event E2 As System.Action
End Class
]]></file>
</compilation>)
Dim expectedErrors1 = <errors><![CDATA[
BC40014: sub 'get_P1' conflicts with a member implicitly declared for property 'P1' in the base class 'I1' and should be declared 'Shadows'.
Overloads Sub get_P1()
~~~~~~
BC40012: property 'P2' implicitly declares 'get_P2', which conflicts with a member in the base class 'I1', and so the property should be declared 'Shadows'.
Overloads ReadOnly Property P2 As Integer
~~
BC40014: sub 'add_E1' conflicts with a member implicitly declared for event 'E1' in the base class 'I1' and should be declared 'Shadows'.
Overloads Sub add_E1()
~~~~~~
BC40012: event 'E2' implicitly declares 'remove_E2', which conflicts with a member in the base class 'I1', and so the event should be declared 'Shadows'.
Event E2 As System.Action
~~
]]></errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub NoObsoleteDiagnosticsForProjectLevelImports_01()
Dim options = TestOptions.ReleaseDll.WithGlobalImports(GlobalImport.Parse({"GlobEnumsClass"}))
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
<System.Serializable><System.Obsolete()>
Class GlobEnumsClass
Public Enum xEmailMsg
Option1
Option2
End Enum
End Class
Class Account
Property Status() As xEmailMsg
End Class
]]></file>
</compilation>, options:=options)
CompileAndVerify(compilation).VerifyDiagnostics()
End Sub
<Fact>
Public Sub NoObsoleteDiagnosticsForProjectLevelImports_02()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports GlobEnumsClass
<System.Serializable><System.Obsolete()>
Class GlobEnumsClass
Public Enum xEmailMsg
Option1
Option2
End Enum
End Class
Class Account
Property Status() As xEmailMsg
End Class
]]></file>
</compilation>, options:=TestOptions.ReleaseDll)
compilation.AssertTheseDiagnostics(<expected>
BC40008: 'GlobEnumsClass' is obsolete.
Imports GlobEnumsClass
~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MustOverrideInScript()
Dim source = <![CDATA[
Friend MustOverride Function F() As Object
Friend MustOverride ReadOnly Property P
]]>
Dim comp = CreateCompilationWithMscorlib45(
{VisualBasicSyntaxTree.ParseText(source.Value, TestOptions.Script)},
references:={SystemCoreRef})
comp.AssertTheseDiagnostics(<expected>
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride Function F() As Object
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride ReadOnly Property P
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MustOverrideInInteractive()
Dim source = <![CDATA[
Friend MustOverride Function F() As Object
Friend MustOverride ReadOnly Property P
]]>
Dim submission = VisualBasicCompilation.CreateScriptCompilation(
"s0.dll",
syntaxTree:=Parse(source.Value, TestOptions.Script),
references:={MscorlibRef, SystemCoreRef})
submission.AssertTheseDiagnostics(<expected>
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride Function F() As Object
~~~~~~~~~~~~
BC30607: 'NotInheritable' classes cannot have members declared 'MustOverride'.
Friend MustOverride ReadOnly Property P
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsOfATypeToDifferentAssembliesWithoutUsingItShouldNotReportAnError()
Dim forwardingIL = "
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly Forwarding
{
}
.module Forwarding.dll
.assembly extern Destination1
{
}
.assembly extern Destination2
{
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}
.class public auto ansi beforefieldinit TestSpace.ExistingReference
extends [mscorlib]System.Object
{
.field public static literal string Value = ""TEST VALUE""
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void[mscorlib] System.Object::.ctor()
IL_0006: nop
IL_0007: ret
}
}"
Dim ilReference = CompileIL(forwardingIL, prependDefaultHeader:=False)
Dim code =
<compilation>
<file name="a.vb"><![CDATA[
Imports TestSpace
Namespace UserSpace
Public Class Program
Public Shared Sub Main()
System.Console.WriteLine(ExistingReference.Value)
End Sub
End Class
End Namespace
]]></file>
</compilation>
CompileAndVerify(
source:=code,
references:={ilReference},
expectedOutput:="TEST VALUE")
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsOfFullyQualifiedTypeToDifferentAssembliesWhileReferencingItShouldErrorOut()
Dim userCode =
<compilation>
<file name="a.vb"><![CDATA[
Namespace ForwardingNamespace
Public Class Program
Public Shared Sub Main()
Dim obj = New Destination.TestClass()
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim forwardingIL = "
.assembly extern Destination1
{
.ver 1:0:0:0
}
.assembly extern Destination2
{
.ver 1:0:0:0
}
.assembly Forwarder
{
.ver 1:0:0:0
}
.module ForwarderModule.dll
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}"
Dim compilation = CreateCompilationWithCustomILSource(userCode, forwardingIL, appendDefaultHeader:=False)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30002: Type 'Destination.TestClass' is not defined.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsToManyAssembliesShouldJustReportTheFirstTwo()
Dim userCode =
<compilation>
<file name="a.vb"><![CDATA[
Namespace ForwardingNamespace
Public Class Program
Public Shared Sub Main()
Dim obj = New Destination.TestClass()
End Sub
End Class
End Namespace
]]></file>
</compilation>
Dim forwardingIL = "
.assembly Forwarder
{
}
.module ForwarderModule.dll
.assembly extern Destination1 { }
.assembly extern Destination2 { }
.assembly extern Destination3 { }
.assembly extern Destination4 { }
.assembly extern Destination5 { }
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination3
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination4
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination5
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination1
}
.class extern forwarder Destination.TestClass
{
.assembly extern Destination2
}"
Dim compilation = CreateCompilationWithCustomILSource(userCode, forwardingIL, appendDefaultHeader:=False)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30002: Type 'Destination.TestClass' is not defined.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = New Destination.TestClass()
~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub RequiredExternalTypesForAMethodSignatureWillReportErrorsIfForwardedToMultipleAssemblies()
' The scenario Is that assembly A Is calling a method from assembly B. This method has a parameter of a type that lives
' in assembly C. If A Is compiled against B And C, it should compile successfully.
' Now if assembly C Is replaced with assembly C2, that forwards the type to both D1 And D2, it should fail with the appropriate error.
Dim codeC = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim referenceC = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="C").EmitToImageReference()
Dim codeB = "
Imports C
Namespace B
Public Class ClassB
Public Shared Sub MethodB(obj As ClassC)
System.Console.WriteLine(obj.GetHashCode())
End Sub
End Class
End Namespace"
Dim compilationB = CreateCompilationWithMscorlib40(
source:=codeB,
references:={referenceC},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="B")
Dim referenceB = compilationB.EmitToImageReference()
Dim codeA = "
Imports B
Namespace A
Public Class ClassA
Public Sub MethodA()
ClassB.MethodB(Nothing)
End Sub
End Class
End Namespace"
Dim compilation = CreateCompilationWithMscorlib40(
source:=codeA,
references:={referenceB, referenceC},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="A")
compilation.VerifyDiagnostics() ' No Errors
Dim codeC2 = "
.assembly C { }
.module CModule.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder C.ClassC
{
.assembly extern D1
}
.class extern forwarder C.ClassC
{
.assembly extern D2
}"
Dim referenceC2 = CompileIL(codeC2, prependDefaultHeader:=False)
compilation = CreateCompilationWithMscorlib40(
source:=codeA,
references:={referenceB, referenceC2},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="A")
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC37208: Module 'CModule.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
ClassB.MethodB(Nothing)
~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleTypeForwardersToTheSameAssemblyShouldNotResultInMultipleForwardError()
Dim codeC = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim compilationC = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="C")
Dim referenceC = compilationC.EmitToImageReference()
Dim codeB = "
Imports C
Namespace B
Public Class ClassB
Public Shared Function MethodB(obj As ClassC) As String
Return ""obj is "" + If(obj Is Nothing, ""nothing"", obj.ToString())
End Function
End Class
End Namespace"
Dim compilationB = CreateCompilationWithMscorlib40(
source:=codeB,
references:={referenceC},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="B")
Dim referenceB = compilationB.EmitToImageReference()
Dim codeA =
<compilation>
<file name="a.vb"><![CDATA[
Imports B
Namespace A
Public Class ClassA
Public Shared Sub Main()
System.Console.WriteLine(ClassB.MethodB(Nothing))
End Sub
End Class
End Namespace
]]></file>
</compilation>
CompileAndVerify(
source:=codeA,
references:={referenceB, referenceC},
expectedOutput:="obj is nothing")
Dim codeC2 = "
.assembly C
{
.ver 0:0:0:0
}
.module C.dll
.assembly extern D { }
.class extern forwarder C.ClassC
{
.assembly extern D
}
.class extern forwarder C.ClassC
{
.assembly extern D
}"
Dim referenceC2 = CompileIL(codeC2, prependDefaultHeader:=False)
Dim compilation = CreateCompilationWithMscorlib40(codeA, references:={referenceB, referenceC2})
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30652: Reference required to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'ClassC'. Add one to your project.
System.Console.WriteLine(ClassB.MethodB(Nothing))
~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
Dim codeD = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim referenceD = CreateCompilationWithMscorlib40(
source:=codeD,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="D").EmitToImageReference()
CompileAndVerify(
source:=codeA,
references:={referenceB, referenceC2, referenceD},
expectedOutput:="obj is nothing")
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub CompilingModuleWithMultipleForwardersToDifferentAssembliesShouldErrorOut()
Dim ilSource = "
.module ForwarderModule.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D1
}
.class extern forwarder Testspace.TestType
{
.assembly extern D2
}"
Dim ilModule = GetILModuleReference(ilSource, prependDefaultHeader:=False)
Dim compilation = CreateCompilationWithMscorlib40(
source:=String.Empty,
references:={ilModule},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="Forwarder")
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub CompilingModuleWithMultipleForwardersToTheSameAssemblyShouldNotProduceMultipleForwardingErrors()
Dim ilSource = "
.assembly extern D { }
.class extern forwarder Testspace.TestType
{
.assembly extern D
}
.class extern forwarder Testspace.TestType
{
.assembly extern D
}"
Dim ilModule = GetILModuleReference(ilSource, prependDefaultHeader:=False)
Dim compilation = CreateCompilationWithMscorlib40(String.Empty, references:={ilModule}, options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[
BC30652: Reference required to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'TestType'. Add one to your project.
]]></errors>)
Dim dCode = "
Namespace Testspace
Public Class TestType
End Class
End Namespace"
Dim dReference = CreateCompilationWithMscorlib40(
source:=dCode,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="D").EmitToImageReference()
' Now compilation succeeds
CreateCompilationWithMscorlib40(
source:=String.Empty,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references:={ilModule, dReference}).VerifyDiagnostics()
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub LookingUpATypeForwardedTwiceInASourceCompilationReferenceShouldFail()
' This test specifically tests that SourceAssembly symbols also produce this error (by using a CompilationReference instead of the usual PEAssembly symbol)
Dim ilSource = "
.module ForwarderModule.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D1
}
.class extern forwarder Testspace.TestType
{
.assembly extern D2
}"
Dim ilModuleReference = GetILModuleReference(ilSource, prependDefaultHeader:=False)
Dim forwarderCompilation = CreateEmptyCompilation(
source:=String.Empty,
references:={ilModuleReference},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="Forwarder")
Dim vbSource = "
Namespace UserSpace
Public Class UserClass
Public Shared Sub Main()
Dim obj = new Testspace.TestType()
End Sub
End Class
End Namespace"
Dim userCompilation = CreateCompilationWithMscorlib40(
source:=vbSource,
references:={forwarderCompilation.ToMetadataReference()},
assemblyName:="UserAssembly")
CompilationUtils.AssertTheseDiagnostics(userCompilation, <errors><![CDATA[
BC30002: Type 'Testspace.TestType' is not defined.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
BC37208: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub ForwardingErrorsInLaterModulesAlwaysOverwriteOnesInEarlierModules()
Dim module1IL = "
.module module1IL.dll
.assembly extern D1 { }
.assembly extern D2 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D1
}
.class extern forwarder Testspace.TestType
{
.assembly extern D2
}"
Dim module1Reference = GetILModuleReference(module1IL, prependDefaultHeader:=False)
Dim module2IL = "
.module module12L.dll
.assembly extern D3 { }
.assembly extern D4 { }
.class extern forwarder Testspace.TestType
{
.assembly extern D3
}
.class extern forwarder Testspace.TestType
{
.assembly extern D4
}"
Dim module2Reference = GetILModuleReference(module2IL, prependDefaultHeader:=False)
Dim forwarderCompilation = CreateEmptyCompilation(
source:=String.Empty,
references:={module1Reference, module2Reference},
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="Forwarder")
Dim vbSource = "
Namespace UserSpace
Public Class UserClass
Public Shared Sub Main()
Dim obj = new Testspace.TestType()
End Sub
End Class
End Namespace"
Dim userCompilation = CreateCompilationWithMscorlib40(
source:=vbSource,
references:={forwarderCompilation.ToMetadataReference()},
assemblyName:="UserAssembly")
CompilationUtils.AssertTheseDiagnostics(userCompilation, <errors><![CDATA[
BC30002: Type 'Testspace.TestType' is not defined.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
BC37208: Module 'module12L.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
Dim obj = new Testspace.TestType()
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")>
Public Sub MultipleForwardsThatChainResultInTheSameAssemblyShouldStillProduceAnError()
' The scenario Is that assembly A Is calling a method from assembly B. This method has a parameter of a type that lives
' in assembly C. Now if assembly C Is replaced with assembly C2, that forwards the type to both D And E, And D fowards it to E,
' it should fail with the appropriate error.
Dim codeC = "
Namespace C
Public Class ClassC
End Class
End Namespace"
Dim referenceC = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="C").EmitToImageReference()
Dim codeB = "
Imports C
Namespace B
Public Class ClassB
Public Shared Sub MethodB(obj As ClassC)
System.Console.WriteLine(obj.GetHashCode())
End Sub
End Class
End Namespace"
Dim referenceB = CreateCompilationWithMscorlib40(
source:=codeB,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references:={referenceC},
assemblyName:="B").EmitToImageReference()
Dim codeC2 = "
.assembly C { }
.module C.dll
.assembly extern D { }
.assembly extern E { }
.class extern forwarder C.ClassC
{
.assembly extern D
}
.class extern forwarder C.ClassC
{
.assembly extern E
}"
Dim referenceC2 = CompileIL(codeC2, prependDefaultHeader:=False)
Dim codeD = "
.assembly D { }
.assembly extern E { }
.class extern forwarder C.ClassC
{
.assembly extern E
}"
Dim referenceD = CompileIL(codeD, prependDefaultHeader:=False)
Dim referenceE = CreateCompilationWithMscorlib40(
source:=codeC,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
assemblyName:="E").EmitToImageReference()
Dim codeA = "
Imports B
Imports C
Namespace A
Public Class ClassA
Public Sub MethodA(obj As ClassC)
ClassB.MethodB(obj)
End Sub
End Class
End Namespace"
Dim userCompilation = CreateCompilationWithMscorlib40(
source:=codeA,
options:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references:={referenceB, referenceC2, referenceD, referenceE},
assemblyName:="A")
CompilationUtils.AssertTheseDiagnostics(userCompilation, <errors><![CDATA[
BC37208: Module 'C.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
ClassB.MethodB(obj)
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
<WorkItem(52516, "https://github.com/dotnet/roslyn/issues/52516")>
Public Sub ErrorInfo_01()
Dim [error] = New MissingMetadataTypeSymbol.Nested(New UnsupportedMetadataTypeSymbol(), "Test", 0, False)
Dim info = [error].ErrorInfo
Assert.Equal(ERRID.ERR_UnsupportedType1, CType(info.Code, ERRID))
Assert.Null([error].ContainingModule)
Assert.Null([error].ContainingAssembly)
Assert.NotNull([error].ContainingSymbol)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Test/Emit/Emit/EmitMetadataTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class EmitMetadata : EmitMetadataTestBase
{
[Fact]
public void InstantiatedGenerics()
{
string source = @"
public class A<T>
{
public class B : A<T>
{
internal class C : B
{}
protected B y1;
protected A<D>.B y2;
}
public class H<S>
{
public class I : A<T>.H<S>
{}
}
internal A<T> x1;
internal A<D> x2;
}
public class D
{
public class K<T>
{
public class L : K<T>
{}
}
}
namespace NS1
{
class E : D
{}
}
class F : A<D>
{}
class G : A<NS1.E>.B
{}
class J : A<D>.H<D>
{}
public class M
{}
public class N : D.K<M>
{}
";
CompileAndVerify(source, symbolValidator: module =>
{
var dump = DumpTypeInfo(module).ToString();
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
<Global>
<type name=""<Module>"" />
<type name=""A"" Of=""T"" base=""System.Object"">
<field name=""x1"" type=""A<T>"" />
<field name=""x2"" type=""A<D>"" />
<type name=""B"" base=""A<T>"">
<field name=""y1"" type=""A<T>.B"" />
<field name=""y2"" type=""A<D>.B"" />
<type name=""C"" base=""A<T>.B"" />
</type>
<type name=""H"" Of=""S"" base=""System.Object"">
<type name=""I"" base=""A<T>.H<S>"" />
</type>
</type>
<type name=""D"" base=""System.Object"">
<type name=""K"" Of=""T"" base=""System.Object"">
<type name=""L"" base=""D.K<T>"" />
</type>
</type>
<type name=""F"" base=""A<D>"" />
<type name=""G"" base=""A<NS1.E>.B"" />
<type name=""J"" base=""A<D>.H<D>"" />
<type name=""M"" base=""System.Object"" />
<type name=""N"" base=""D.K<M>"" />
<NS1>
<type name=""E"" base=""D"" />
</NS1>
</Global>
", dump);
}, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void StringArrays()
{
string source = @"
public class D
{
public D()
{}
public static void Main()
{
System.Console.WriteLine(65536);
arrayField = new string[] {""string1"", ""string2""};
System.Console.WriteLine(arrayField[1]);
System.Console.WriteLine(arrayField[0]);
}
static string[] arrayField;
}
";
CompileAndVerify(source, expectedOutput: @"
65536
string2
string1
"
);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void FieldRVA()
{
string source = @"
public class D
{
public D()
{}
public static void Main()
{
byte[] a = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.Console.WriteLine(a[0]);
System.Console.WriteLine(a[8]);
}
}
";
CompileAndVerify(source, expectedOutput: @"
1
9
"
);
}
[Fact]
public void AssemblyRefs1()
{
var metadataTestLib1 = TestReferences.SymbolsTests.MDTestLib1;
var metadataTestLib2 = TestReferences.SymbolsTests.MDTestLib2;
string source = @"
public class Test : C107
{
}
";
CompileAndVerifyWithMscorlib40(source, new[] { metadataTestLib1, metadataTestLib2 }, assemblyValidator: (assembly) =>
{
var refs = assembly.Modules[0].ReferencedAssemblies.OrderBy(r => r.Name).ToArray();
Assert.Equal(2, refs.Length);
Assert.Equal("MDTestLib1", refs[0].Name, StringComparer.OrdinalIgnoreCase);
Assert.Equal("mscorlib", refs[1].Name, StringComparer.OrdinalIgnoreCase);
});
}
[Fact]
public void AssemblyRefs2()
{
string sources = @"
public class Test : Class2
{
}
";
CompileAndVerifyWithMscorlib40(sources, new[] { TestReferences.SymbolsTests.MultiModule.Assembly }, assemblyValidator: (assembly) =>
{
var refs2 = assembly.Modules[0].ReferencedAssemblies.Select(r => r.Name);
Assert.Equal(2, refs2.Count());
Assert.Contains("MultiModule", refs2, StringComparer.OrdinalIgnoreCase);
Assert.Contains("mscorlib", refs2, StringComparer.OrdinalIgnoreCase);
var peFileReader = assembly.GetMetadataReader();
Assert.Equal(0, peFileReader.GetTableRowCount(TableIndex.File));
Assert.Equal(0, peFileReader.GetTableRowCount(TableIndex.ModuleRef));
});
}
[WorkItem(687434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687434")]
[Fact()]
public void Bug687434()
{
CompileAndVerify(
"public class C { }",
verify: Verification.Fails,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.NetModule));
}
[Fact, WorkItem(529006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529006")]
public void AddModule()
{
var netModule1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(filePath: Path.GetFullPath("netModule1.netmodule"));
var netModule2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2).GetReference(filePath: Path.GetFullPath("netModule2.netmodule"));
string source = @"
public class Test : Class1
{
}
";
// modules not supported in ref emit
CompileAndVerify(source, new[] { netModule1, netModule2 }, assemblyValidator: (assembly) =>
{
Assert.Equal(3, assembly.Modules.Length);
var reader = assembly.GetMetadataReader();
Assert.Equal(2, reader.GetTableRowCount(TableIndex.File));
var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1));
var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2));
Assert.Equal("netModule1.netmodule", reader.GetString(file1.Name));
Assert.Equal("netModule2.netmodule", reader.GetString(file2.Name));
Assert.False(file1.HashValue.IsNil);
Assert.False(file2.HashValue.IsNil);
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef));
var moduleRefName = reader.GetModuleReference(MetadataTokens.ModuleReferenceHandle(1)).Name;
Assert.Equal("netModule1.netmodule", reader.GetString(moduleRefName));
var actual = from h in reader.ExportedTypes
let et = reader.GetExportedType(h)
select $"{reader.GetString(et.NamespaceDefinition)}.{reader.GetString(et.Name)} 0x{MetadataTokens.GetToken(et.Implementation):X8} ({et.Implementation.Kind}) 0x{(int)et.Attributes:X4}";
AssertEx.Equal(new[]
{
".Class1 0x26000001 (AssemblyFile) 0x0001",
".Class3 0x27000001 (ExportedType) 0x0002",
"NS1.Class4 0x26000001 (AssemblyFile) 0x0001",
".Class7 0x27000003 (ExportedType) 0x0002",
".Class2 0x26000002 (AssemblyFile) 0x0001"
}, actual);
});
}
[Fact]
public void ImplementingAnInterface()
{
string source = @"
public interface I1
{}
public class A : I1
{
}
public interface I2
{
void M2();
}
public interface I3
{
void M3();
}
abstract public class B : I2, I3
{
public abstract void M2();
public abstract void M3();
}
";
CompileAndVerify(source, symbolValidator: module =>
{
var classA = module.GlobalNamespace.GetMember<NamedTypeSymbol>("A");
var classB = module.GlobalNamespace.GetMember<NamedTypeSymbol>("B");
var i1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I1");
var i2 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I2");
var i3 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I3");
Assert.Equal(TypeKind.Interface, i1.TypeKind);
Assert.Equal(TypeKind.Interface, i2.TypeKind);
Assert.Equal(TypeKind.Interface, i3.TypeKind);
Assert.Equal(TypeKind.Class, classA.TypeKind);
Assert.Equal(TypeKind.Class, classB.TypeKind);
Assert.Same(i1, classA.Interfaces().Single());
var interfaces = classB.Interfaces();
Assert.Same(i2, interfaces[0]);
Assert.Same(i3, interfaces[1]);
Assert.Equal(1, i2.GetMembers("M2").Length);
Assert.Equal(1, i3.GetMembers("M3").Length);
});
}
[Fact]
public void InterfaceOrder()
{
string source = @"
interface I1 : I2, I5 { }
interface I2 : I3, I4 { }
interface I3 { }
interface I4 { }
interface I5 : I6, I7 { }
interface I6 { }
interface I7 { }
class C : I1 { }
";
CompileAndVerify(source, symbolValidator: module =>
{
var i1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I1");
var i2 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I2");
var i3 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I3");
var i4 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I4");
var i5 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I5");
var i6 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I6");
var i7 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I7");
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
// Order is important - should be pre-order depth-first with declaration order at each level
Assert.True(i1.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i2, i3, i4, i5, i6, i7)));
Assert.True(i2.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i3, i4)));
Assert.False(i3.Interfaces().Any());
Assert.False(i4.Interfaces().Any());
Assert.True(i5.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i6, i7)));
Assert.False(i6.Interfaces().Any());
Assert.False(i7.Interfaces().Any());
Assert.True(c.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i1, i2, i3, i4, i5, i6, i7)));
});
}
[Fact]
public void ExplicitGenericInterfaceImplementation()
{
CompileAndVerify(@"
class S
{
class C<T>
{
public interface I
{
void m(T x);
}
}
abstract public class D : C<int>.I
{
void C<int>.I.m(int x)
{
}
}
}
");
}
[Fact]
public void TypeWithAbstractMethod()
{
string source = @"
abstract public class A
{
public abstract A[] M1(ref System.Array p1);
public abstract A[,] M2(System.Boolean p2);
public abstract A[,,] M3(System.Char p3);
public abstract void M4(System.SByte p4,
System.Single p5,
System.Double p6,
System.Int16 p7,
System.Int32 p8,
System.Int64 p9,
System.IntPtr p10,
System.String p11,
System.Byte p12,
System.UInt16 p13,
System.UInt32 p14,
System.UInt64 p15,
System.UIntPtr p16);
public abstract void M5<T, S>(T p17, S p18);
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll, symbolValidator: module =>
{
var classA = module.GlobalNamespace.GetTypeMembers("A").Single();
var m1 = classA.GetMembers("M1").OfType<MethodSymbol>().Single();
var m2 = classA.GetMembers("M2").OfType<MethodSymbol>().Single();
var m3 = classA.GetMembers("M3").OfType<MethodSymbol>().Single();
var m4 = classA.GetMembers("M4").OfType<MethodSymbol>().Single();
var m5 = classA.GetMembers("M5").OfType<MethodSymbol>().Single();
var method1Ret = (ArrayTypeSymbol)m1.ReturnType;
var method2Ret = (ArrayTypeSymbol)m2.ReturnType;
var method3Ret = (ArrayTypeSymbol)m3.ReturnType;
Assert.True(method1Ret.IsSZArray);
Assert.Same(classA, method1Ret.ElementType);
Assert.Equal(2, method2Ret.Rank);
Assert.Same(classA, method2Ret.ElementType);
Assert.Equal(3, method3Ret.Rank);
Assert.Same(classA, method3Ret.ElementType);
Assert.True(classA.IsAbstract);
Assert.Equal(Accessibility.Public, classA.DeclaredAccessibility);
var parameter1 = m1.Parameters.Single();
var parameter1Type = parameter1.Type;
Assert.Equal(RefKind.Ref, parameter1.RefKind);
Assert.Same(module.GetCorLibType(SpecialType.System_Array), parameter1Type);
Assert.Same(module.GetCorLibType(SpecialType.System_Boolean), m2.Parameters.Single().Type);
Assert.Same(module.GetCorLibType(SpecialType.System_Char), m3.Parameters.Single().Type);
var method4ParamTypes = m4.Parameters.Select(p => p.Type).ToArray();
Assert.Same(module.GetCorLibType(SpecialType.System_Void), m4.ReturnType);
Assert.Same(module.GetCorLibType(SpecialType.System_SByte), method4ParamTypes[0]);
Assert.Same(module.GetCorLibType(SpecialType.System_Single), method4ParamTypes[1]);
Assert.Same(module.GetCorLibType(SpecialType.System_Double), method4ParamTypes[2]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int16), method4ParamTypes[3]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int32), method4ParamTypes[4]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int64), method4ParamTypes[5]);
Assert.Same(module.GetCorLibType(SpecialType.System_IntPtr), method4ParamTypes[6]);
Assert.Same(module.GetCorLibType(SpecialType.System_String), method4ParamTypes[7]);
Assert.Same(module.GetCorLibType(SpecialType.System_Byte), method4ParamTypes[8]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt16), method4ParamTypes[9]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt32), method4ParamTypes[10]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt64), method4ParamTypes[11]);
Assert.Same(module.GetCorLibType(SpecialType.System_UIntPtr), method4ParamTypes[12]);
Assert.True(m5.IsGenericMethod);
Assert.Same(m5.TypeParameters[0], m5.Parameters[0].Type);
Assert.Same(m5.TypeParameters[1], m5.Parameters[1].Type);
Assert.Equal(6, ((PEModuleSymbol)module).Module.GetMetadataReader().TypeReferences.Count);
});
}
[Fact]
public void Types()
{
string source = @"
sealed internal class B
{}
static class C
{
public class D{}
internal class E{}
protected class F{}
private class G{}
protected internal class H{}
class K{}
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classB = module.GlobalNamespace.GetTypeMembers("B").Single();
Assert.True(classB.IsSealed);
Assert.Equal(Accessibility.Internal, classB.DeclaredAccessibility);
var classC = module.GlobalNamespace.GetTypeMembers("C").Single();
Assert.True(classC.IsStatic);
Assert.Equal(Accessibility.Internal, classC.DeclaredAccessibility);
var classD = classC.GetTypeMembers("D").Single();
var classE = classC.GetTypeMembers("E").Single();
var classF = classC.GetTypeMembers("F").Single();
var classH = classC.GetTypeMembers("H").Single();
Assert.Equal(Accessibility.Public, classD.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, classE.DeclaredAccessibility);
Assert.Equal(Accessibility.Protected, classF.DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedOrInternal, classH.DeclaredAccessibility);
if (isFromSource)
{
var classG = classC.GetTypeMembers("G").Single();
var classK = classC.GetTypeMembers("K").Single();
Assert.Equal(Accessibility.Private, classG.DeclaredAccessibility);
Assert.Equal(Accessibility.Private, classK.DeclaredAccessibility);
}
var peModuleSymbol = module as PEModuleSymbol;
if (peModuleSymbol != null)
{
Assert.Equal(5, peModuleSymbol.Module.GetMetadataReader().TypeReferences.Count);
}
};
CompileAndVerify(source, options: TestOptions.ReleaseDll, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void Fields()
{
string source = @"
public class A
{
public int F1;
internal volatile int F2;
protected internal string F3;
protected float F4;
private double F5;
char F6;
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classA = module.GlobalNamespace.GetTypeMembers("A").Single();
var f1 = classA.GetMembers("F1").OfType<FieldSymbol>().Single();
var f2 = classA.GetMembers("F2").OfType<FieldSymbol>().Single();
var f3 = classA.GetMembers("F3").OfType<FieldSymbol>().Single();
var f4 = classA.GetMembers("F4").OfType<FieldSymbol>().Single();
Assert.False(f1.IsVolatile);
Assert.Equal(0, f1.TypeWithAnnotations.CustomModifiers.Length);
Assert.True(f2.IsVolatile);
Assert.Equal(1, f2.TypeWithAnnotations.CustomModifiers.Length);
CustomModifier mod = f2.TypeWithAnnotations.CustomModifiers[0];
Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, f2.DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedOrInternal, f3.DeclaredAccessibility);
Assert.Equal(Accessibility.Protected, f4.DeclaredAccessibility);
if (isFromSource)
{
var f5 = classA.GetMembers("F5").OfType<FieldSymbol>().Single();
var f6 = classA.GetMembers("F6").OfType<FieldSymbol>().Single();
Assert.Equal(Accessibility.Private, f5.DeclaredAccessibility);
Assert.Equal(Accessibility.Private, f6.DeclaredAccessibility);
}
Assert.False(mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsVolatile", mod.Modifier.ToTestDisplayString());
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void Constructors()
{
string source =
@"namespace N
{
abstract class C
{
static C() {}
protected C() {}
}
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("N.C");
var ctor = (MethodSymbol)type.GetMembers(".ctor").SingleOrDefault();
var cctor = (MethodSymbol)type.GetMembers(".cctor").SingleOrDefault();
Assert.NotNull(ctor);
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name);
Assert.Equal(MethodKind.Constructor, ctor.MethodKind);
Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility);
Assert.True(ctor.IsDefinition);
Assert.False(ctor.IsStatic);
Assert.False(ctor.IsAbstract);
Assert.False(ctor.IsSealed);
Assert.False(ctor.IsVirtual);
Assert.False(ctor.IsOverride);
Assert.False(ctor.IsGenericMethod);
Assert.False(ctor.IsExtensionMethod);
Assert.True(ctor.ReturnsVoid);
Assert.False(ctor.IsVararg);
// Bug - 2067
Assert.Equal("N.C." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString());
Assert.Equal(0, ctor.TypeParameters.Length);
Assert.Equal("Void", ctor.ReturnTypeWithAnnotations.Type.Name);
if (isFromSource)
{
Assert.NotNull(cctor);
Assert.Equal(WellKnownMemberNames.StaticConstructorName, cctor.Name);
Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind);
Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility);
Assert.True(cctor.IsDefinition);
Assert.True(cctor.IsStatic);
Assert.False(cctor.IsAbstract);
Assert.False(cctor.IsSealed);
Assert.False(cctor.IsVirtual);
Assert.False(cctor.IsOverride);
Assert.False(cctor.IsGenericMethod);
Assert.False(cctor.IsExtensionMethod);
Assert.True(cctor.ReturnsVoid);
Assert.False(cctor.IsVararg);
// Bug - 2067
Assert.Equal("N.C." + WellKnownMemberNames.StaticConstructorName + "()", cctor.ToTestDisplayString());
Assert.Equal(0, cctor.TypeArgumentsWithAnnotations.Length);
Assert.Equal(0, cctor.Parameters.Length);
Assert.Equal("Void", cctor.ReturnTypeWithAnnotations.Type.Name);
}
else
{
Assert.Null(cctor);
}
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void ConstantFields()
{
string source =
@"class C
{
private const int I = -1;
internal const int J = I;
protected internal const object O = null;
public const string S = ""string"";
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
if (isFromSource)
{
CheckConstantField(type, "I", Accessibility.Private, SpecialType.System_Int32, -1);
}
CheckConstantField(type, "J", Accessibility.Internal, SpecialType.System_Int32, -1);
CheckConstantField(type, "O", Accessibility.ProtectedOrInternal, SpecialType.System_Object, null);
CheckConstantField(type, "S", Accessibility.Public, SpecialType.System_String, "string");
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
private void CheckConstantField(NamedTypeSymbol type, string name, Accessibility declaredAccessibility, SpecialType fieldType, object value)
{
var field = type.GetMembers(name).SingleOrDefault() as FieldSymbol;
Assert.NotNull(field);
Assert.True(field.IsStatic);
Assert.True(field.IsConst);
Assert.Equal(field.DeclaredAccessibility, declaredAccessibility);
Assert.Equal(field.Type.SpecialType, fieldType);
Assert.Equal(field.ConstantValue, value);
}
//the test for not importing internal members is elsewhere
[Fact]
public void DoNotImportPrivateMembers()
{
string source =
@"namespace Namespace
{
public class Public { }
internal class Internal { }
}
class Types
{
public class Public { }
internal class Internal { }
protected class Protected { }
protected internal class ProtectedInternal { }
private class Private { }
}
class Fields
{
public object Public = null;
internal object Internal = null;
protected object Protected = null;
protected internal object ProtectedInternal = null;
private object Private = null;
}
class Methods
{
public void Public() { }
internal void Internal() { }
protected void Protected() { }
protected internal void ProtectedInternal() { }
private void Private() { }
}
class Properties
{
public object Public { get; set; }
internal object Internal { get; set; }
protected object Protected { get; set; }
protected internal object ProtectedInternal { get; set; }
private object Private { get; set; }
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var nmspace = module.GlobalNamespace.GetMember<NamespaceSymbol>("Namespace");
Assert.NotNull(nmspace.GetTypeMembers("Public").SingleOrDefault());
Assert.NotNull(nmspace.GetTypeMembers("Internal").SingleOrDefault());
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Types").Single(), isFromSource, true);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource, false);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource, false);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource, false);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
private void CheckPrivateMembers(NamedTypeSymbol type, bool isFromSource, bool importPrivates)
{
Symbol member;
member = type.GetMembers("Public").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Internal").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Protected").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("ProtectedInternal").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Private").SingleOrDefault();
if (isFromSource || importPrivates)
{
Assert.NotNull(member);
}
else
{
Assert.Null(member);
}
}
[Fact]
public void GenericBaseTypeResolution()
{
string source =
@"class Base<T, U>
{
}
class Derived<T, U> : Base<T, U>
{
}";
Action<ModuleSymbol> validator = module =>
{
var derivedType = module.GlobalNamespace.GetTypeMembers("Derived").Single();
Assert.Equal(2, derivedType.Arity);
var baseType = derivedType.BaseType();
Assert.Equal("Base", baseType.Name);
Assert.Equal(2, baseType.Arity);
Assert.Equal(derivedType.BaseType(), baseType);
Assert.Same(baseType.TypeArguments()[0], derivedType.TypeParameters[0]);
Assert.Same(baseType.TypeArguments()[1], derivedType.TypeParameters[1]);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void ImportExplicitImplementations()
{
string source =
@"interface I
{
void Method();
object Property { get; set; }
}
class C : I
{
void I.Method() { }
object I.Property { get; set; }
}";
Action<ModuleSymbol> validator = module =>
{
// Interface
var type = module.GlobalNamespace.GetTypeMembers("I").Single();
var method = (MethodSymbol)type.GetMembers("Method").Single();
Assert.NotNull(method);
var property = (PropertySymbol)type.GetMembers("Property").Single();
Assert.NotNull(property.GetMethod);
Assert.NotNull(property.SetMethod);
// Implementation
type = module.GlobalNamespace.GetTypeMembers("C").Single();
method = (MethodSymbol)type.GetMembers("I.Method").Single();
Assert.NotNull(method);
property = (PropertySymbol)type.GetMembers("I.Property").Single();
Assert.NotNull(property.GetMethod);
Assert.NotNull(property.SetMethod);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void Properties()
{
string source =
@"public class C
{
public int P1 { get { return 0; } set { } }
internal int P2 { get { return 0; } }
protected internal int P3 { get { return 0; } }
protected int P4 { get { return 0; } }
private int P5 { set { } }
int P6 { get { return 0; } }
public int P7 { private get { return 0; } set { } }
internal int P8 { get { return 0; } private set { } }
protected int P9 { get { return 0; } private set { } }
protected internal int P10 { protected get { return 0; } set { } }
protected internal int P11 { internal get { return 0; } set { } }
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
var members = type.GetMembers();
// Ensure member names are unique.
var memberNames = members.Select(member => member.Name).Distinct().ToList();
Assert.Equal(memberNames.Count, members.Length);
var c = members.First(member => member.Name == ".ctor");
Assert.NotNull(c);
var p1 = (PropertySymbol)members.First(member => member.Name == "P1");
var p2 = (PropertySymbol)members.First(member => member.Name == "P2");
var p3 = (PropertySymbol)members.First(member => member.Name == "P3");
var p4 = (PropertySymbol)members.First(member => member.Name == "P4");
var p7 = (PropertySymbol)members.First(member => member.Name == "P7");
var p8 = (PropertySymbol)members.First(member => member.Name == "P8");
var p9 = (PropertySymbol)members.First(member => member.Name == "P9");
var p10 = (PropertySymbol)members.First(member => member.Name == "P10");
var p11 = (PropertySymbol)members.First(member => member.Name == "P11");
var privateOrNotApplicable = isFromSource ? Accessibility.Private : Accessibility.NotApplicable;
CheckPropertyAccessibility(p1, Accessibility.Public, Accessibility.Public, Accessibility.Public);
CheckPropertyAccessibility(p2, Accessibility.Internal, Accessibility.Internal, Accessibility.NotApplicable);
CheckPropertyAccessibility(p3, Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal, Accessibility.NotApplicable);
CheckPropertyAccessibility(p4, Accessibility.Protected, Accessibility.Protected, Accessibility.NotApplicable);
CheckPropertyAccessibility(p7, Accessibility.Public, privateOrNotApplicable, Accessibility.Public);
CheckPropertyAccessibility(p8, Accessibility.Internal, Accessibility.Internal, privateOrNotApplicable);
CheckPropertyAccessibility(p9, Accessibility.Protected, Accessibility.Protected, privateOrNotApplicable);
CheckPropertyAccessibility(p10, Accessibility.ProtectedOrInternal, Accessibility.Protected, Accessibility.ProtectedOrInternal);
CheckPropertyAccessibility(p11, Accessibility.ProtectedOrInternal, Accessibility.Internal, Accessibility.ProtectedOrInternal);
if (isFromSource)
{
var p5 = (PropertySymbol)members.First(member => member.Name == "P5");
var p6 = (PropertySymbol)members.First(member => member.Name == "P6");
CheckPropertyAccessibility(p5, Accessibility.Private, Accessibility.NotApplicable, Accessibility.Private);
CheckPropertyAccessibility(p6, Accessibility.Private, Accessibility.Private, Accessibility.NotApplicable);
}
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void SetGetOnlyAutopropsInConstructors()
{
var comp = CreateCompilationWithMscorlib45(@"using System;
class C
{
public int P1 { get; }
public static int P2 { get; }
public C()
{
P1 = 10;
}
static C()
{
P2 = 11;
}
static void Main()
{
Console.Write(C.P2);
var c = new C();
Console.Write(c.P1);
}
}", options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "1110");
}
[Fact]
public void AutoPropInitializersClass()
{
var comp = CreateCompilation(@"using System;
class C
{
public int P { get; set; } = 1;
public string Q { get; set; } = ""test"";
public decimal R { get; } = 300;
public static char S { get; } = 'S';
static void Main()
{
var c = new C();
Console.Write(c.P);
Console.Write(c.Q);
Console.Write(c.R);
Console.Write(C.S);
}
}", parseOptions: TestOptions.Regular,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var p = type.GetMember<SourcePropertySymbol>("P");
var pBack = p.BackingField;
Assert.False(pBack.IsReadOnly);
Assert.False(pBack.IsStatic);
Assert.Equal(SpecialType.System_Int32, pBack.Type.SpecialType);
var q = type.GetMember<SourcePropertySymbol>("Q");
var qBack = q.BackingField;
Assert.False(qBack.IsReadOnly);
Assert.False(qBack.IsStatic);
Assert.Equal(SpecialType.System_String, qBack.Type.SpecialType);
var r = type.GetMember<SourcePropertySymbol>("R");
var rBack = r.BackingField;
Assert.True(rBack.IsReadOnly);
Assert.False(rBack.IsStatic);
Assert.Equal(SpecialType.System_Decimal, rBack.Type.SpecialType);
var s = type.GetMember<SourcePropertySymbol>("S");
var sBack = s.BackingField;
Assert.True(sBack.IsReadOnly);
Assert.True(sBack.IsStatic);
Assert.Equal(SpecialType.System_Char, sBack.Type.SpecialType);
};
CompileAndVerify(
comp,
sourceSymbolValidator: validator,
expectedOutput: "1test300S");
}
[Fact]
public void AutoPropInitializersStruct()
{
var comp = CreateCompilation(@"
using System;
struct S
{
public readonly int P;
public string Q { get; }
public decimal R { get; }
public static char T { get; } = 'T';
public S(int p)
{
P = p;
Q = ""test"";
R = 300;
}
static void Main()
{
var s = new S(1);
Console.Write(s.P);
Console.Write(s.Q);
Console.Write(s.R);
Console.Write(S.T);
s = new S();
Console.Write(s.P);
Console.Write(s.Q ?? ""null"");
Console.Write(s.R);
Console.Write(S.T);
}
}", parseOptions: TestOptions.Regular,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("S");
var p = type.GetMember<SourceMemberFieldSymbol>("P");
Assert.False(p.HasInitializer);
Assert.True(p.IsReadOnly);
Assert.False(p.IsStatic);
Assert.Equal(SpecialType.System_Int32, p.Type.SpecialType);
var q = type.GetMember<SourcePropertySymbol>("Q");
var qBack = q.BackingField;
Assert.True(qBack.IsReadOnly);
Assert.False(qBack.IsStatic);
Assert.Equal(SpecialType.System_String, qBack.Type.SpecialType);
var r = type.GetMember<SourcePropertySymbol>("R");
var rBack = r.BackingField;
Assert.True(rBack.IsReadOnly);
Assert.False(rBack.IsStatic);
Assert.Equal(SpecialType.System_Decimal, rBack.Type.SpecialType);
var s = type.GetMember<SourcePropertySymbol>("T");
var sBack = s.BackingField;
Assert.True(sBack.IsReadOnly);
Assert.True(sBack.IsStatic);
Assert.Equal(SpecialType.System_Char, sBack.Type.SpecialType);
};
CompileAndVerify(
comp,
sourceSymbolValidator: validator,
expectedOutput: "1test300T0null0T");
}
/// <summary>
/// Private accessors of a virtual property should not be virtual.
/// </summary>
[Fact]
public void PrivatePropertyAccessorNotVirtual()
{
string source = @"
class C
{
public virtual int P { get; private set; }
public virtual int Q { get; internal set; }
}
class D : C
{
public override int Q { internal set { } }
}
class E : D
{
public override int Q { get { return 0; } }
}
class F : E
{
public override int P { get { return 0; } }
public override int Q { internal set { } }
}
class Program
{
static void Main()
{
}
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
bool checkValidProperties = (type is PENamedTypeSymbol);
var propertyP = (PropertySymbol)type.GetMembers("P").Single();
if (isFromSource)
{
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.Private);
Assert.False(propertyP.SetMethod.IsVirtual);
Assert.False(propertyP.SetMethod.IsOverride);
}
else
{
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable);
Assert.Null(propertyP.SetMethod);
}
Assert.True(propertyP.GetMethod.IsVirtual);
Assert.False(propertyP.GetMethod.IsOverride);
var propertyQ = (PropertySymbol)type.GetMembers("Q").Single();
CheckPropertyAccessibility(propertyQ, Accessibility.Public, Accessibility.Public, Accessibility.Internal);
Assert.True(propertyQ.GetMethod.IsVirtual);
Assert.False(propertyQ.GetMethod.IsOverride);
Assert.True(propertyQ.SetMethod.IsVirtual);
Assert.False(propertyQ.SetMethod.IsOverride);
Assert.False(propertyQ.IsReadOnly);
Assert.False(propertyQ.IsWriteOnly);
if (checkValidProperties)
{
Assert.False(propertyP.MustCallMethodsDirectly);
Assert.False(propertyQ.MustCallMethodsDirectly);
}
type = module.GlobalNamespace.GetTypeMembers("F").Single();
propertyP = (PropertySymbol)type.GetMembers("P").Single();
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable);
Assert.False(propertyP.GetMethod.IsVirtual);
Assert.True(propertyP.GetMethod.IsOverride);
propertyQ = (PropertySymbol)type.GetMembers("Q").Single();
// Derived property should be public even though the only
// declared accessor on the derived property is internal.
CheckPropertyAccessibility(propertyQ, Accessibility.Public, Accessibility.NotApplicable, Accessibility.Internal);
Assert.False(propertyQ.SetMethod.IsVirtual);
Assert.True(propertyQ.SetMethod.IsOverride);
Assert.False(propertyQ.IsReadOnly);
Assert.False(propertyQ.IsWriteOnly);
if (checkValidProperties)
{
Assert.False(propertyP.MustCallMethodsDirectly);
Assert.False(propertyQ.MustCallMethodsDirectly);
}
// Overridden property should be E but overridden
// accessor should be D.set_Q.
var overriddenProperty = module.GlobalNamespace.GetTypeMembers("E").Single().GetMembers("Q").Single();
Assert.NotNull(overriddenProperty);
Assert.Same(overriddenProperty, propertyQ.OverriddenProperty);
var overriddenAccessor = module.GlobalNamespace.GetTypeMembers("D").Single().GetMembers("set_Q").Single();
Assert.NotNull(overriddenProperty);
Assert.Same(overriddenAccessor, propertyQ.SetMethod.OverriddenMethod);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void InterfaceProperties()
{
string source = @"
interface I
{
int P { get; set; }
}
public class C : I
{
int I.P { get { return 0; } set { } }
}";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
var members = type.GetMembers();
var ip = (PropertySymbol)members.First(member => member.Name == "I.P");
CheckPropertyAccessibility(ip, Accessibility.Private, Accessibility.Private, Accessibility.Private);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
private static void CheckPropertyAccessibility(PropertySymbol property, Accessibility propertyAccessibility, Accessibility getterAccessibility, Accessibility setterAccessibility)
{
var type = property.TypeWithAnnotations;
Assert.NotEqual(Microsoft.Cci.PrimitiveTypeCode.Void, type.PrimitiveTypeCode);
Assert.Equal(propertyAccessibility, property.DeclaredAccessibility);
CheckPropertyAccessorAccessibility(property, propertyAccessibility, property.GetMethod, getterAccessibility);
CheckPropertyAccessorAccessibility(property, propertyAccessibility, property.SetMethod, setterAccessibility);
}
private static void CheckPropertyAccessorAccessibility(PropertySymbol property, Accessibility propertyAccessibility, MethodSymbol accessor, Accessibility accessorAccessibility)
{
if (accessor == null)
{
Assert.Equal(Accessibility.NotApplicable, accessorAccessibility);
}
else
{
var containingType = property.ContainingType;
Assert.Equal(property, accessor.AssociatedSymbol);
Assert.Equal(containingType, accessor.ContainingType);
Assert.Equal(containingType, accessor.ContainingSymbol);
var method = containingType.GetMembers(accessor.Name).Single();
Assert.Equal(method, accessor);
Assert.Equal(accessorAccessibility, accessor.DeclaredAccessibility);
}
}
// Property/method override should succeed (and should reference
// the correct base method, even if there is a method/property
// with the same name in an intermediate class.
[WorkItem(538720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538720")]
[Fact]
public void TestPropertyOverrideGet()
{
PropertyOverrideGet(@"
class A
{
public virtual int P { get { return 0; } }
}
class B : A
{
public virtual int get_P() { return 0; }
}
class C : B
{
public override int P { get { return 0; } }
}
");
PropertyOverrideGet(@"
class A
{
public virtual int get_P() { return 0; }
}
class B : A
{
public virtual int P { get { return 0; } }
}
class C : B
{
public override int get_P() { return 0; }
}
");
}
private void PropertyOverrideGet(string source)
{
Action<ModuleSymbol> validator = module =>
{
var typeA = module.GlobalNamespace.GetTypeMembers("A").Single();
Assert.NotNull(typeA);
var getMethodA = (MethodSymbol)typeA.GetMembers("get_P").Single();
Assert.NotNull(getMethodA);
Assert.True(getMethodA.IsVirtual);
Assert.False(getMethodA.IsOverride);
var typeC = module.GlobalNamespace.GetTypeMembers("C").Single();
Assert.NotNull(typeC);
var getMethodC = (MethodSymbol)typeC.GetMembers("get_P").Single();
Assert.NotNull(getMethodC);
Assert.False(getMethodC.IsVirtual);
Assert.True(getMethodC.IsOverride);
Assert.Same(getMethodC.OverriddenMethod, getMethodA);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void AutoProperties()
{
string source = @"
class A
{
public int P { get; private set; }
internal int Q { get; set; }
}
class B<T>
{
protected internal T P { get; set; }
}
class C : B<string>
{
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classA = module.GlobalNamespace.GetTypeMember("A");
var p = classA.GetProperty("P");
VerifyAutoProperty(p, isFromSource);
var q = classA.GetProperty("Q");
VerifyAutoProperty(q, isFromSource);
var classC = module.GlobalNamespace.GetTypeMembers("C").Single();
p = classC.BaseType().GetProperty("P");
VerifyAutoProperty(p, isFromSource);
Assert.Equal(SpecialType.System_String, p.Type.SpecialType);
Assert.Equal(p.GetMethod.AssociatedSymbol, p);
};
CompileAndVerify(
source,
sourceSymbolValidator: validator(true),
symbolValidator: validator(false),
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
}
private static void VerifyAutoProperty(PropertySymbol property, bool isFromSource)
{
if (isFromSource)
{
if (property is SourcePropertySymbol sourceProperty)
{
Assert.True(sourceProperty.IsAutoPropertyWithGetAccessor);
}
}
else
{
var backingField = property.ContainingType.GetField(GeneratedNames.MakeBackingFieldName(property.Name));
var attribute = backingField.GetAttributes().Single();
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attribute.AttributeClass.ToTestDisplayString());
Assert.Empty(attribute.AttributeConstructor.Parameters);
}
VerifyAutoPropertyAccessor(property, property.GetMethod);
VerifyAutoPropertyAccessor(property, property.SetMethod);
}
private static void VerifyAutoPropertyAccessor(PropertySymbol property, MethodSymbol accessor)
{
if (accessor != null)
{
var method = property.ContainingType.GetMembers(accessor.Name).Single();
Assert.Equal(method, accessor);
Assert.Equal(accessor.AssociatedSymbol, property);
Assert.False(accessor.IsImplicitlyDeclared, "MethodSymbol.IsImplicitlyDeclared should be false for auto property accessors");
}
}
[Fact]
public void EmptyEnum()
{
string source = "enum E {}";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("E").Single();
CheckEnumType(type, Accessibility.Internal, SpecialType.System_Int32);
Assert.Equal(1, type.GetMembers().Length);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void NonEmptyEnum()
{
string source =
@"enum E : short
{
A,
B = 0x02,
C,
D,
E = B | D,
F = C,
G,
}
";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("E").Single();
CheckEnumType(type, Accessibility.Internal, SpecialType.System_Int16);
Assert.Equal(8, type.GetMembers().Length);
CheckEnumConstant(type, "A", (short)0);
CheckEnumConstant(type, "B", (short)2);
CheckEnumConstant(type, "C", (short)3);
CheckEnumConstant(type, "D", (short)4);
CheckEnumConstant(type, "E", (short)6);
CheckEnumConstant(type, "F", (short)3);
CheckEnumConstant(type, "G", (short)4);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
private void CheckEnumConstant(NamedTypeSymbol type, string name, object value)
{
var field = type.GetMembers(name).SingleOrDefault() as FieldSymbol;
Assert.NotNull(field);
Assert.True(field.IsStatic);
Assert.True(field.IsConst);
// TODO: DeclaredAccessibility should be NotApplicable.
//Assert.Equal(field.DeclaredAccessibility, Accessibility.NotApplicable);
Assert.Equal(field.Type, type);
Assert.Equal(field.ConstantValue, value);
var sourceType = type as SourceNamedTypeSymbol;
if ((object)sourceType != null)
{
var fieldDefinition = (Microsoft.Cci.IFieldDefinition)field.GetCciAdapter();
Assert.False(fieldDefinition.IsSpecialName);
Assert.False(fieldDefinition.IsRuntimeSpecial);
}
}
private void CheckEnumType(NamedTypeSymbol type, Accessibility declaredAccessibility, SpecialType underlyingType)
{
Assert.Equal(SpecialType.System_Enum, type.BaseType().SpecialType);
Assert.Equal(type.EnumUnderlyingType.SpecialType, underlyingType);
Assert.Equal(type.DeclaredAccessibility, declaredAccessibility);
Assert.True(type.IsSealed);
// value__ field should not be exposed from type, even though it is public,
// since we want to prevent source from accessing the field directly.
var field = type.GetMembers(WellKnownMemberNames.EnumBackingFieldName).SingleOrDefault() as FieldSymbol;
Assert.Null(field);
var sourceType = type as SourceNamedTypeSymbol;
if ((object)sourceType != null)
{
field = sourceType.EnumValueField;
Assert.NotNull(field);
Assert.Equal(field.Name, WellKnownMemberNames.EnumBackingFieldName);
Assert.False(field.IsStatic);
Assert.False(field.IsConst);
Assert.False(field.IsReadOnly);
Assert.Equal(Accessibility.Public, field.DeclaredAccessibility); // Dev10: value__ is public
Assert.Equal(field.Type, type.EnumUnderlyingType);
var module = new PEAssemblyBuilder((SourceAssemblySymbol)sourceType.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var typeDefinition = (Microsoft.Cci.ITypeDefinition)type.GetCciAdapter();
var fieldDefinition = typeDefinition.GetFields(context).First();
Assert.Same(fieldDefinition.GetInternalSymbol(), field); // Dev10: value__ field is the first field.
Assert.True(fieldDefinition.IsSpecialName);
Assert.True(fieldDefinition.IsRuntimeSpecial);
context.Diagnostics.Verify();
}
}
[Fact]
public void GenericMethods()
{
string source = @"
public class A
{
public static void Main()
{
System.Console.WriteLine(""GenericMethods"");
//B.Test<int>();
//C<int>.Test<int>();
}
}
public class B
{
public static void Test<T>()
{
System.Console.WriteLine(""Test<T>"");
}
}
public class C<T>
{
public static void Test<S>()
{
System.Console.WriteLine(""C<T>.Test<S>"");
}
}
";
CompileAndVerify(source, expectedOutput: "GenericMethods\r\n");
}
[Fact]
public void GenericMethods2()
{
string source = @"
class A
{
public static void Main()
{
TC1 x = new TC1();
System.Console.WriteLine(x.GetType());
TC2<byte> y = new TC2<byte>();
System.Console.WriteLine(y.GetType());
TC3<byte>.TC4 z = new TC3<byte>.TC4();
System.Console.WriteLine(z.GetType());
}
}
class TC1
{
void TM1<T1>()
{
TM1<T1>();
}
void TM2<T2>()
{
TM2<int>();
}
}
class TC2<T3>
{
void TM3<T4>()
{
TM3<T4>();
TM3<T4>();
}
void TM4<T5>()
{
TM4<int>();
TM4<int>();
}
static void TM5<T6>(T6 x)
{
TC2<int>.TM5(x);
}
static void TM6<T7>(T7 x)
{
TC2<int>.TM6(1);
}
void TM9()
{
TM9();
TM9();
}
}
class TC3<T8>
{
public class TC4
{
void TM7<T9>()
{
TM7<T9>();
TM7<int>();
}
static void TM8<T10>(T10 x)
{
TC3<int>.TC4.TM8(x);
TC3<int>.TC4.TM8(1);
}
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput:
@"TC1
TC2`1[System.Byte]
TC3`1+TC4[System.Byte]
");
verifier.VerifyIL("TC1.TM1<T1>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC1.TM1<T1>()""
IL_0006: ret
}
");
verifier.VerifyIL("TC1.TM2<T2>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC1.TM2<int>()""
IL_0006: ret
}
");
verifier.VerifyIL("TC2<T3>.TM3<T4>",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<T3>.TM3<T4>()""
IL_0006: ldarg.0
IL_0007: call ""void TC2<T3>.TM3<T4>()""
IL_000c: ret
}
");
verifier.VerifyIL("TC2<T3>.TM4<T5>",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<T3>.TM4<int>()""
IL_0006: ldarg.0
IL_0007: call ""void TC2<T3>.TM4<int>()""
IL_000c: ret
}
");
verifier.VerifyIL("TC2<T3>.TM5<T6>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<int>.TM5<T6>(T6)""
IL_0006: ret
}
");
verifier.VerifyIL("TC2<T3>.TM6<T7>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void TC2<int>.TM6<int>(int)""
IL_0006: ret
}
");
}
[Fact]
public void Generics3()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
C1<Byte, Byte> x1 = new C1<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte> x2 = new C1<Byte, Byte>.C2<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte> x3 = new C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>.C4<Byte> x4 = new C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>.C4<Byte>();
C1<Byte, Byte>.C5 x5 = new C1<Byte, Byte>.C5();
}
}
class C1<C1T1, C1T2>
{
public class C2<C2T1, C2T2>
{
public class C3<C3T1, C3T2> where C3T2 : C1T1
{
public class C4<C4T1>
{
}
}
public C1<int, C2T2>.C5 V1;
public C1<C2T1, C2T2>.C5 V2;
public C1<int, int>.C5 V3;
public C2<Byte, Byte> V4;
public C1<C1T2, C1T1>.C2<C2T1, C2T2> V5;
public C1<C1T2, C1T1>.C2<C2T2, C2T1> V6;
public C1<C1T2, C1T1>.C2<Byte, int> V7;
public C2<C2T1, C2T2> V8;
public C2<Byte, C2T2> V9;
void Test12(C2<int, int> x)
{
C1<C1T1, C1T2>.C2<Byte, int> y = x.V9;
}
void Test11(C1<int, int>.C2<Byte, Byte> x)
{
C1<int, int>.C2<Byte, Byte> y = x.V8;
}
void Test6(C1<C1T2, C1T1>.C2<C2T1, C2T2> x)
{
C1<C1T1, C1T2>.C2<C2T1, C2T2> y = x.V5;
}
void Test7(C1<C1T2, C1T1>.C2<C2T2, C2T1> x)
{
C1<C1T1, C1T2>.C2<C2T1, C2T2> y = x.V6;
}
void Test8(C1<C1T2, C1T1>.C2<C2T2, C2T1> x)
{
C1<C1T1, C1T2>.C2<Byte, int> y = x.V7;
}
void Test9(C1<int, Byte>.C2<C2T2, C2T1> x)
{
C1<Byte, int>.C2<Byte, int> y = x.V7;
}
void Test10(C1<C1T1, C1T2>.C2<C2T2, C2T1> x)
{
C1<C1T2, C1T1>.C2<Byte, int> y = x.V7;
}
}
public class C5
{
}
void Test1(C2<C1T1, int> x)
{
C1<int, int>.C5 y = x.V1;
}
void Test2(C2<C1T1, C1T2> x)
{
C5 y = x.V2;
}
void Test3(C2<C1T2, C1T1> x)
{
C1<int, int>.C5 y = x.V3;
}
void Test4(C1<int, int>.C2<C1T1, C1T2> x)
{
C1<int, int>.C2<Byte, Byte> y = x.V4;
}
}
";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_UnsupportedOrdering1()
{
CompileAndVerify(@"
public class E
{
public struct N2
{
public N3 n1;
}
public struct N3
{
}
N2 n2;
}
");
}
[Fact]
public void RefEmit_UnsupportedOrdering1_EP()
{
string source = @"
public class E
{
public struct N2
{
public N3 n1;
}
public struct N3
{
}
N2 n2;
public static void Main()
{
System.Console.Write(1234);
}
}";
CompileAndVerify(source, expectedOutput: @"1234");
}
[Fact]
public void RefEmit_UnsupportedOrdering2()
{
CompileAndVerify(@"
class B<T> where T : A {}
class A : B<A> {}
");
}
[Fact]
public void RefEmit_MembersOfOpenGenericType()
{
CompileAndVerify(@"
class C<T>
{
void goo()
{
System.Collections.Generic.Dictionary<int, T> d = new System.Collections.Generic.Dictionary<int, T>();
}
}
");
}
[Fact]
public void RefEmit_ListOfValueTypes()
{
string source = @"
using System.Collections.Generic;
class A
{
struct S { }
List<S> f;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedNestedSelfReference()
{
string source = @"
class A<T>
{
class B {
}
A<int>.B x;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedNestedGenericSelfReference()
{
string source = @"
class A<T>
{
public class B<S> {
public class C<U,V> {
}
}
A<int>.B<double>.C<string, bool> x;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Cycle()
{
string source = @"
public class B : I<C> { }
public class C : I<B> { }
public interface I<T> { }
";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedMemberReference()
{
string source = @"
class A<T>
{
public A()
{
A<int>.method();
int a = A<string>.field;
new A<double>();
}
public static void method()
{
}
public static int field;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_NestedGenericTypeReferences()
{
string source = @"
class A<T>
{
public class H<S>
{
A<T>.H<S> x;
}
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Ordering2()
{
// order:
// E <(value type field) E.C.N2 <(value type field) N3
string source = @"
public class E
{
public class C {
public struct N2
{
public N3 n1;
}
}
C.N2 n2;
}
public struct N3
{
E f;
int g;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Ordering3()
{
string source = @"
using System.Collections.Generic;
public class E
{
public struct N2
{
public List<N3> n1; // E.N2 doesn't depend on E.N3 since List<> isn't a value type
}
public struct N3
{
}
N2 n2;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_IL1()
{
CompileAndVerify(@"
class C
{
public static void Main()
{
int i = 0, j, k = 2147483647;
long l = 0, m = 9200000000000000000L;
int b = -10;
byte c = 200;
float f = 3.14159F;
double d = 2.71828;
string s = ""abcdef"";
bool x = true;
System.Console.WriteLine(i);
System.Console.WriteLine(k);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(f);
System.Console.WriteLine(d);
System.Console.WriteLine(s);
System.Console.WriteLine(x);
}
}
", expectedOutput: @"
0
2147483647
-10
200
3.14159
2.71828
abcdef
True
");
}
[WorkItem(540581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540581")]
[Fact]
public void RefEmit_DependencyGraphAndCachedTypeReferences()
{
var source = @"
using System;
interface I1<T>
{
void Method(T x);
}
interface I2<U>
{
void Method(U x);
}
interface I3<W> : I1<W>, I2<W>
{
void Method(W x);
}
class Implicit2 : I3<string> // Implicit2 depends on I3<string>
{
public void Method(string x) { }
}
class Test
{
public static void Main()
{
I3<string> i = new Implicit2();
}
}
";
// If I3<string> in Main body is resolved first and stored in a cache,
// the fact that Implicit2 depends on I3<string> isn't recorded if we pull
// I3<string> from cache at the beginning of ResolveType method.
CompileAndVerify(source);
}
[Fact]
public void CheckRef()
{
string source = @"
public abstract class C
{
public abstract int M(int x, ref int y, out int z);
}
";
CompileAndVerify(source, symbolValidator: module =>
{
var global = module.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
var m = c.GetMembers("M").Single() as MethodSymbol;
Assert.Equal(RefKind.None, m.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, m.Parameters[1].RefKind);
Assert.Equal(RefKind.Out, m.Parameters[2].RefKind);
});
}
[Fact]
public void OutArgument()
{
string source = @"
class C
{
static void Main() { double d; double.TryParse(null, out d); }
}
";
CompileAndVerify(source);
}
[Fact]
public void CreateInstance()
{
string source = @"
class C
{
static void Main() { System.Activator.CreateInstance<int>(); }
}
";
CompileAndVerify(source);
}
[Fact]
public void DelegateRoundTrip()
{
string source = @"delegate int MyDel(
int x,
// ref int y, // commented out until 4264 is fixed.
// out int z, // commented out until 4264 is fixed.
int w);";
CompileAndVerify(source, symbolValidator: module =>
{
var global = module.GlobalNamespace;
var myDel = global.GetTypeMembers("MyDel", 0).Single() as NamedTypeSymbol;
var invoke = myDel.DelegateInvokeMethod;
var beginInvoke = myDel.GetMembers("BeginInvoke").Single() as MethodSymbol;
Assert.Equal(invoke.Parameters.Length + 2, beginInvoke.Parameters.Length);
Assert.Equal(TypeKind.Interface, beginInvoke.ReturnType.TypeKind);
Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToTestDisplayString());
for (int i = 0; i < invoke.Parameters.Length; i++)
{
Assert.Equal(invoke.Parameters[i].Type, beginInvoke.Parameters[i].Type);
Assert.Equal(invoke.Parameters[i].RefKind, beginInvoke.Parameters[i].RefKind);
}
Assert.Equal("System.AsyncCallback", beginInvoke.Parameters[invoke.Parameters.Length].Type.ToTestDisplayString());
Assert.Equal("System.Object", beginInvoke.Parameters[invoke.Parameters.Length + 1].Type.ToTestDisplayString());
var invokeReturn = invoke.ReturnType;
var endInvoke = myDel.GetMembers("EndInvoke").Single() as MethodSymbol;
var endInvokeReturn = endInvoke.ReturnType;
Assert.Equal(invokeReturn, endInvokeReturn);
int k = 0;
for (int i = 0; i < invoke.Parameters.Length; i++)
{
if (invoke.Parameters[i].RefKind != RefKind.None)
{
Assert.Equal(invoke.Parameters[i].TypeWithAnnotations, endInvoke.Parameters[k].TypeWithAnnotations);
Assert.Equal(invoke.Parameters[i].RefKind, endInvoke.Parameters[k++].RefKind);
}
}
Assert.Equal("System.IAsyncResult", endInvoke.Parameters[k++].Type.ToTestDisplayString());
Assert.Equal(k, endInvoke.Parameters.Length);
});
}
[Fact]
public void StaticClassRoundTrip()
{
string source = @"
public static class C
{
private static string msg = ""Hello"";
private static void Goo()
{
System.Console.WriteLine(msg);
}
public static void Main()
{
Goo();
}
}
";
CompileAndVerify(source,
symbolValidator: module =>
{
var global = module.GlobalNamespace;
var classC = global.GetMember<NamedTypeSymbol>("C");
Assert.True(classC.IsStatic, "Expected C to be static");
Assert.False(classC.IsAbstract, "Expected C to be non-abstract"); //even though it is abstract in metadata
Assert.False(classC.IsSealed, "Expected C to be non-sealed"); //even though it is sealed in metadata
Assert.Equal(0, classC.GetMembers(WellKnownMemberNames.InstanceConstructorName).Length); //since C is static
Assert.Equal(0, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); //since we don't import private members
});
}
[Fact]
public void DoNotImportInternalMembers()
{
string sources =
@"public class Fields
{
public int Public;
internal int Internal;
}
public class Methods
{
public void Public() {}
internal void Internal() {}
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol m) =>
{
CheckInternalMembers(m.GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource);
CheckInternalMembers(m.GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource);
};
CompileAndVerify(sources, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void Issue4695()
{
string source = @"
using System;
class Program
{
sealed class Cache
{
abstract class BucketwiseBase<TArg> where TArg : class
{
internal abstract void Default(TArg arg);
}
class BucketwiseBase<TAccumulator, TArg> : BucketwiseBase<TArg> where TArg : class
{
internal override void Default(TArg arg = null) { }
}
public string GetAll()
{
new BucketwiseBase<object, object>().Default(); // Bad image format thrown here on legacy compiler
return ""OK"";
}
}
static void Main(string[] args)
{
Console.WriteLine(new Cache().GetAll());
}
}
";
CompileAndVerify(source, expectedOutput: "OK");
}
private void CheckInternalMembers(NamedTypeSymbol type, bool isFromSource)
{
Assert.NotNull(type.GetMembers("Public").SingleOrDefault());
var member = type.GetMembers("Internal").SingleOrDefault();
if (isFromSource)
Assert.NotNull(member);
else
Assert.Null(member);
}
[WorkItem(90, "https://github.com/dotnet/roslyn/issues/90")]
[Fact]
public void EmitWithNoResourcesAllPlatforms()
{
var comp = CreateCompilation("class Test { static void Main() { } }");
VerifyEmitWithNoResources(comp, Platform.AnyCpu);
VerifyEmitWithNoResources(comp, Platform.AnyCpu32BitPreferred);
VerifyEmitWithNoResources(comp, Platform.Arm); // broken before fix
VerifyEmitWithNoResources(comp, Platform.Itanium); // broken before fix
VerifyEmitWithNoResources(comp, Platform.X64); // broken before fix
VerifyEmitWithNoResources(comp, Platform.X86);
}
private void VerifyEmitWithNoResources(CSharpCompilation comp, Platform platform)
{
var options = TestOptions.ReleaseExe.WithPlatform(platform);
CompileAndVerify(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_" + platform.ToString()).WithOptions(options));
}
[Fact]
public unsafe void PEHeaders1()
{
var options = EmitOptions.Default.WithFileAlignment(0x2000);
var syntax = SyntaxFactory.ParseSyntaxTree(@"class C {}", TestOptions.Regular);
var peStream = CreateCompilationWithMscorlib40(
syntax,
options: TestOptions.ReleaseDll.WithDeterministic(true),
assemblyName: "46B9C2B2-B7A0-45C5-9EF9-28DDF739FD9E").EmitToStream(options);
peStream.Position = 0;
var peReader = new PEReader(peStream);
var peHeaders = peReader.PEHeaders;
var peHeader = peHeaders.PEHeader;
var coffHeader = peHeaders.CoffHeader;
var corHeader = peHeaders.CorHeader;
Assert.Equal(PEMagic.PE32, peHeader.Magic);
Assert.Equal(0x0000237E, peHeader.AddressOfEntryPoint);
Assert.Equal(0x00002000, peHeader.BaseOfCode);
Assert.Equal(0x00004000, peHeader.BaseOfData);
Assert.Equal(0x00002000, peHeader.SizeOfHeaders);
Assert.Equal(0x00002000, peHeader.SizeOfCode);
Assert.Equal(0x00001000u, peHeader.SizeOfHeapCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfHeapReserve);
Assert.Equal(0x00006000, peHeader.SizeOfImage);
Assert.Equal(0x00002000, peHeader.SizeOfInitializedData);
Assert.Equal(0x00001000u, peHeader.SizeOfStackCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfStackReserve);
Assert.Equal(0, peHeader.SizeOfUninitializedData);
Assert.Equal(Subsystem.WindowsCui, peHeader.Subsystem);
Assert.Equal(DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware, peHeader.DllCharacteristics);
Assert.Equal(0u, peHeader.CheckSum);
Assert.Equal(0x2000, peHeader.FileAlignment);
Assert.Equal(0x10000000u, peHeader.ImageBase);
Assert.Equal(0x2000, peHeader.SectionAlignment);
Assert.Equal(0, peHeader.MajorImageVersion);
Assert.Equal(0, peHeader.MinorImageVersion);
Assert.Equal(0x30, peHeader.MajorLinkerVersion);
Assert.Equal(0, peHeader.MinorLinkerVersion);
Assert.Equal(4, peHeader.MajorOperatingSystemVersion);
Assert.Equal(0, peHeader.MinorOperatingSystemVersion);
Assert.Equal(4, peHeader.MajorSubsystemVersion);
Assert.Equal(0, peHeader.MinorSubsystemVersion);
Assert.Equal(16, peHeader.NumberOfRvaAndSizes);
Assert.Equal(0x2000, peHeader.SizeOfHeaders);
Assert.Equal(0x4000, peHeader.BaseRelocationTableDirectory.RelativeVirtualAddress);
Assert.Equal(0xc, peHeader.BaseRelocationTableDirectory.Size);
Assert.Equal(0, peHeader.BoundImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BoundImportTableDirectory.Size);
Assert.Equal(0, peHeader.CertificateTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CertificateTableDirectory.Size);
Assert.Equal(0, peHeader.CopyrightTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CopyrightTableDirectory.Size);
Assert.Equal(0x2008, peHeader.CorHeaderTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x48, peHeader.CorHeaderTableDirectory.Size);
Assert.Equal(0x2310, peHeader.DebugTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x1C, peHeader.DebugTableDirectory.Size);
Assert.Equal(0, peHeader.ExceptionTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExceptionTableDirectory.Size);
Assert.Equal(0, peHeader.ExportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExportTableDirectory.Size);
Assert.Equal(0x2000, peHeader.ImportAddressTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x8, peHeader.ImportAddressTableDirectory.Size);
Assert.Equal(0x232C, peHeader.ImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x4f, peHeader.ImportTableDirectory.Size);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.Size);
Assert.Equal(0, peHeader.ResourceTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ResourceTableDirectory.Size);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.Size);
int importAddressTableDirectoryOffset;
Assert.True(peHeaders.TryGetDirectoryOffset(peHeader.ImportAddressTableDirectory, out importAddressTableDirectoryOffset));
Assert.Equal(0x2000, importAddressTableDirectoryOffset);
var importAddressTableDirectoryBytes = new byte[peHeader.ImportAddressTableDirectory.Size];
peStream.Position = importAddressTableDirectoryOffset;
peStream.Read(importAddressTableDirectoryBytes, 0, importAddressTableDirectoryBytes.Length);
AssertEx.Equal(new byte[]
{
0x60, 0x23, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}, importAddressTableDirectoryBytes);
int importTableDirectoryOffset;
Assert.True(peHeaders.TryGetDirectoryOffset(peHeader.ImportTableDirectory, out importTableDirectoryOffset));
Assert.Equal(0x232C, importTableDirectoryOffset);
var importTableDirectoryBytes = new byte[peHeader.ImportTableDirectory.Size];
peStream.Position = importTableDirectoryOffset;
peStream.Read(importTableDirectoryBytes, 0, importTableDirectoryBytes.Length);
AssertEx.Equal(new byte[]
{
0x54, 0x23, 0x00, 0x00, // RVA
0x00, 0x00, 0x00, 0x00, // 0
0x00, 0x00, 0x00, 0x00, // 0
0x6E, 0x23, 0x00, 0x00, // name RVA
0x00, 0x20, 0x00, 0x00, // ImportAddressTableDirectory RVA
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x60, 0x23, 0x00, 0x00, // hint RVA
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, // hint
(byte)'_', (byte)'C', (byte)'o', (byte)'r', (byte)'D', (byte)'l', (byte)'l', (byte)'M', (byte)'a', (byte)'i', (byte)'n', 0x00,
(byte)'m', (byte)'s', (byte)'c', (byte)'o', (byte)'r', (byte)'e', (byte)'e', (byte)'.', (byte)'d', (byte)'l', (byte)'l', 0x00,
0x00
}, importTableDirectoryBytes);
var entryPointSectionIndex = peHeaders.GetContainingSectionIndex(peHeader.AddressOfEntryPoint);
Assert.Equal(0, entryPointSectionIndex);
peStream.Position = peHeaders.SectionHeaders[0].PointerToRawData + peHeader.AddressOfEntryPoint - peHeaders.SectionHeaders[0].VirtualAddress;
byte[] startupStub = new byte[8];
peStream.Read(startupStub, 0, startupStub.Length);
AssertEx.Equal(new byte[] { 0xFF, 0x25, 0x00, 0x20, 0x00, 0x10, 0x00, 0x00 }, startupStub);
Assert.Equal(Characteristics.Dll | Characteristics.LargeAddressAware | Characteristics.ExecutableImage, coffHeader.Characteristics);
Assert.Equal(Machine.I386, coffHeader.Machine);
Assert.Equal(2, coffHeader.NumberOfSections);
Assert.Equal(0, coffHeader.NumberOfSymbols);
Assert.Equal(0, coffHeader.PointerToSymbolTable);
Assert.Equal(0xe0, coffHeader.SizeOfOptionalHeader);
Assert.Equal(-609278808, coffHeader.TimeDateStamp);
Assert.Equal(0, corHeader.EntryPointTokenOrRelativeVirtualAddress);
Assert.Equal(CorFlags.ILOnly, corHeader.Flags);
Assert.Equal(2, corHeader.MajorRuntimeVersion);
Assert.Equal(5, corHeader.MinorRuntimeVersion);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.Size);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.Size);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.Size);
Assert.Equal(0x2058, corHeader.MetadataDirectory.RelativeVirtualAddress);
Assert.Equal(0x02b8, corHeader.MetadataDirectory.Size);
Assert.Equal(0, corHeader.ResourcesDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ResourcesDirectory.Size);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.Size);
Assert.Equal(0, corHeader.VtableFixupsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.VtableFixupsDirectory.Size);
var sections = peHeaders.SectionHeaders;
Assert.Equal(2, sections.Length);
Assert.Equal(".text", sections[0].Name);
Assert.Equal(0, sections[0].NumberOfLineNumbers);
Assert.Equal(0, sections[0].NumberOfRelocations);
Assert.Equal(0, sections[0].PointerToLineNumbers);
Assert.Equal(0x2000, sections[0].PointerToRawData);
Assert.Equal(0, sections[0].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead, sections[0].SectionCharacteristics);
Assert.Equal(0x2000, sections[0].SizeOfRawData);
Assert.Equal(0x2000, sections[0].VirtualAddress);
Assert.Equal(900, sections[0].VirtualSize);
Assert.Equal(".reloc", sections[1].Name);
Assert.Equal(0, sections[1].NumberOfLineNumbers);
Assert.Equal(0, sections[1].NumberOfRelocations);
Assert.Equal(0, sections[1].PointerToLineNumbers);
Assert.Equal(0x4000, sections[1].PointerToRawData);
Assert.Equal(0, sections[1].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable | SectionCharacteristics.MemRead, sections[1].SectionCharacteristics);
Assert.Equal(0x2000, sections[1].SizeOfRawData);
Assert.Equal(0x4000, sections[1].VirtualAddress);
Assert.Equal(12, sections[1].VirtualSize);
var relocBlock = peReader.GetSectionData(sections[1].VirtualAddress);
var relocBytes = new byte[sections[1].VirtualSize];
Marshal.Copy((IntPtr)relocBlock.Pointer, relocBytes, 0, relocBytes.Length);
AssertEx.Equal(new byte[] { 0, 0x20, 0, 0, 0x0c, 0, 0, 0, 0x80, 0x33, 0, 0 }, relocBytes);
}
[Fact]
public void PEHeaders2()
{
var options = EmitOptions.Default.
WithFileAlignment(512).
WithBaseAddress(0x123456789ABCDEF).
WithHighEntropyVirtualAddressSpace(true).
WithSubsystemVersion(SubsystemVersion.WindowsXP);
var syntax = SyntaxFactory.ParseSyntaxTree(@"class C { static void Main() { } }", TestOptions.Regular);
var peStream = CreateCompilationWithMscorlib40(
syntax,
options: TestOptions.DebugExe.WithPlatform(Platform.X64).WithDeterministic(true),
assemblyName: "B37A4FCD-ED76-4924-A2AD-298836056E00").EmitToStream(options);
peStream.Position = 0;
var peHeaders = new PEHeaders(peStream);
var peHeader = peHeaders.PEHeader;
var coffHeader = peHeaders.CoffHeader;
var corHeader = peHeaders.CorHeader;
Assert.Equal(PEMagic.PE32Plus, peHeader.Magic);
Assert.Equal(0x00000000, peHeader.AddressOfEntryPoint);
Assert.Equal(0x00002000, peHeader.BaseOfCode);
Assert.Equal(0x00000000, peHeader.BaseOfData);
Assert.Equal(0x00000200, peHeader.SizeOfHeaders);
Assert.Equal(0x00000400, peHeader.SizeOfCode);
Assert.Equal(0x00002000u, peHeader.SizeOfHeapCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfHeapReserve);
Assert.Equal(0x00004000, peHeader.SizeOfImage);
Assert.Equal(0x00000000, peHeader.SizeOfInitializedData);
Assert.Equal(0x00004000u, peHeader.SizeOfStackCommit);
Assert.Equal(0x0400000u, peHeader.SizeOfStackReserve);
Assert.Equal(0, peHeader.SizeOfUninitializedData);
Assert.Equal(Subsystem.WindowsCui, peHeader.Subsystem);
Assert.Equal(0u, peHeader.CheckSum);
Assert.Equal(0x200, peHeader.FileAlignment);
Assert.Equal(0x0123456789ac0000u, peHeader.ImageBase);
Assert.Equal(0x2000, peHeader.SectionAlignment);
Assert.Equal(0, peHeader.MajorImageVersion);
Assert.Equal(0, peHeader.MinorImageVersion);
Assert.Equal(0x30, peHeader.MajorLinkerVersion);
Assert.Equal(0, peHeader.MinorLinkerVersion);
Assert.Equal(4, peHeader.MajorOperatingSystemVersion);
Assert.Equal(0, peHeader.MinorOperatingSystemVersion);
Assert.Equal(5, peHeader.MajorSubsystemVersion);
Assert.Equal(1, peHeader.MinorSubsystemVersion);
Assert.Equal(16, peHeader.NumberOfRvaAndSizes);
Assert.Equal(0x200, peHeader.SizeOfHeaders);
Assert.Equal(0, peHeader.BaseRelocationTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BaseRelocationTableDirectory.Size);
Assert.Equal(0, peHeader.BoundImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BoundImportTableDirectory.Size);
Assert.Equal(0, peHeader.CertificateTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CertificateTableDirectory.Size);
Assert.Equal(0, peHeader.CopyrightTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CopyrightTableDirectory.Size);
Assert.Equal(0x2000, peHeader.CorHeaderTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x48, peHeader.CorHeaderTableDirectory.Size);
Assert.Equal(0x2324, peHeader.DebugTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x1C, peHeader.DebugTableDirectory.Size);
Assert.Equal(0, peHeader.ExceptionTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExceptionTableDirectory.Size);
Assert.Equal(0, peHeader.ExportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExportTableDirectory.Size);
Assert.Equal(0, peHeader.ImportAddressTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ImportAddressTableDirectory.Size);
Assert.Equal(0, peHeader.ImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ImportTableDirectory.Size);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.Size);
Assert.Equal(0, peHeader.ResourceTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ResourceTableDirectory.Size);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.Size);
Assert.Equal(Characteristics.LargeAddressAware | Characteristics.ExecutableImage, coffHeader.Characteristics);
Assert.Equal(Machine.Amd64, coffHeader.Machine);
Assert.Equal(1, coffHeader.NumberOfSections);
Assert.Equal(0, coffHeader.NumberOfSymbols);
Assert.Equal(0, coffHeader.PointerToSymbolTable);
Assert.Equal(240, coffHeader.SizeOfOptionalHeader);
Assert.Equal(-1823671907, coffHeader.TimeDateStamp);
Assert.Equal(0x06000001, corHeader.EntryPointTokenOrRelativeVirtualAddress);
Assert.Equal(CorFlags.ILOnly, corHeader.Flags);
Assert.Equal(2, corHeader.MajorRuntimeVersion);
Assert.Equal(5, corHeader.MinorRuntimeVersion);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.Size);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.Size);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.Size);
Assert.Equal(0x2054, corHeader.MetadataDirectory.RelativeVirtualAddress);
Assert.Equal(0x02d0, corHeader.MetadataDirectory.Size);
Assert.Equal(0, corHeader.ResourcesDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ResourcesDirectory.Size);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.Size);
Assert.Equal(0, corHeader.VtableFixupsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.VtableFixupsDirectory.Size);
var sections = peHeaders.SectionHeaders;
Assert.Equal(1, sections.Length);
Assert.Equal(".text", sections[0].Name);
Assert.Equal(0, sections[0].NumberOfLineNumbers);
Assert.Equal(0, sections[0].NumberOfRelocations);
Assert.Equal(0, sections[0].PointerToLineNumbers);
Assert.Equal(0x200, sections[0].PointerToRawData);
Assert.Equal(0, sections[0].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead, sections[0].SectionCharacteristics);
Assert.Equal(0x400, sections[0].SizeOfRawData);
Assert.Equal(0x2000, sections[0].VirtualAddress);
Assert.Equal(832, sections[0].VirtualSize);
}
[Fact]
public void InParametersShouldHaveMetadataIn_TypeMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
public void M(in int a, [In]in int b, [In]int c, int d) {}
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_IndexerMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
public int this[in int a, [In]in int b, [In]int c, int d] => 0;
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("get_Item").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_Delegates()
{
var text = @"
using System.Runtime.InteropServices;
public delegate void D(in int a, [In]in int b, [In]int c, int d);
public class C
{
public void M()
{
N((in int a, in int b, int c, int d) => {});
}
public void N(D lambda) { }
}
";
CompileAndVerify(text,
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
sourceSymbolValidator: module =>
{
var parameters = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.Parameters;
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
},
symbolValidator: module =>
{
var delegateParameters = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.Parameters;
Assert.Equal(4, delegateParameters.Length);
Assert.True(delegateParameters[0].IsMetadataIn);
Assert.True(delegateParameters[1].IsMetadataIn);
Assert.True(delegateParameters[2].IsMetadataIn);
Assert.False(delegateParameters[3].IsMetadataIn);
var lambdaParameters = module.GlobalNamespace.GetTypeMember("C").GetTypeMember("<>c").GetMethod("<M>b__0_0").Parameters;
Assert.Equal(4, lambdaParameters.Length);
Assert.True(lambdaParameters[0].IsMetadataIn);
Assert.True(lambdaParameters[1].IsMetadataIn);
Assert.False(lambdaParameters[2].IsMetadataIn);
Assert.False(lambdaParameters[3].IsMetadataIn);
});
}
[Fact]
public void InParametersShouldHaveMetadataIn_LocalFunctions()
{
var text = @"
using System.Runtime.InteropServices;
public class C
{
public void M()
{
void local(in int a, int c) { }
}
}
";
CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("C").GetMember("<M>g__local|0_0").GetParameters();
Assert.Equal(2, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.False(parameters[1].IsMetadataIn);
});
}
[Fact]
public void InParametersShouldHaveMetadataIn_ExternMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
[DllImport(""Other.dll"")]
public static extern void M(in int a, [In]in int b, [In]int c, int d);
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_NoPIA()
{
var comAssembly = CreateCompilationWithMscorlib40(@"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""test.dll"")]
[assembly: Guid(""6681dcd6-9c3e-4c3a-b04a-aef3ee85c2cf"")]
[ComImport()]
[Guid(""6681dcd6-9c3e-4c3a-b04a-aef3ee85c2cf"")]
public interface T
{
void M(in int a, [In]in int b, [In]int c, int d);
}");
CompileAndVerify(comAssembly, symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
});
var code = @"
class User
{
public void M(T obj)
{
obj.M(1, 2, 3, 4);
}
}";
CompileAndVerify(
source: code,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
references: new[] { comAssembly.EmitToImageReference(embedInteropTypes: true) },
symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
});
}
[Fact]
public void ExtendingInParametersFromParentWithoutInAttributeWorksWithoutErrors()
{
var reference = CompileIL(@"
.class private auto ansi sealed beforefieldinit Microsoft.CodeAnalysis.EmbeddedAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (01 00 00 00)
.custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = (01 00 00 00)
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: nop
IL_0007: ret
}
}
.class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (01 00 00 00)
.custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = (01 00 00 00)
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: nop
IL_0007: ret
}
}
.class public auto ansi beforefieldinit Parent extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual instance void M (
int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) a,
int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) b,
int32 c,
int32 d) cil managed
{
.param [1] .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (01 00 00 00)
.param [2] .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (01 00 00 00)
.maxstack 8
IL_0000: nop
IL_0001: ldstr ""Parent called""
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void[mscorlib] System.Object::.ctor()
IL_0006: nop
IL_0007: ret
}
}");
var comp = CreateCompilation(@"
using System;
using System.Runtime.InteropServices;
public class Child : Parent
{
public override void M(in int a, [In]in int b, [In]int c, int d)
{
base.M(a, b, c, d);
Console.WriteLine(""Child called"");
}
}
public static class Program
{
public static void Main()
{
var obj = new Child();
obj.M(1, 2, 3, 4);
}
}", new[] { reference }, TestOptions.ReleaseExe);
var parentParameters = comp.GetTypeByMetadataName("Parent").GetMethod("M").GetParameters();
Assert.Equal(4, parentParameters.Length);
Assert.False(parentParameters[0].IsMetadataIn);
Assert.False(parentParameters[1].IsMetadataIn);
Assert.False(parentParameters[2].IsMetadataIn);
Assert.False(parentParameters[3].IsMetadataIn);
var expectedOutput =
@"Parent called
Child called";
CompileAndVerify(comp, expectedOutput: expectedOutput, symbolValidator: module =>
{
var childParameters = module.ContainingAssembly.GetTypeByMetadataName("Child").GetMethod("M").GetParameters();
Assert.Equal(4, childParameters.Length);
Assert.True(childParameters[0].IsMetadataIn);
Assert.True(childParameters[1].IsMetadataIn);
Assert.True(childParameters[2].IsMetadataIn);
Assert.False(childParameters[3].IsMetadataIn);
});
}
[Fact]
public void GeneratingProxyForVirtualMethodInParentCopiesMetadataBitsCorrectly_OutAttribute()
{
var reference = CreateCompilation(@"
using System.Runtime.InteropServices;
public class Parent
{
public void M(out int a, [Out] int b) => throw null;
}");
CompileAndVerify(reference, symbolValidator: module =>
{
var sourceParentParameters = module.GlobalNamespace.GetTypeMember("Parent").GetMethod("M").GetParameters();
Assert.Equal(2, sourceParentParameters.Length);
Assert.True(sourceParentParameters[0].IsMetadataOut);
Assert.True(sourceParentParameters[1].IsMetadataOut);
});
var source = @"
using System.Runtime.InteropServices;
public interface IParent
{
void M(out int a, [Out] int b);
}
public class Child : Parent, IParent
{
}";
CompileAndVerify(
source: source,
references: new[] { reference.EmitToImageReference() },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var interfaceParameters = module.GlobalNamespace.GetTypeMember("IParent").GetMethod("M").GetParameters();
Assert.Equal(2, interfaceParameters.Length);
Assert.True(interfaceParameters[0].IsMetadataOut);
Assert.True(interfaceParameters[1].IsMetadataOut);
var proxyChildParameters = module.GlobalNamespace.GetTypeMember("Child").GetMethod("IParent.M").GetParameters();
Assert.Equal(2, proxyChildParameters.Length);
Assert.True(proxyChildParameters[0].IsMetadataOut);
Assert.False(proxyChildParameters[1].IsMetadataOut); // User placed attributes are not copied.
});
}
[Fact]
public void GeneratingProxyForVirtualMethodInParentCopiesMetadataBitsCorrectly_InAttribute()
{
var reference = CreateCompilation(@"
using System.Runtime.InteropServices;
public class Parent
{
public void M(in int a, [In] int b) => throw null;
}");
CompileAndVerify(reference, symbolValidator: module =>
{
var sourceParentParameters = module.GlobalNamespace.GetTypeMember("Parent").GetMethod("M").GetParameters();
Assert.Equal(2, sourceParentParameters.Length);
Assert.True(sourceParentParameters[0].IsMetadataIn);
Assert.True(sourceParentParameters[1].IsMetadataIn);
});
var source = @"
using System.Runtime.InteropServices;
public interface IParent
{
void M(in int a, [In] int b);
}
public class Child : Parent, IParent
{
}";
CompileAndVerify(
source: source,
references: new[] { reference.EmitToImageReference() },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var interfaceParameters = module.GlobalNamespace.GetTypeMember("IParent").GetMethod("M").GetParameters();
Assert.Equal(2, interfaceParameters.Length);
Assert.True(interfaceParameters[0].IsMetadataIn);
Assert.True(interfaceParameters[1].IsMetadataIn);
var proxyChildParameters = module.GlobalNamespace.GetTypeMember("Child").GetMethod("IParent.M").GetParameters();
Assert.Equal(2, proxyChildParameters.Length);
Assert.True(proxyChildParameters[0].IsMetadataIn);
Assert.False(proxyChildParameters[1].IsMetadataIn); // User placed attributes are not copied.
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class EmitMetadata : EmitMetadataTestBase
{
[Fact]
public void InstantiatedGenerics()
{
string source = @"
public class A<T>
{
public class B : A<T>
{
internal class C : B
{}
protected B y1;
protected A<D>.B y2;
}
public class H<S>
{
public class I : A<T>.H<S>
{}
}
internal A<T> x1;
internal A<D> x2;
}
public class D
{
public class K<T>
{
public class L : K<T>
{}
}
}
namespace NS1
{
class E : D
{}
}
class F : A<D>
{}
class G : A<NS1.E>.B
{}
class J : A<D>.H<D>
{}
public class M
{}
public class N : D.K<M>
{}
";
CompileAndVerify(source, symbolValidator: module =>
{
var dump = DumpTypeInfo(module).ToString();
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
<Global>
<type name=""<Module>"" />
<type name=""A"" Of=""T"" base=""System.Object"">
<field name=""x1"" type=""A<T>"" />
<field name=""x2"" type=""A<D>"" />
<type name=""B"" base=""A<T>"">
<field name=""y1"" type=""A<T>.B"" />
<field name=""y2"" type=""A<D>.B"" />
<type name=""C"" base=""A<T>.B"" />
</type>
<type name=""H"" Of=""S"" base=""System.Object"">
<type name=""I"" base=""A<T>.H<S>"" />
</type>
</type>
<type name=""D"" base=""System.Object"">
<type name=""K"" Of=""T"" base=""System.Object"">
<type name=""L"" base=""D.K<T>"" />
</type>
</type>
<type name=""F"" base=""A<D>"" />
<type name=""G"" base=""A<NS1.E>.B"" />
<type name=""J"" base=""A<D>.H<D>"" />
<type name=""M"" base=""System.Object"" />
<type name=""N"" base=""D.K<M>"" />
<NS1>
<type name=""E"" base=""D"" />
</NS1>
</Global>
", dump);
}, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void StringArrays()
{
string source = @"
public class D
{
public D()
{}
public static void Main()
{
System.Console.WriteLine(65536);
arrayField = new string[] {""string1"", ""string2""};
System.Console.WriteLine(arrayField[1]);
System.Console.WriteLine(arrayField[0]);
}
static string[] arrayField;
}
";
CompileAndVerify(source, expectedOutput: @"
65536
string2
string1
"
);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void FieldRVA()
{
string source = @"
public class D
{
public D()
{}
public static void Main()
{
byte[] a = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.Console.WriteLine(a[0]);
System.Console.WriteLine(a[8]);
}
}
";
CompileAndVerify(source, expectedOutput: @"
1
9
"
);
}
[Fact]
public void AssemblyRefs1()
{
var metadataTestLib1 = TestReferences.SymbolsTests.MDTestLib1;
var metadataTestLib2 = TestReferences.SymbolsTests.MDTestLib2;
string source = @"
public class Test : C107
{
}
";
CompileAndVerifyWithMscorlib40(source, new[] { metadataTestLib1, metadataTestLib2 }, assemblyValidator: (assembly) =>
{
var refs = assembly.Modules[0].ReferencedAssemblies.OrderBy(r => r.Name).ToArray();
Assert.Equal(2, refs.Length);
Assert.Equal("MDTestLib1", refs[0].Name, StringComparer.OrdinalIgnoreCase);
Assert.Equal("mscorlib", refs[1].Name, StringComparer.OrdinalIgnoreCase);
});
}
[Fact]
public void AssemblyRefs2()
{
string sources = @"
public class Test : Class2
{
}
";
CompileAndVerifyWithMscorlib40(sources, new[] { TestReferences.SymbolsTests.MultiModule.Assembly }, assemblyValidator: (assembly) =>
{
var refs2 = assembly.Modules[0].ReferencedAssemblies.Select(r => r.Name);
Assert.Equal(2, refs2.Count());
Assert.Contains("MultiModule", refs2, StringComparer.OrdinalIgnoreCase);
Assert.Contains("mscorlib", refs2, StringComparer.OrdinalIgnoreCase);
var peFileReader = assembly.GetMetadataReader();
Assert.Equal(0, peFileReader.GetTableRowCount(TableIndex.File));
Assert.Equal(0, peFileReader.GetTableRowCount(TableIndex.ModuleRef));
});
}
[WorkItem(687434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/687434")]
[Fact()]
public void Bug687434()
{
CompileAndVerify(
"public class C { }",
verify: Verification.Fails,
options: TestOptions.DebugDll.WithOutputKind(OutputKind.NetModule));
}
[Fact, WorkItem(529006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529006")]
public void AddModule()
{
var netModule1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(filePath: Path.GetFullPath("netModule1.netmodule"));
var netModule2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2).GetReference(filePath: Path.GetFullPath("netModule2.netmodule"));
string source = @"
public class Test : Class1
{
}
";
// modules not supported in ref emit
CompileAndVerify(source, new[] { netModule1, netModule2 }, assemblyValidator: (assembly) =>
{
Assert.Equal(3, assembly.Modules.Length);
var reader = assembly.GetMetadataReader();
Assert.Equal(2, reader.GetTableRowCount(TableIndex.File));
var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1));
var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2));
Assert.Equal("netModule1.netmodule", reader.GetString(file1.Name));
Assert.Equal("netModule2.netmodule", reader.GetString(file2.Name));
Assert.False(file1.HashValue.IsNil);
Assert.False(file2.HashValue.IsNil);
Assert.Equal(1, reader.GetTableRowCount(TableIndex.ModuleRef));
var moduleRefName = reader.GetModuleReference(MetadataTokens.ModuleReferenceHandle(1)).Name;
Assert.Equal("netModule1.netmodule", reader.GetString(moduleRefName));
var actual = from h in reader.ExportedTypes
let et = reader.GetExportedType(h)
select $"{reader.GetString(et.NamespaceDefinition)}.{reader.GetString(et.Name)} 0x{MetadataTokens.GetToken(et.Implementation):X8} ({et.Implementation.Kind}) 0x{(int)et.Attributes:X4}";
AssertEx.Equal(new[]
{
".Class1 0x26000001 (AssemblyFile) 0x0001",
".Class3 0x27000001 (ExportedType) 0x0002",
"NS1.Class4 0x26000001 (AssemblyFile) 0x0001",
".Class7 0x27000003 (ExportedType) 0x0002",
".Class2 0x26000002 (AssemblyFile) 0x0001"
}, actual);
});
}
[Fact]
public void ImplementingAnInterface()
{
string source = @"
public interface I1
{}
public class A : I1
{
}
public interface I2
{
void M2();
}
public interface I3
{
void M3();
}
abstract public class B : I2, I3
{
public abstract void M2();
public abstract void M3();
}
";
CompileAndVerify(source, symbolValidator: module =>
{
var classA = module.GlobalNamespace.GetMember<NamedTypeSymbol>("A");
var classB = module.GlobalNamespace.GetMember<NamedTypeSymbol>("B");
var i1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I1");
var i2 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I2");
var i3 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I3");
Assert.Equal(TypeKind.Interface, i1.TypeKind);
Assert.Equal(TypeKind.Interface, i2.TypeKind);
Assert.Equal(TypeKind.Interface, i3.TypeKind);
Assert.Equal(TypeKind.Class, classA.TypeKind);
Assert.Equal(TypeKind.Class, classB.TypeKind);
Assert.Same(i1, classA.Interfaces().Single());
var interfaces = classB.Interfaces();
Assert.Same(i2, interfaces[0]);
Assert.Same(i3, interfaces[1]);
Assert.Equal(1, i2.GetMembers("M2").Length);
Assert.Equal(1, i3.GetMembers("M3").Length);
});
}
[Fact]
public void InterfaceOrder()
{
string source = @"
interface I1 : I2, I5 { }
interface I2 : I3, I4 { }
interface I3 { }
interface I4 { }
interface I5 : I6, I7 { }
interface I6 { }
interface I7 { }
class C : I1 { }
";
CompileAndVerify(source, symbolValidator: module =>
{
var i1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I1");
var i2 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I2");
var i3 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I3");
var i4 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I4");
var i5 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I5");
var i6 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I6");
var i7 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("I7");
var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
// Order is important - should be pre-order depth-first with declaration order at each level
Assert.True(i1.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i2, i3, i4, i5, i6, i7)));
Assert.True(i2.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i3, i4)));
Assert.False(i3.Interfaces().Any());
Assert.False(i4.Interfaces().Any());
Assert.True(i5.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i6, i7)));
Assert.False(i6.Interfaces().Any());
Assert.False(i7.Interfaces().Any());
Assert.True(c.Interfaces().SequenceEqual(ImmutableArray.Create<NamedTypeSymbol>(i1, i2, i3, i4, i5, i6, i7)));
});
}
[Fact]
public void ExplicitGenericInterfaceImplementation()
{
CompileAndVerify(@"
class S
{
class C<T>
{
public interface I
{
void m(T x);
}
}
abstract public class D : C<int>.I
{
void C<int>.I.m(int x)
{
}
}
}
");
}
[Fact]
public void TypeWithAbstractMethod()
{
string source = @"
abstract public class A
{
public abstract A[] M1(ref System.Array p1);
public abstract A[,] M2(System.Boolean p2);
public abstract A[,,] M3(System.Char p3);
public abstract void M4(System.SByte p4,
System.Single p5,
System.Double p6,
System.Int16 p7,
System.Int32 p8,
System.Int64 p9,
System.IntPtr p10,
System.String p11,
System.Byte p12,
System.UInt16 p13,
System.UInt32 p14,
System.UInt64 p15,
System.UIntPtr p16);
public abstract void M5<T, S>(T p17, S p18);
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll, symbolValidator: module =>
{
var classA = module.GlobalNamespace.GetTypeMembers("A").Single();
var m1 = classA.GetMembers("M1").OfType<MethodSymbol>().Single();
var m2 = classA.GetMembers("M2").OfType<MethodSymbol>().Single();
var m3 = classA.GetMembers("M3").OfType<MethodSymbol>().Single();
var m4 = classA.GetMembers("M4").OfType<MethodSymbol>().Single();
var m5 = classA.GetMembers("M5").OfType<MethodSymbol>().Single();
var method1Ret = (ArrayTypeSymbol)m1.ReturnType;
var method2Ret = (ArrayTypeSymbol)m2.ReturnType;
var method3Ret = (ArrayTypeSymbol)m3.ReturnType;
Assert.True(method1Ret.IsSZArray);
Assert.Same(classA, method1Ret.ElementType);
Assert.Equal(2, method2Ret.Rank);
Assert.Same(classA, method2Ret.ElementType);
Assert.Equal(3, method3Ret.Rank);
Assert.Same(classA, method3Ret.ElementType);
Assert.True(classA.IsAbstract);
Assert.Equal(Accessibility.Public, classA.DeclaredAccessibility);
var parameter1 = m1.Parameters.Single();
var parameter1Type = parameter1.Type;
Assert.Equal(RefKind.Ref, parameter1.RefKind);
Assert.Same(module.GetCorLibType(SpecialType.System_Array), parameter1Type);
Assert.Same(module.GetCorLibType(SpecialType.System_Boolean), m2.Parameters.Single().Type);
Assert.Same(module.GetCorLibType(SpecialType.System_Char), m3.Parameters.Single().Type);
var method4ParamTypes = m4.Parameters.Select(p => p.Type).ToArray();
Assert.Same(module.GetCorLibType(SpecialType.System_Void), m4.ReturnType);
Assert.Same(module.GetCorLibType(SpecialType.System_SByte), method4ParamTypes[0]);
Assert.Same(module.GetCorLibType(SpecialType.System_Single), method4ParamTypes[1]);
Assert.Same(module.GetCorLibType(SpecialType.System_Double), method4ParamTypes[2]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int16), method4ParamTypes[3]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int32), method4ParamTypes[4]);
Assert.Same(module.GetCorLibType(SpecialType.System_Int64), method4ParamTypes[5]);
Assert.Same(module.GetCorLibType(SpecialType.System_IntPtr), method4ParamTypes[6]);
Assert.Same(module.GetCorLibType(SpecialType.System_String), method4ParamTypes[7]);
Assert.Same(module.GetCorLibType(SpecialType.System_Byte), method4ParamTypes[8]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt16), method4ParamTypes[9]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt32), method4ParamTypes[10]);
Assert.Same(module.GetCorLibType(SpecialType.System_UInt64), method4ParamTypes[11]);
Assert.Same(module.GetCorLibType(SpecialType.System_UIntPtr), method4ParamTypes[12]);
Assert.True(m5.IsGenericMethod);
Assert.Same(m5.TypeParameters[0], m5.Parameters[0].Type);
Assert.Same(m5.TypeParameters[1], m5.Parameters[1].Type);
Assert.Equal(6, ((PEModuleSymbol)module).Module.GetMetadataReader().TypeReferences.Count);
});
}
[Fact]
public void Types()
{
string source = @"
sealed internal class B
{}
static class C
{
public class D{}
internal class E{}
protected class F{}
private class G{}
protected internal class H{}
class K{}
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classB = module.GlobalNamespace.GetTypeMembers("B").Single();
Assert.True(classB.IsSealed);
Assert.Equal(Accessibility.Internal, classB.DeclaredAccessibility);
var classC = module.GlobalNamespace.GetTypeMembers("C").Single();
Assert.True(classC.IsStatic);
Assert.Equal(Accessibility.Internal, classC.DeclaredAccessibility);
var classD = classC.GetTypeMembers("D").Single();
var classE = classC.GetTypeMembers("E").Single();
var classF = classC.GetTypeMembers("F").Single();
var classH = classC.GetTypeMembers("H").Single();
Assert.Equal(Accessibility.Public, classD.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, classE.DeclaredAccessibility);
Assert.Equal(Accessibility.Protected, classF.DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedOrInternal, classH.DeclaredAccessibility);
if (isFromSource)
{
var classG = classC.GetTypeMembers("G").Single();
var classK = classC.GetTypeMembers("K").Single();
Assert.Equal(Accessibility.Private, classG.DeclaredAccessibility);
Assert.Equal(Accessibility.Private, classK.DeclaredAccessibility);
}
var peModuleSymbol = module as PEModuleSymbol;
if (peModuleSymbol != null)
{
Assert.Equal(5, peModuleSymbol.Module.GetMetadataReader().TypeReferences.Count);
}
};
CompileAndVerify(source, options: TestOptions.ReleaseDll, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void Fields()
{
string source = @"
public class A
{
public int F1;
internal volatile int F2;
protected internal string F3;
protected float F4;
private double F5;
char F6;
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classA = module.GlobalNamespace.GetTypeMembers("A").Single();
var f1 = classA.GetMembers("F1").OfType<FieldSymbol>().Single();
var f2 = classA.GetMembers("F2").OfType<FieldSymbol>().Single();
var f3 = classA.GetMembers("F3").OfType<FieldSymbol>().Single();
var f4 = classA.GetMembers("F4").OfType<FieldSymbol>().Single();
Assert.False(f1.IsVolatile);
Assert.Equal(0, f1.TypeWithAnnotations.CustomModifiers.Length);
Assert.True(f2.IsVolatile);
Assert.Equal(1, f2.TypeWithAnnotations.CustomModifiers.Length);
CustomModifier mod = f2.TypeWithAnnotations.CustomModifiers[0];
Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, f2.DeclaredAccessibility);
Assert.Equal(Accessibility.ProtectedOrInternal, f3.DeclaredAccessibility);
Assert.Equal(Accessibility.Protected, f4.DeclaredAccessibility);
if (isFromSource)
{
var f5 = classA.GetMembers("F5").OfType<FieldSymbol>().Single();
var f6 = classA.GetMembers("F6").OfType<FieldSymbol>().Single();
Assert.Equal(Accessibility.Private, f5.DeclaredAccessibility);
Assert.Equal(Accessibility.Private, f6.DeclaredAccessibility);
}
Assert.False(mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsVolatile", mod.Modifier.ToTestDisplayString());
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void Constructors()
{
string source =
@"namespace N
{
abstract class C
{
static C() {}
protected C() {}
}
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("N.C");
var ctor = (MethodSymbol)type.GetMembers(".ctor").SingleOrDefault();
var cctor = (MethodSymbol)type.GetMembers(".cctor").SingleOrDefault();
Assert.NotNull(ctor);
Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name);
Assert.Equal(MethodKind.Constructor, ctor.MethodKind);
Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility);
Assert.True(ctor.IsDefinition);
Assert.False(ctor.IsStatic);
Assert.False(ctor.IsAbstract);
Assert.False(ctor.IsSealed);
Assert.False(ctor.IsVirtual);
Assert.False(ctor.IsOverride);
Assert.False(ctor.IsGenericMethod);
Assert.False(ctor.IsExtensionMethod);
Assert.True(ctor.ReturnsVoid);
Assert.False(ctor.IsVararg);
// Bug - 2067
Assert.Equal("N.C." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString());
Assert.Equal(0, ctor.TypeParameters.Length);
Assert.Equal("Void", ctor.ReturnTypeWithAnnotations.Type.Name);
if (isFromSource)
{
Assert.NotNull(cctor);
Assert.Equal(WellKnownMemberNames.StaticConstructorName, cctor.Name);
Assert.Equal(MethodKind.StaticConstructor, cctor.MethodKind);
Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility);
Assert.True(cctor.IsDefinition);
Assert.True(cctor.IsStatic);
Assert.False(cctor.IsAbstract);
Assert.False(cctor.IsSealed);
Assert.False(cctor.IsVirtual);
Assert.False(cctor.IsOverride);
Assert.False(cctor.IsGenericMethod);
Assert.False(cctor.IsExtensionMethod);
Assert.True(cctor.ReturnsVoid);
Assert.False(cctor.IsVararg);
// Bug - 2067
Assert.Equal("N.C." + WellKnownMemberNames.StaticConstructorName + "()", cctor.ToTestDisplayString());
Assert.Equal(0, cctor.TypeArgumentsWithAnnotations.Length);
Assert.Equal(0, cctor.Parameters.Length);
Assert.Equal("Void", cctor.ReturnTypeWithAnnotations.Type.Name);
}
else
{
Assert.Null(cctor);
}
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void ConstantFields()
{
string source =
@"class C
{
private const int I = -1;
internal const int J = I;
protected internal const object O = null;
public const string S = ""string"";
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
if (isFromSource)
{
CheckConstantField(type, "I", Accessibility.Private, SpecialType.System_Int32, -1);
}
CheckConstantField(type, "J", Accessibility.Internal, SpecialType.System_Int32, -1);
CheckConstantField(type, "O", Accessibility.ProtectedOrInternal, SpecialType.System_Object, null);
CheckConstantField(type, "S", Accessibility.Public, SpecialType.System_String, "string");
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
private void CheckConstantField(NamedTypeSymbol type, string name, Accessibility declaredAccessibility, SpecialType fieldType, object value)
{
var field = type.GetMembers(name).SingleOrDefault() as FieldSymbol;
Assert.NotNull(field);
Assert.True(field.IsStatic);
Assert.True(field.IsConst);
Assert.Equal(field.DeclaredAccessibility, declaredAccessibility);
Assert.Equal(field.Type.SpecialType, fieldType);
Assert.Equal(field.ConstantValue, value);
}
//the test for not importing internal members is elsewhere
[Fact]
public void DoNotImportPrivateMembers()
{
string source =
@"namespace Namespace
{
public class Public { }
internal class Internal { }
}
class Types
{
public class Public { }
internal class Internal { }
protected class Protected { }
protected internal class ProtectedInternal { }
private class Private { }
}
class Fields
{
public object Public = null;
internal object Internal = null;
protected object Protected = null;
protected internal object ProtectedInternal = null;
private object Private = null;
}
class Methods
{
public void Public() { }
internal void Internal() { }
protected void Protected() { }
protected internal void ProtectedInternal() { }
private void Private() { }
}
class Properties
{
public object Public { get; set; }
internal object Internal { get; set; }
protected object Protected { get; set; }
protected internal object ProtectedInternal { get; set; }
private object Private { get; set; }
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var nmspace = module.GlobalNamespace.GetMember<NamespaceSymbol>("Namespace");
Assert.NotNull(nmspace.GetTypeMembers("Public").SingleOrDefault());
Assert.NotNull(nmspace.GetTypeMembers("Internal").SingleOrDefault());
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Types").Single(), isFromSource, true);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource, false);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource, false);
CheckPrivateMembers(module.GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource, false);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
private void CheckPrivateMembers(NamedTypeSymbol type, bool isFromSource, bool importPrivates)
{
Symbol member;
member = type.GetMembers("Public").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Internal").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Protected").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("ProtectedInternal").SingleOrDefault();
Assert.NotNull(member);
member = type.GetMembers("Private").SingleOrDefault();
if (isFromSource || importPrivates)
{
Assert.NotNull(member);
}
else
{
Assert.Null(member);
}
}
[Fact]
public void GenericBaseTypeResolution()
{
string source =
@"class Base<T, U>
{
}
class Derived<T, U> : Base<T, U>
{
}";
Action<ModuleSymbol> validator = module =>
{
var derivedType = module.GlobalNamespace.GetTypeMembers("Derived").Single();
Assert.Equal(2, derivedType.Arity);
var baseType = derivedType.BaseType();
Assert.Equal("Base", baseType.Name);
Assert.Equal(2, baseType.Arity);
Assert.Equal(derivedType.BaseType(), baseType);
Assert.Same(baseType.TypeArguments()[0], derivedType.TypeParameters[0]);
Assert.Same(baseType.TypeArguments()[1], derivedType.TypeParameters[1]);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void ImportExplicitImplementations()
{
string source =
@"interface I
{
void Method();
object Property { get; set; }
}
class C : I
{
void I.Method() { }
object I.Property { get; set; }
}";
Action<ModuleSymbol> validator = module =>
{
// Interface
var type = module.GlobalNamespace.GetTypeMembers("I").Single();
var method = (MethodSymbol)type.GetMembers("Method").Single();
Assert.NotNull(method);
var property = (PropertySymbol)type.GetMembers("Property").Single();
Assert.NotNull(property.GetMethod);
Assert.NotNull(property.SetMethod);
// Implementation
type = module.GlobalNamespace.GetTypeMembers("C").Single();
method = (MethodSymbol)type.GetMembers("I.Method").Single();
Assert.NotNull(method);
property = (PropertySymbol)type.GetMembers("I.Property").Single();
Assert.NotNull(property.GetMethod);
Assert.NotNull(property.SetMethod);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void Properties()
{
string source =
@"public class C
{
public int P1 { get { return 0; } set { } }
internal int P2 { get { return 0; } }
protected internal int P3 { get { return 0; } }
protected int P4 { get { return 0; } }
private int P5 { set { } }
int P6 { get { return 0; } }
public int P7 { private get { return 0; } set { } }
internal int P8 { get { return 0; } private set { } }
protected int P9 { get { return 0; } private set { } }
protected internal int P10 { protected get { return 0; } set { } }
protected internal int P11 { internal get { return 0; } set { } }
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
var members = type.GetMembers();
// Ensure member names are unique.
var memberNames = members.Select(member => member.Name).Distinct().ToList();
Assert.Equal(memberNames.Count, members.Length);
var c = members.First(member => member.Name == ".ctor");
Assert.NotNull(c);
var p1 = (PropertySymbol)members.First(member => member.Name == "P1");
var p2 = (PropertySymbol)members.First(member => member.Name == "P2");
var p3 = (PropertySymbol)members.First(member => member.Name == "P3");
var p4 = (PropertySymbol)members.First(member => member.Name == "P4");
var p7 = (PropertySymbol)members.First(member => member.Name == "P7");
var p8 = (PropertySymbol)members.First(member => member.Name == "P8");
var p9 = (PropertySymbol)members.First(member => member.Name == "P9");
var p10 = (PropertySymbol)members.First(member => member.Name == "P10");
var p11 = (PropertySymbol)members.First(member => member.Name == "P11");
var privateOrNotApplicable = isFromSource ? Accessibility.Private : Accessibility.NotApplicable;
CheckPropertyAccessibility(p1, Accessibility.Public, Accessibility.Public, Accessibility.Public);
CheckPropertyAccessibility(p2, Accessibility.Internal, Accessibility.Internal, Accessibility.NotApplicable);
CheckPropertyAccessibility(p3, Accessibility.ProtectedOrInternal, Accessibility.ProtectedOrInternal, Accessibility.NotApplicable);
CheckPropertyAccessibility(p4, Accessibility.Protected, Accessibility.Protected, Accessibility.NotApplicable);
CheckPropertyAccessibility(p7, Accessibility.Public, privateOrNotApplicable, Accessibility.Public);
CheckPropertyAccessibility(p8, Accessibility.Internal, Accessibility.Internal, privateOrNotApplicable);
CheckPropertyAccessibility(p9, Accessibility.Protected, Accessibility.Protected, privateOrNotApplicable);
CheckPropertyAccessibility(p10, Accessibility.ProtectedOrInternal, Accessibility.Protected, Accessibility.ProtectedOrInternal);
CheckPropertyAccessibility(p11, Accessibility.ProtectedOrInternal, Accessibility.Internal, Accessibility.ProtectedOrInternal);
if (isFromSource)
{
var p5 = (PropertySymbol)members.First(member => member.Name == "P5");
var p6 = (PropertySymbol)members.First(member => member.Name == "P6");
CheckPropertyAccessibility(p5, Accessibility.Private, Accessibility.NotApplicable, Accessibility.Private);
CheckPropertyAccessibility(p6, Accessibility.Private, Accessibility.Private, Accessibility.NotApplicable);
}
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false), options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
}
[Fact]
public void SetGetOnlyAutopropsInConstructors()
{
var comp = CreateCompilationWithMscorlib45(@"using System;
class C
{
public int P1 { get; }
public static int P2 { get; }
public C()
{
P1 = 10;
}
static C()
{
P2 = 11;
}
static void Main()
{
Console.Write(C.P2);
var c = new C();
Console.Write(c.P1);
}
}", options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "1110");
}
[Fact]
public void AutoPropInitializersClass()
{
var comp = CreateCompilation(@"using System;
class C
{
public int P { get; set; } = 1;
public string Q { get; set; } = ""test"";
public decimal R { get; } = 300;
public static char S { get; } = 'S';
static void Main()
{
var c = new C();
Console.Write(c.P);
Console.Write(c.Q);
Console.Write(c.R);
Console.Write(C.S);
}
}", parseOptions: TestOptions.Regular,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var p = type.GetMember<SourcePropertySymbol>("P");
var pBack = p.BackingField;
Assert.False(pBack.IsReadOnly);
Assert.False(pBack.IsStatic);
Assert.Equal(SpecialType.System_Int32, pBack.Type.SpecialType);
var q = type.GetMember<SourcePropertySymbol>("Q");
var qBack = q.BackingField;
Assert.False(qBack.IsReadOnly);
Assert.False(qBack.IsStatic);
Assert.Equal(SpecialType.System_String, qBack.Type.SpecialType);
var r = type.GetMember<SourcePropertySymbol>("R");
var rBack = r.BackingField;
Assert.True(rBack.IsReadOnly);
Assert.False(rBack.IsStatic);
Assert.Equal(SpecialType.System_Decimal, rBack.Type.SpecialType);
var s = type.GetMember<SourcePropertySymbol>("S");
var sBack = s.BackingField;
Assert.True(sBack.IsReadOnly);
Assert.True(sBack.IsStatic);
Assert.Equal(SpecialType.System_Char, sBack.Type.SpecialType);
};
CompileAndVerify(
comp,
sourceSymbolValidator: validator,
expectedOutput: "1test300S");
}
[Fact]
public void AutoPropInitializersStruct()
{
var comp = CreateCompilation(@"
using System;
struct S
{
public readonly int P;
public string Q { get; }
public decimal R { get; }
public static char T { get; } = 'T';
public S(int p)
{
P = p;
Q = ""test"";
R = 300;
}
static void Main()
{
var s = new S(1);
Console.Write(s.P);
Console.Write(s.Q);
Console.Write(s.R);
Console.Write(S.T);
s = new S();
Console.Write(s.P);
Console.Write(s.Q ?? ""null"");
Console.Write(s.R);
Console.Write(S.T);
}
}", parseOptions: TestOptions.Regular,
options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal));
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetMember<NamedTypeSymbol>("S");
var p = type.GetMember<SourceMemberFieldSymbol>("P");
Assert.False(p.HasInitializer);
Assert.True(p.IsReadOnly);
Assert.False(p.IsStatic);
Assert.Equal(SpecialType.System_Int32, p.Type.SpecialType);
var q = type.GetMember<SourcePropertySymbol>("Q");
var qBack = q.BackingField;
Assert.True(qBack.IsReadOnly);
Assert.False(qBack.IsStatic);
Assert.Equal(SpecialType.System_String, qBack.Type.SpecialType);
var r = type.GetMember<SourcePropertySymbol>("R");
var rBack = r.BackingField;
Assert.True(rBack.IsReadOnly);
Assert.False(rBack.IsStatic);
Assert.Equal(SpecialType.System_Decimal, rBack.Type.SpecialType);
var s = type.GetMember<SourcePropertySymbol>("T");
var sBack = s.BackingField;
Assert.True(sBack.IsReadOnly);
Assert.True(sBack.IsStatic);
Assert.Equal(SpecialType.System_Char, sBack.Type.SpecialType);
};
CompileAndVerify(
comp,
sourceSymbolValidator: validator,
expectedOutput: "1test300T0null0T");
}
/// <summary>
/// Private accessors of a virtual property should not be virtual.
/// </summary>
[Fact]
public void PrivatePropertyAccessorNotVirtual()
{
string source = @"
class C
{
public virtual int P { get; private set; }
public virtual int Q { get; internal set; }
}
class D : C
{
public override int Q { internal set { } }
}
class E : D
{
public override int Q { get { return 0; } }
}
class F : E
{
public override int P { get { return 0; } }
public override int Q { internal set { } }
}
class Program
{
static void Main()
{
}
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
bool checkValidProperties = (type is PENamedTypeSymbol);
var propertyP = (PropertySymbol)type.GetMembers("P").Single();
if (isFromSource)
{
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.Private);
Assert.False(propertyP.SetMethod.IsVirtual);
Assert.False(propertyP.SetMethod.IsOverride);
}
else
{
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable);
Assert.Null(propertyP.SetMethod);
}
Assert.True(propertyP.GetMethod.IsVirtual);
Assert.False(propertyP.GetMethod.IsOverride);
var propertyQ = (PropertySymbol)type.GetMembers("Q").Single();
CheckPropertyAccessibility(propertyQ, Accessibility.Public, Accessibility.Public, Accessibility.Internal);
Assert.True(propertyQ.GetMethod.IsVirtual);
Assert.False(propertyQ.GetMethod.IsOverride);
Assert.True(propertyQ.SetMethod.IsVirtual);
Assert.False(propertyQ.SetMethod.IsOverride);
Assert.False(propertyQ.IsReadOnly);
Assert.False(propertyQ.IsWriteOnly);
if (checkValidProperties)
{
Assert.False(propertyP.MustCallMethodsDirectly);
Assert.False(propertyQ.MustCallMethodsDirectly);
}
type = module.GlobalNamespace.GetTypeMembers("F").Single();
propertyP = (PropertySymbol)type.GetMembers("P").Single();
CheckPropertyAccessibility(propertyP, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable);
Assert.False(propertyP.GetMethod.IsVirtual);
Assert.True(propertyP.GetMethod.IsOverride);
propertyQ = (PropertySymbol)type.GetMembers("Q").Single();
// Derived property should be public even though the only
// declared accessor on the derived property is internal.
CheckPropertyAccessibility(propertyQ, Accessibility.Public, Accessibility.NotApplicable, Accessibility.Internal);
Assert.False(propertyQ.SetMethod.IsVirtual);
Assert.True(propertyQ.SetMethod.IsOverride);
Assert.False(propertyQ.IsReadOnly);
Assert.False(propertyQ.IsWriteOnly);
if (checkValidProperties)
{
Assert.False(propertyP.MustCallMethodsDirectly);
Assert.False(propertyQ.MustCallMethodsDirectly);
}
// Overridden property should be E but overridden
// accessor should be D.set_Q.
var overriddenProperty = module.GlobalNamespace.GetTypeMembers("E").Single().GetMembers("Q").Single();
Assert.NotNull(overriddenProperty);
Assert.Same(overriddenProperty, propertyQ.OverriddenProperty);
var overriddenAccessor = module.GlobalNamespace.GetTypeMembers("D").Single().GetMembers("set_Q").Single();
Assert.NotNull(overriddenProperty);
Assert.Same(overriddenAccessor, propertyQ.SetMethod.OverriddenMethod);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void InterfaceProperties()
{
string source = @"
interface I
{
int P { get; set; }
}
public class C : I
{
int I.P { get { return 0; } set { } }
}";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("C").Single();
var members = type.GetMembers();
var ip = (PropertySymbol)members.First(member => member.Name == "I.P");
CheckPropertyAccessibility(ip, Accessibility.Private, Accessibility.Private, Accessibility.Private);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
private static void CheckPropertyAccessibility(PropertySymbol property, Accessibility propertyAccessibility, Accessibility getterAccessibility, Accessibility setterAccessibility)
{
var type = property.TypeWithAnnotations;
Assert.NotEqual(Microsoft.Cci.PrimitiveTypeCode.Void, type.PrimitiveTypeCode);
Assert.Equal(propertyAccessibility, property.DeclaredAccessibility);
CheckPropertyAccessorAccessibility(property, propertyAccessibility, property.GetMethod, getterAccessibility);
CheckPropertyAccessorAccessibility(property, propertyAccessibility, property.SetMethod, setterAccessibility);
}
private static void CheckPropertyAccessorAccessibility(PropertySymbol property, Accessibility propertyAccessibility, MethodSymbol accessor, Accessibility accessorAccessibility)
{
if (accessor == null)
{
Assert.Equal(Accessibility.NotApplicable, accessorAccessibility);
}
else
{
var containingType = property.ContainingType;
Assert.Equal(property, accessor.AssociatedSymbol);
Assert.Equal(containingType, accessor.ContainingType);
Assert.Equal(containingType, accessor.ContainingSymbol);
var method = containingType.GetMembers(accessor.Name).Single();
Assert.Equal(method, accessor);
Assert.Equal(accessorAccessibility, accessor.DeclaredAccessibility);
}
}
// Property/method override should succeed (and should reference
// the correct base method, even if there is a method/property
// with the same name in an intermediate class.
[WorkItem(538720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538720")]
[Fact]
public void TestPropertyOverrideGet()
{
PropertyOverrideGet(@"
class A
{
public virtual int P { get { return 0; } }
}
class B : A
{
public virtual int get_P() { return 0; }
}
class C : B
{
public override int P { get { return 0; } }
}
");
PropertyOverrideGet(@"
class A
{
public virtual int get_P() { return 0; }
}
class B : A
{
public virtual int P { get { return 0; } }
}
class C : B
{
public override int get_P() { return 0; }
}
");
}
private void PropertyOverrideGet(string source)
{
Action<ModuleSymbol> validator = module =>
{
var typeA = module.GlobalNamespace.GetTypeMembers("A").Single();
Assert.NotNull(typeA);
var getMethodA = (MethodSymbol)typeA.GetMembers("get_P").Single();
Assert.NotNull(getMethodA);
Assert.True(getMethodA.IsVirtual);
Assert.False(getMethodA.IsOverride);
var typeC = module.GlobalNamespace.GetTypeMembers("C").Single();
Assert.NotNull(typeC);
var getMethodC = (MethodSymbol)typeC.GetMembers("get_P").Single();
Assert.NotNull(getMethodC);
Assert.False(getMethodC.IsVirtual);
Assert.True(getMethodC.IsOverride);
Assert.Same(getMethodC.OverriddenMethod, getMethodA);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void AutoProperties()
{
string source = @"
class A
{
public int P { get; private set; }
internal int Q { get; set; }
}
class B<T>
{
protected internal T P { get; set; }
}
class C : B<string>
{
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var classA = module.GlobalNamespace.GetTypeMember("A");
var p = classA.GetProperty("P");
VerifyAutoProperty(p, isFromSource);
var q = classA.GetProperty("Q");
VerifyAutoProperty(q, isFromSource);
var classC = module.GlobalNamespace.GetTypeMembers("C").Single();
p = classC.BaseType().GetProperty("P");
VerifyAutoProperty(p, isFromSource);
Assert.Equal(SpecialType.System_String, p.Type.SpecialType);
Assert.Equal(p.GetMethod.AssociatedSymbol, p);
};
CompileAndVerify(
source,
sourceSymbolValidator: validator(true),
symbolValidator: validator(false),
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
}
private static void VerifyAutoProperty(PropertySymbol property, bool isFromSource)
{
if (isFromSource)
{
if (property is SourcePropertySymbol sourceProperty)
{
Assert.True(sourceProperty.IsAutoPropertyWithGetAccessor);
}
}
else
{
var backingField = property.ContainingType.GetField(GeneratedNames.MakeBackingFieldName(property.Name));
var attribute = backingField.GetAttributes().Single();
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attribute.AttributeClass.ToTestDisplayString());
Assert.Empty(attribute.AttributeConstructor.Parameters);
}
VerifyAutoPropertyAccessor(property, property.GetMethod);
VerifyAutoPropertyAccessor(property, property.SetMethod);
}
private static void VerifyAutoPropertyAccessor(PropertySymbol property, MethodSymbol accessor)
{
if (accessor != null)
{
var method = property.ContainingType.GetMembers(accessor.Name).Single();
Assert.Equal(method, accessor);
Assert.Equal(accessor.AssociatedSymbol, property);
Assert.False(accessor.IsImplicitlyDeclared, "MethodSymbol.IsImplicitlyDeclared should be false for auto property accessors");
}
}
[Fact]
public void EmptyEnum()
{
string source = "enum E {}";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("E").Single();
CheckEnumType(type, Accessibility.Internal, SpecialType.System_Int32);
Assert.Equal(1, type.GetMembers().Length);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
[Fact]
public void NonEmptyEnum()
{
string source =
@"enum E : short
{
A,
B = 0x02,
C,
D,
E = B | D,
F = C,
G,
}
";
Action<ModuleSymbol> validator = module =>
{
var type = module.GlobalNamespace.GetTypeMembers("E").Single();
CheckEnumType(type, Accessibility.Internal, SpecialType.System_Int16);
Assert.Equal(8, type.GetMembers().Length);
CheckEnumConstant(type, "A", (short)0);
CheckEnumConstant(type, "B", (short)2);
CheckEnumConstant(type, "C", (short)3);
CheckEnumConstant(type, "D", (short)4);
CheckEnumConstant(type, "E", (short)6);
CheckEnumConstant(type, "F", (short)3);
CheckEnumConstant(type, "G", (short)4);
};
CompileAndVerify(source: source, sourceSymbolValidator: validator, symbolValidator: validator);
}
private void CheckEnumConstant(NamedTypeSymbol type, string name, object value)
{
var field = type.GetMembers(name).SingleOrDefault() as FieldSymbol;
Assert.NotNull(field);
Assert.True(field.IsStatic);
Assert.True(field.IsConst);
// TODO: DeclaredAccessibility should be NotApplicable.
//Assert.Equal(field.DeclaredAccessibility, Accessibility.NotApplicable);
Assert.Equal(field.Type, type);
Assert.Equal(field.ConstantValue, value);
var sourceType = type as SourceNamedTypeSymbol;
if ((object)sourceType != null)
{
var fieldDefinition = (Microsoft.Cci.IFieldDefinition)field.GetCciAdapter();
Assert.False(fieldDefinition.IsSpecialName);
Assert.False(fieldDefinition.IsRuntimeSpecial);
}
}
private void CheckEnumType(NamedTypeSymbol type, Accessibility declaredAccessibility, SpecialType underlyingType)
{
Assert.Equal(SpecialType.System_Enum, type.BaseType().SpecialType);
Assert.Equal(type.EnumUnderlyingType.SpecialType, underlyingType);
Assert.Equal(type.DeclaredAccessibility, declaredAccessibility);
Assert.True(type.IsSealed);
// value__ field should not be exposed from type, even though it is public,
// since we want to prevent source from accessing the field directly.
var field = type.GetMembers(WellKnownMemberNames.EnumBackingFieldName).SingleOrDefault() as FieldSymbol;
Assert.Null(field);
var sourceType = type as SourceNamedTypeSymbol;
if ((object)sourceType != null)
{
field = sourceType.EnumValueField;
Assert.NotNull(field);
Assert.Equal(field.Name, WellKnownMemberNames.EnumBackingFieldName);
Assert.False(field.IsStatic);
Assert.False(field.IsConst);
Assert.False(field.IsReadOnly);
Assert.Equal(Accessibility.Public, field.DeclaredAccessibility); // Dev10: value__ is public
Assert.Equal(field.Type, type.EnumUnderlyingType);
var module = new PEAssemblyBuilder((SourceAssemblySymbol)sourceType.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary,
GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>());
var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var typeDefinition = (Microsoft.Cci.ITypeDefinition)type.GetCciAdapter();
var fieldDefinition = typeDefinition.GetFields(context).First();
Assert.Same(fieldDefinition.GetInternalSymbol(), field); // Dev10: value__ field is the first field.
Assert.True(fieldDefinition.IsSpecialName);
Assert.True(fieldDefinition.IsRuntimeSpecial);
context.Diagnostics.Verify();
}
}
[Fact]
public void GenericMethods()
{
string source = @"
public class A
{
public static void Main()
{
System.Console.WriteLine(""GenericMethods"");
//B.Test<int>();
//C<int>.Test<int>();
}
}
public class B
{
public static void Test<T>()
{
System.Console.WriteLine(""Test<T>"");
}
}
public class C<T>
{
public static void Test<S>()
{
System.Console.WriteLine(""C<T>.Test<S>"");
}
}
";
CompileAndVerify(source, expectedOutput: "GenericMethods\r\n");
}
[Fact]
public void GenericMethods2()
{
string source = @"
class A
{
public static void Main()
{
TC1 x = new TC1();
System.Console.WriteLine(x.GetType());
TC2<byte> y = new TC2<byte>();
System.Console.WriteLine(y.GetType());
TC3<byte>.TC4 z = new TC3<byte>.TC4();
System.Console.WriteLine(z.GetType());
}
}
class TC1
{
void TM1<T1>()
{
TM1<T1>();
}
void TM2<T2>()
{
TM2<int>();
}
}
class TC2<T3>
{
void TM3<T4>()
{
TM3<T4>();
TM3<T4>();
}
void TM4<T5>()
{
TM4<int>();
TM4<int>();
}
static void TM5<T6>(T6 x)
{
TC2<int>.TM5(x);
}
static void TM6<T7>(T7 x)
{
TC2<int>.TM6(1);
}
void TM9()
{
TM9();
TM9();
}
}
class TC3<T8>
{
public class TC4
{
void TM7<T9>()
{
TM7<T9>();
TM7<int>();
}
static void TM8<T10>(T10 x)
{
TC3<int>.TC4.TM8(x);
TC3<int>.TC4.TM8(1);
}
}
}
";
var verifier = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput:
@"TC1
TC2`1[System.Byte]
TC3`1+TC4[System.Byte]
");
verifier.VerifyIL("TC1.TM1<T1>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC1.TM1<T1>()""
IL_0006: ret
}
");
verifier.VerifyIL("TC1.TM2<T2>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC1.TM2<int>()""
IL_0006: ret
}
");
verifier.VerifyIL("TC2<T3>.TM3<T4>",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<T3>.TM3<T4>()""
IL_0006: ldarg.0
IL_0007: call ""void TC2<T3>.TM3<T4>()""
IL_000c: ret
}
");
verifier.VerifyIL("TC2<T3>.TM4<T5>",
@"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<T3>.TM4<int>()""
IL_0006: ldarg.0
IL_0007: call ""void TC2<T3>.TM4<int>()""
IL_000c: ret
}
");
verifier.VerifyIL("TC2<T3>.TM5<T6>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""void TC2<int>.TM5<T6>(T6)""
IL_0006: ret
}
");
verifier.VerifyIL("TC2<T3>.TM6<T7>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void TC2<int>.TM6<int>(int)""
IL_0006: ret
}
");
}
[Fact]
public void Generics3()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
C1<Byte, Byte> x1 = new C1<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte> x2 = new C1<Byte, Byte>.C2<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte> x3 = new C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>();
C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>.C4<Byte> x4 = new C1<Byte, Byte>.C2<Byte, Byte>.C3<Byte, Byte>.C4<Byte>();
C1<Byte, Byte>.C5 x5 = new C1<Byte, Byte>.C5();
}
}
class C1<C1T1, C1T2>
{
public class C2<C2T1, C2T2>
{
public class C3<C3T1, C3T2> where C3T2 : C1T1
{
public class C4<C4T1>
{
}
}
public C1<int, C2T2>.C5 V1;
public C1<C2T1, C2T2>.C5 V2;
public C1<int, int>.C5 V3;
public C2<Byte, Byte> V4;
public C1<C1T2, C1T1>.C2<C2T1, C2T2> V5;
public C1<C1T2, C1T1>.C2<C2T2, C2T1> V6;
public C1<C1T2, C1T1>.C2<Byte, int> V7;
public C2<C2T1, C2T2> V8;
public C2<Byte, C2T2> V9;
void Test12(C2<int, int> x)
{
C1<C1T1, C1T2>.C2<Byte, int> y = x.V9;
}
void Test11(C1<int, int>.C2<Byte, Byte> x)
{
C1<int, int>.C2<Byte, Byte> y = x.V8;
}
void Test6(C1<C1T2, C1T1>.C2<C2T1, C2T2> x)
{
C1<C1T1, C1T2>.C2<C2T1, C2T2> y = x.V5;
}
void Test7(C1<C1T2, C1T1>.C2<C2T2, C2T1> x)
{
C1<C1T1, C1T2>.C2<C2T1, C2T2> y = x.V6;
}
void Test8(C1<C1T2, C1T1>.C2<C2T2, C2T1> x)
{
C1<C1T1, C1T2>.C2<Byte, int> y = x.V7;
}
void Test9(C1<int, Byte>.C2<C2T2, C2T1> x)
{
C1<Byte, int>.C2<Byte, int> y = x.V7;
}
void Test10(C1<C1T1, C1T2>.C2<C2T2, C2T1> x)
{
C1<C1T2, C1T1>.C2<Byte, int> y = x.V7;
}
}
public class C5
{
}
void Test1(C2<C1T1, int> x)
{
C1<int, int>.C5 y = x.V1;
}
void Test2(C2<C1T1, C1T2> x)
{
C5 y = x.V2;
}
void Test3(C2<C1T2, C1T1> x)
{
C1<int, int>.C5 y = x.V3;
}
void Test4(C1<int, int>.C2<C1T1, C1T2> x)
{
C1<int, int>.C2<Byte, Byte> y = x.V4;
}
}
";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_UnsupportedOrdering1()
{
CompileAndVerify(@"
public class E
{
public struct N2
{
public N3 n1;
}
public struct N3
{
}
N2 n2;
}
");
}
[Fact]
public void RefEmit_UnsupportedOrdering1_EP()
{
string source = @"
public class E
{
public struct N2
{
public N3 n1;
}
public struct N3
{
}
N2 n2;
public static void Main()
{
System.Console.Write(1234);
}
}";
CompileAndVerify(source, expectedOutput: @"1234");
}
[Fact]
public void RefEmit_UnsupportedOrdering2()
{
CompileAndVerify(@"
class B<T> where T : A {}
class A : B<A> {}
");
}
[Fact]
public void RefEmit_MembersOfOpenGenericType()
{
CompileAndVerify(@"
class C<T>
{
void goo()
{
System.Collections.Generic.Dictionary<int, T> d = new System.Collections.Generic.Dictionary<int, T>();
}
}
");
}
[Fact]
public void RefEmit_ListOfValueTypes()
{
string source = @"
using System.Collections.Generic;
class A
{
struct S { }
List<S> f;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedNestedSelfReference()
{
string source = @"
class A<T>
{
class B {
}
A<int>.B x;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedNestedGenericSelfReference()
{
string source = @"
class A<T>
{
public class B<S> {
public class C<U,V> {
}
}
A<int>.B<double>.C<string, bool> x;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Cycle()
{
string source = @"
public class B : I<C> { }
public class C : I<B> { }
public interface I<T> { }
";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_SpecializedMemberReference()
{
string source = @"
class A<T>
{
public A()
{
A<int>.method();
int a = A<string>.field;
new A<double>();
}
public static void method()
{
}
public static int field;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_NestedGenericTypeReferences()
{
string source = @"
class A<T>
{
public class H<S>
{
A<T>.H<S> x;
}
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Ordering2()
{
// order:
// E <(value type field) E.C.N2 <(value type field) N3
string source = @"
public class E
{
public class C {
public struct N2
{
public N3 n1;
}
}
C.N2 n2;
}
public struct N3
{
E f;
int g;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_Ordering3()
{
string source = @"
using System.Collections.Generic;
public class E
{
public struct N2
{
public List<N3> n1; // E.N2 doesn't depend on E.N3 since List<> isn't a value type
}
public struct N3
{
}
N2 n2;
}";
CompileAndVerify(source);
}
[Fact]
public void RefEmit_IL1()
{
CompileAndVerify(@"
class C
{
public static void Main()
{
int i = 0, j, k = 2147483647;
long l = 0, m = 9200000000000000000L;
int b = -10;
byte c = 200;
float f = 3.14159F;
double d = 2.71828;
string s = ""abcdef"";
bool x = true;
System.Console.WriteLine(i);
System.Console.WriteLine(k);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(f);
System.Console.WriteLine(d);
System.Console.WriteLine(s);
System.Console.WriteLine(x);
}
}
", expectedOutput: @"
0
2147483647
-10
200
3.14159
2.71828
abcdef
True
");
}
[WorkItem(540581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540581")]
[Fact]
public void RefEmit_DependencyGraphAndCachedTypeReferences()
{
var source = @"
using System;
interface I1<T>
{
void Method(T x);
}
interface I2<U>
{
void Method(U x);
}
interface I3<W> : I1<W>, I2<W>
{
void Method(W x);
}
class Implicit2 : I3<string> // Implicit2 depends on I3<string>
{
public void Method(string x) { }
}
class Test
{
public static void Main()
{
I3<string> i = new Implicit2();
}
}
";
// If I3<string> in Main body is resolved first and stored in a cache,
// the fact that Implicit2 depends on I3<string> isn't recorded if we pull
// I3<string> from cache at the beginning of ResolveType method.
CompileAndVerify(source);
}
[Fact]
public void CheckRef()
{
string source = @"
public abstract class C
{
public abstract int M(int x, ref int y, out int z);
}
";
CompileAndVerify(source, symbolValidator: module =>
{
var global = module.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
var m = c.GetMembers("M").Single() as MethodSymbol;
Assert.Equal(RefKind.None, m.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, m.Parameters[1].RefKind);
Assert.Equal(RefKind.Out, m.Parameters[2].RefKind);
});
}
[Fact]
public void OutArgument()
{
string source = @"
class C
{
static void Main() { double d; double.TryParse(null, out d); }
}
";
CompileAndVerify(source);
}
[Fact]
public void CreateInstance()
{
string source = @"
class C
{
static void Main() { System.Activator.CreateInstance<int>(); }
}
";
CompileAndVerify(source);
}
[Fact]
public void DelegateRoundTrip()
{
string source = @"delegate int MyDel(
int x,
// ref int y, // commented out until 4264 is fixed.
// out int z, // commented out until 4264 is fixed.
int w);";
CompileAndVerify(source, symbolValidator: module =>
{
var global = module.GlobalNamespace;
var myDel = global.GetTypeMembers("MyDel", 0).Single() as NamedTypeSymbol;
var invoke = myDel.DelegateInvokeMethod;
var beginInvoke = myDel.GetMembers("BeginInvoke").Single() as MethodSymbol;
Assert.Equal(invoke.Parameters.Length + 2, beginInvoke.Parameters.Length);
Assert.Equal(TypeKind.Interface, beginInvoke.ReturnType.TypeKind);
Assert.Equal("System.IAsyncResult", beginInvoke.ReturnType.ToTestDisplayString());
for (int i = 0; i < invoke.Parameters.Length; i++)
{
Assert.Equal(invoke.Parameters[i].Type, beginInvoke.Parameters[i].Type);
Assert.Equal(invoke.Parameters[i].RefKind, beginInvoke.Parameters[i].RefKind);
}
Assert.Equal("System.AsyncCallback", beginInvoke.Parameters[invoke.Parameters.Length].Type.ToTestDisplayString());
Assert.Equal("System.Object", beginInvoke.Parameters[invoke.Parameters.Length + 1].Type.ToTestDisplayString());
var invokeReturn = invoke.ReturnType;
var endInvoke = myDel.GetMembers("EndInvoke").Single() as MethodSymbol;
var endInvokeReturn = endInvoke.ReturnType;
Assert.Equal(invokeReturn, endInvokeReturn);
int k = 0;
for (int i = 0; i < invoke.Parameters.Length; i++)
{
if (invoke.Parameters[i].RefKind != RefKind.None)
{
Assert.Equal(invoke.Parameters[i].TypeWithAnnotations, endInvoke.Parameters[k].TypeWithAnnotations);
Assert.Equal(invoke.Parameters[i].RefKind, endInvoke.Parameters[k++].RefKind);
}
}
Assert.Equal("System.IAsyncResult", endInvoke.Parameters[k++].Type.ToTestDisplayString());
Assert.Equal(k, endInvoke.Parameters.Length);
});
}
[Fact]
public void StaticClassRoundTrip()
{
string source = @"
public static class C
{
private static string msg = ""Hello"";
private static void Goo()
{
System.Console.WriteLine(msg);
}
public static void Main()
{
Goo();
}
}
";
CompileAndVerify(source,
symbolValidator: module =>
{
var global = module.GlobalNamespace;
var classC = global.GetMember<NamedTypeSymbol>("C");
Assert.True(classC.IsStatic, "Expected C to be static");
Assert.False(classC.IsAbstract, "Expected C to be non-abstract"); //even though it is abstract in metadata
Assert.False(classC.IsSealed, "Expected C to be non-sealed"); //even though it is sealed in metadata
Assert.Equal(0, classC.GetMembers(WellKnownMemberNames.InstanceConstructorName).Length); //since C is static
Assert.Equal(0, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); //since we don't import private members
});
}
[Fact]
public void DoNotImportInternalMembers()
{
string sources =
@"public class Fields
{
public int Public;
internal int Internal;
}
public class Methods
{
public void Public() {}
internal void Internal() {}
}";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => (ModuleSymbol m) =>
{
CheckInternalMembers(m.GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource);
CheckInternalMembers(m.GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource);
};
CompileAndVerify(sources, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void Issue4695()
{
string source = @"
using System;
class Program
{
sealed class Cache
{
abstract class BucketwiseBase<TArg> where TArg : class
{
internal abstract void Default(TArg arg);
}
class BucketwiseBase<TAccumulator, TArg> : BucketwiseBase<TArg> where TArg : class
{
internal override void Default(TArg arg = null) { }
}
public string GetAll()
{
new BucketwiseBase<object, object>().Default(); // Bad image format thrown here on legacy compiler
return ""OK"";
}
}
static void Main(string[] args)
{
Console.WriteLine(new Cache().GetAll());
}
}
";
CompileAndVerify(source, expectedOutput: "OK");
}
private void CheckInternalMembers(NamedTypeSymbol type, bool isFromSource)
{
Assert.NotNull(type.GetMembers("Public").SingleOrDefault());
var member = type.GetMembers("Internal").SingleOrDefault();
if (isFromSource)
Assert.NotNull(member);
else
Assert.Null(member);
}
[WorkItem(90, "https://github.com/dotnet/roslyn/issues/90")]
[Fact]
public void EmitWithNoResourcesAllPlatforms()
{
var comp = CreateCompilation("class Test { static void Main() { } }");
VerifyEmitWithNoResources(comp, Platform.AnyCpu);
VerifyEmitWithNoResources(comp, Platform.AnyCpu32BitPreferred);
VerifyEmitWithNoResources(comp, Platform.Arm); // broken before fix
VerifyEmitWithNoResources(comp, Platform.Itanium); // broken before fix
VerifyEmitWithNoResources(comp, Platform.X64); // broken before fix
VerifyEmitWithNoResources(comp, Platform.X86);
}
private void VerifyEmitWithNoResources(CSharpCompilation comp, Platform platform)
{
var options = TestOptions.ReleaseExe.WithPlatform(platform);
CompileAndVerify(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_" + platform.ToString()).WithOptions(options));
}
[Fact]
public unsafe void PEHeaders1()
{
var options = EmitOptions.Default.WithFileAlignment(0x2000);
var syntax = SyntaxFactory.ParseSyntaxTree(@"class C {}", TestOptions.Regular);
var peStream = CreateCompilationWithMscorlib40(
syntax,
options: TestOptions.ReleaseDll.WithDeterministic(true),
assemblyName: "46B9C2B2-B7A0-45C5-9EF9-28DDF739FD9E").EmitToStream(options);
peStream.Position = 0;
var peReader = new PEReader(peStream);
var peHeaders = peReader.PEHeaders;
var peHeader = peHeaders.PEHeader;
var coffHeader = peHeaders.CoffHeader;
var corHeader = peHeaders.CorHeader;
Assert.Equal(PEMagic.PE32, peHeader.Magic);
Assert.Equal(0x0000237E, peHeader.AddressOfEntryPoint);
Assert.Equal(0x00002000, peHeader.BaseOfCode);
Assert.Equal(0x00004000, peHeader.BaseOfData);
Assert.Equal(0x00002000, peHeader.SizeOfHeaders);
Assert.Equal(0x00002000, peHeader.SizeOfCode);
Assert.Equal(0x00001000u, peHeader.SizeOfHeapCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfHeapReserve);
Assert.Equal(0x00006000, peHeader.SizeOfImage);
Assert.Equal(0x00002000, peHeader.SizeOfInitializedData);
Assert.Equal(0x00001000u, peHeader.SizeOfStackCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfStackReserve);
Assert.Equal(0, peHeader.SizeOfUninitializedData);
Assert.Equal(Subsystem.WindowsCui, peHeader.Subsystem);
Assert.Equal(DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware, peHeader.DllCharacteristics);
Assert.Equal(0u, peHeader.CheckSum);
Assert.Equal(0x2000, peHeader.FileAlignment);
Assert.Equal(0x10000000u, peHeader.ImageBase);
Assert.Equal(0x2000, peHeader.SectionAlignment);
Assert.Equal(0, peHeader.MajorImageVersion);
Assert.Equal(0, peHeader.MinorImageVersion);
Assert.Equal(0x30, peHeader.MajorLinkerVersion);
Assert.Equal(0, peHeader.MinorLinkerVersion);
Assert.Equal(4, peHeader.MajorOperatingSystemVersion);
Assert.Equal(0, peHeader.MinorOperatingSystemVersion);
Assert.Equal(4, peHeader.MajorSubsystemVersion);
Assert.Equal(0, peHeader.MinorSubsystemVersion);
Assert.Equal(16, peHeader.NumberOfRvaAndSizes);
Assert.Equal(0x2000, peHeader.SizeOfHeaders);
Assert.Equal(0x4000, peHeader.BaseRelocationTableDirectory.RelativeVirtualAddress);
Assert.Equal(0xc, peHeader.BaseRelocationTableDirectory.Size);
Assert.Equal(0, peHeader.BoundImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BoundImportTableDirectory.Size);
Assert.Equal(0, peHeader.CertificateTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CertificateTableDirectory.Size);
Assert.Equal(0, peHeader.CopyrightTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CopyrightTableDirectory.Size);
Assert.Equal(0x2008, peHeader.CorHeaderTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x48, peHeader.CorHeaderTableDirectory.Size);
Assert.Equal(0x2310, peHeader.DebugTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x1C, peHeader.DebugTableDirectory.Size);
Assert.Equal(0, peHeader.ExceptionTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExceptionTableDirectory.Size);
Assert.Equal(0, peHeader.ExportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExportTableDirectory.Size);
Assert.Equal(0x2000, peHeader.ImportAddressTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x8, peHeader.ImportAddressTableDirectory.Size);
Assert.Equal(0x232C, peHeader.ImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x4f, peHeader.ImportTableDirectory.Size);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.Size);
Assert.Equal(0, peHeader.ResourceTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ResourceTableDirectory.Size);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.Size);
int importAddressTableDirectoryOffset;
Assert.True(peHeaders.TryGetDirectoryOffset(peHeader.ImportAddressTableDirectory, out importAddressTableDirectoryOffset));
Assert.Equal(0x2000, importAddressTableDirectoryOffset);
var importAddressTableDirectoryBytes = new byte[peHeader.ImportAddressTableDirectory.Size];
peStream.Position = importAddressTableDirectoryOffset;
peStream.Read(importAddressTableDirectoryBytes, 0, importAddressTableDirectoryBytes.Length);
AssertEx.Equal(new byte[]
{
0x60, 0x23, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}, importAddressTableDirectoryBytes);
int importTableDirectoryOffset;
Assert.True(peHeaders.TryGetDirectoryOffset(peHeader.ImportTableDirectory, out importTableDirectoryOffset));
Assert.Equal(0x232C, importTableDirectoryOffset);
var importTableDirectoryBytes = new byte[peHeader.ImportTableDirectory.Size];
peStream.Position = importTableDirectoryOffset;
peStream.Read(importTableDirectoryBytes, 0, importTableDirectoryBytes.Length);
AssertEx.Equal(new byte[]
{
0x54, 0x23, 0x00, 0x00, // RVA
0x00, 0x00, 0x00, 0x00, // 0
0x00, 0x00, 0x00, 0x00, // 0
0x6E, 0x23, 0x00, 0x00, // name RVA
0x00, 0x20, 0x00, 0x00, // ImportAddressTableDirectory RVA
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x60, 0x23, 0x00, 0x00, // hint RVA
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, // hint
(byte)'_', (byte)'C', (byte)'o', (byte)'r', (byte)'D', (byte)'l', (byte)'l', (byte)'M', (byte)'a', (byte)'i', (byte)'n', 0x00,
(byte)'m', (byte)'s', (byte)'c', (byte)'o', (byte)'r', (byte)'e', (byte)'e', (byte)'.', (byte)'d', (byte)'l', (byte)'l', 0x00,
0x00
}, importTableDirectoryBytes);
var entryPointSectionIndex = peHeaders.GetContainingSectionIndex(peHeader.AddressOfEntryPoint);
Assert.Equal(0, entryPointSectionIndex);
peStream.Position = peHeaders.SectionHeaders[0].PointerToRawData + peHeader.AddressOfEntryPoint - peHeaders.SectionHeaders[0].VirtualAddress;
byte[] startupStub = new byte[8];
peStream.Read(startupStub, 0, startupStub.Length);
AssertEx.Equal(new byte[] { 0xFF, 0x25, 0x00, 0x20, 0x00, 0x10, 0x00, 0x00 }, startupStub);
Assert.Equal(Characteristics.Dll | Characteristics.LargeAddressAware | Characteristics.ExecutableImage, coffHeader.Characteristics);
Assert.Equal(Machine.I386, coffHeader.Machine);
Assert.Equal(2, coffHeader.NumberOfSections);
Assert.Equal(0, coffHeader.NumberOfSymbols);
Assert.Equal(0, coffHeader.PointerToSymbolTable);
Assert.Equal(0xe0, coffHeader.SizeOfOptionalHeader);
Assert.Equal(-609278808, coffHeader.TimeDateStamp);
Assert.Equal(0, corHeader.EntryPointTokenOrRelativeVirtualAddress);
Assert.Equal(CorFlags.ILOnly, corHeader.Flags);
Assert.Equal(2, corHeader.MajorRuntimeVersion);
Assert.Equal(5, corHeader.MinorRuntimeVersion);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.Size);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.Size);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.Size);
Assert.Equal(0x2058, corHeader.MetadataDirectory.RelativeVirtualAddress);
Assert.Equal(0x02b8, corHeader.MetadataDirectory.Size);
Assert.Equal(0, corHeader.ResourcesDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ResourcesDirectory.Size);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.Size);
Assert.Equal(0, corHeader.VtableFixupsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.VtableFixupsDirectory.Size);
var sections = peHeaders.SectionHeaders;
Assert.Equal(2, sections.Length);
Assert.Equal(".text", sections[0].Name);
Assert.Equal(0, sections[0].NumberOfLineNumbers);
Assert.Equal(0, sections[0].NumberOfRelocations);
Assert.Equal(0, sections[0].PointerToLineNumbers);
Assert.Equal(0x2000, sections[0].PointerToRawData);
Assert.Equal(0, sections[0].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead, sections[0].SectionCharacteristics);
Assert.Equal(0x2000, sections[0].SizeOfRawData);
Assert.Equal(0x2000, sections[0].VirtualAddress);
Assert.Equal(900, sections[0].VirtualSize);
Assert.Equal(".reloc", sections[1].Name);
Assert.Equal(0, sections[1].NumberOfLineNumbers);
Assert.Equal(0, sections[1].NumberOfRelocations);
Assert.Equal(0, sections[1].PointerToLineNumbers);
Assert.Equal(0x4000, sections[1].PointerToRawData);
Assert.Equal(0, sections[1].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable | SectionCharacteristics.MemRead, sections[1].SectionCharacteristics);
Assert.Equal(0x2000, sections[1].SizeOfRawData);
Assert.Equal(0x4000, sections[1].VirtualAddress);
Assert.Equal(12, sections[1].VirtualSize);
var relocBlock = peReader.GetSectionData(sections[1].VirtualAddress);
var relocBytes = new byte[sections[1].VirtualSize];
Marshal.Copy((IntPtr)relocBlock.Pointer, relocBytes, 0, relocBytes.Length);
AssertEx.Equal(new byte[] { 0, 0x20, 0, 0, 0x0c, 0, 0, 0, 0x80, 0x33, 0, 0 }, relocBytes);
}
[Fact]
public void PEHeaders2()
{
var options = EmitOptions.Default.
WithFileAlignment(512).
WithBaseAddress(0x123456789ABCDEF).
WithHighEntropyVirtualAddressSpace(true).
WithSubsystemVersion(SubsystemVersion.WindowsXP);
var syntax = SyntaxFactory.ParseSyntaxTree(@"class C { static void Main() { } }", TestOptions.Regular);
var peStream = CreateCompilationWithMscorlib40(
syntax,
options: TestOptions.DebugExe.WithPlatform(Platform.X64).WithDeterministic(true),
assemblyName: "B37A4FCD-ED76-4924-A2AD-298836056E00").EmitToStream(options);
peStream.Position = 0;
var peHeaders = new PEHeaders(peStream);
var peHeader = peHeaders.PEHeader;
var coffHeader = peHeaders.CoffHeader;
var corHeader = peHeaders.CorHeader;
Assert.Equal(PEMagic.PE32Plus, peHeader.Magic);
Assert.Equal(0x00000000, peHeader.AddressOfEntryPoint);
Assert.Equal(0x00002000, peHeader.BaseOfCode);
Assert.Equal(0x00000000, peHeader.BaseOfData);
Assert.Equal(0x00000200, peHeader.SizeOfHeaders);
Assert.Equal(0x00000400, peHeader.SizeOfCode);
Assert.Equal(0x00002000u, peHeader.SizeOfHeapCommit);
Assert.Equal(0x00100000u, peHeader.SizeOfHeapReserve);
Assert.Equal(0x00004000, peHeader.SizeOfImage);
Assert.Equal(0x00000000, peHeader.SizeOfInitializedData);
Assert.Equal(0x00004000u, peHeader.SizeOfStackCommit);
Assert.Equal(0x0400000u, peHeader.SizeOfStackReserve);
Assert.Equal(0, peHeader.SizeOfUninitializedData);
Assert.Equal(Subsystem.WindowsCui, peHeader.Subsystem);
Assert.Equal(0u, peHeader.CheckSum);
Assert.Equal(0x200, peHeader.FileAlignment);
Assert.Equal(0x0123456789ac0000u, peHeader.ImageBase);
Assert.Equal(0x2000, peHeader.SectionAlignment);
Assert.Equal(0, peHeader.MajorImageVersion);
Assert.Equal(0, peHeader.MinorImageVersion);
Assert.Equal(0x30, peHeader.MajorLinkerVersion);
Assert.Equal(0, peHeader.MinorLinkerVersion);
Assert.Equal(4, peHeader.MajorOperatingSystemVersion);
Assert.Equal(0, peHeader.MinorOperatingSystemVersion);
Assert.Equal(5, peHeader.MajorSubsystemVersion);
Assert.Equal(1, peHeader.MinorSubsystemVersion);
Assert.Equal(16, peHeader.NumberOfRvaAndSizes);
Assert.Equal(0x200, peHeader.SizeOfHeaders);
Assert.Equal(0, peHeader.BaseRelocationTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BaseRelocationTableDirectory.Size);
Assert.Equal(0, peHeader.BoundImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.BoundImportTableDirectory.Size);
Assert.Equal(0, peHeader.CertificateTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CertificateTableDirectory.Size);
Assert.Equal(0, peHeader.CopyrightTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.CopyrightTableDirectory.Size);
Assert.Equal(0x2000, peHeader.CorHeaderTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x48, peHeader.CorHeaderTableDirectory.Size);
Assert.Equal(0x2324, peHeader.DebugTableDirectory.RelativeVirtualAddress);
Assert.Equal(0x1C, peHeader.DebugTableDirectory.Size);
Assert.Equal(0, peHeader.ExceptionTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExceptionTableDirectory.Size);
Assert.Equal(0, peHeader.ExportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ExportTableDirectory.Size);
Assert.Equal(0, peHeader.ImportAddressTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ImportAddressTableDirectory.Size);
Assert.Equal(0, peHeader.ImportTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ImportTableDirectory.Size);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.LoadConfigTableDirectory.Size);
Assert.Equal(0, peHeader.ResourceTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ResourceTableDirectory.Size);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, peHeader.ThreadLocalStorageTableDirectory.Size);
Assert.Equal(Characteristics.LargeAddressAware | Characteristics.ExecutableImage, coffHeader.Characteristics);
Assert.Equal(Machine.Amd64, coffHeader.Machine);
Assert.Equal(1, coffHeader.NumberOfSections);
Assert.Equal(0, coffHeader.NumberOfSymbols);
Assert.Equal(0, coffHeader.PointerToSymbolTable);
Assert.Equal(240, coffHeader.SizeOfOptionalHeader);
Assert.Equal(-1823671907, coffHeader.TimeDateStamp);
Assert.Equal(0x06000001, corHeader.EntryPointTokenOrRelativeVirtualAddress);
Assert.Equal(CorFlags.ILOnly, corHeader.Flags);
Assert.Equal(2, corHeader.MajorRuntimeVersion);
Assert.Equal(5, corHeader.MinorRuntimeVersion);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.CodeManagerTableDirectory.Size);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ExportAddressTableJumpsDirectory.Size);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ManagedNativeHeaderDirectory.Size);
Assert.Equal(0x2054, corHeader.MetadataDirectory.RelativeVirtualAddress);
Assert.Equal(0x02d0, corHeader.MetadataDirectory.Size);
Assert.Equal(0, corHeader.ResourcesDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.ResourcesDirectory.Size);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.StrongNameSignatureDirectory.Size);
Assert.Equal(0, corHeader.VtableFixupsDirectory.RelativeVirtualAddress);
Assert.Equal(0, corHeader.VtableFixupsDirectory.Size);
var sections = peHeaders.SectionHeaders;
Assert.Equal(1, sections.Length);
Assert.Equal(".text", sections[0].Name);
Assert.Equal(0, sections[0].NumberOfLineNumbers);
Assert.Equal(0, sections[0].NumberOfRelocations);
Assert.Equal(0, sections[0].PointerToLineNumbers);
Assert.Equal(0x200, sections[0].PointerToRawData);
Assert.Equal(0, sections[0].PointerToRelocations);
Assert.Equal(SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead, sections[0].SectionCharacteristics);
Assert.Equal(0x400, sections[0].SizeOfRawData);
Assert.Equal(0x2000, sections[0].VirtualAddress);
Assert.Equal(832, sections[0].VirtualSize);
}
[Fact]
public void InParametersShouldHaveMetadataIn_TypeMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
public void M(in int a, [In]in int b, [In]int c, int d) {}
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_IndexerMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
public int this[in int a, [In]in int b, [In]int c, int d] => 0;
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("get_Item").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_Delegates()
{
var text = @"
using System.Runtime.InteropServices;
public delegate void D(in int a, [In]in int b, [In]int c, int d);
public class C
{
public void M()
{
N((in int a, in int b, int c, int d) => {});
}
public void N(D lambda) { }
}
";
CompileAndVerify(text,
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
sourceSymbolValidator: module =>
{
var parameters = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.Parameters;
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
},
symbolValidator: module =>
{
var delegateParameters = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.Parameters;
Assert.Equal(4, delegateParameters.Length);
Assert.True(delegateParameters[0].IsMetadataIn);
Assert.True(delegateParameters[1].IsMetadataIn);
Assert.True(delegateParameters[2].IsMetadataIn);
Assert.False(delegateParameters[3].IsMetadataIn);
var lambdaParameters = module.GlobalNamespace.GetTypeMember("C").GetTypeMember("<>c").GetMethod("<M>b__0_0").Parameters;
Assert.Equal(4, lambdaParameters.Length);
Assert.True(lambdaParameters[0].IsMetadataIn);
Assert.True(lambdaParameters[1].IsMetadataIn);
Assert.False(lambdaParameters[2].IsMetadataIn);
Assert.False(lambdaParameters[3].IsMetadataIn);
});
}
[Fact]
public void InParametersShouldHaveMetadataIn_LocalFunctions()
{
var text = @"
using System.Runtime.InteropServices;
public class C
{
public void M()
{
void local(in int a, int c) { }
}
}
";
CompileAndVerify(text, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("C").GetMember("<M>g__local|0_0").GetParameters();
Assert.Equal(2, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.False(parameters[1].IsMetadataIn);
});
}
[Fact]
public void InParametersShouldHaveMetadataIn_ExternMethods()
{
var text = @"
using System.Runtime.InteropServices;
class T
{
[DllImport(""Other.dll"")]
public static extern void M(in int a, [In]in int b, [In]int c, int d);
}";
Action<ModuleSymbol> verifier = module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
};
CompileAndVerify(text, sourceSymbolValidator: verifier, symbolValidator: verifier);
}
[Fact]
public void InParametersShouldHaveMetadataIn_NoPIA()
{
var comAssembly = CreateCompilationWithMscorlib40(@"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""test.dll"")]
[assembly: Guid(""6681dcd6-9c3e-4c3a-b04a-aef3ee85c2cf"")]
[ComImport()]
[Guid(""6681dcd6-9c3e-4c3a-b04a-aef3ee85c2cf"")]
public interface T
{
void M(in int a, [In]in int b, [In]int c, int d);
}");
CompileAndVerify(comAssembly, symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
});
var code = @"
class User
{
public void M(T obj)
{
obj.M(1, 2, 3, 4);
}
}";
CompileAndVerify(
source: code,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
references: new[] { comAssembly.EmitToImageReference(embedInteropTypes: true) },
symbolValidator: module =>
{
var parameters = module.GlobalNamespace.GetTypeMember("T").GetMethod("M").GetParameters();
Assert.Equal(4, parameters.Length);
Assert.True(parameters[0].IsMetadataIn);
Assert.True(parameters[1].IsMetadataIn);
Assert.True(parameters[2].IsMetadataIn);
Assert.False(parameters[3].IsMetadataIn);
});
}
[Fact]
public void ExtendingInParametersFromParentWithoutInAttributeWorksWithoutErrors()
{
var reference = CompileIL(@"
.class private auto ansi sealed beforefieldinit Microsoft.CodeAnalysis.EmbeddedAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (01 00 00 00)
.custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = (01 00 00 00)
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: nop
IL_0007: ret
}
}
.class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsReadOnlyAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (01 00 00 00)
.custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = (01 00 00 00)
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Attribute::.ctor()
IL_0006: nop
IL_0007: ret
}
}
.class public auto ansi beforefieldinit Parent extends [mscorlib]System.Object
{
.method public hidebysig newslot virtual instance void M (
int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) a,
int32& modreq([mscorlib]System.Runtime.InteropServices.InAttribute) b,
int32 c,
int32 d) cil managed
{
.param [1] .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (01 00 00 00)
.param [2] .custom instance void System.Runtime.CompilerServices.IsReadOnlyAttribute::.ctor() = (01 00 00 00)
.maxstack 8
IL_0000: nop
IL_0001: ldstr ""Parent called""
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void[mscorlib] System.Object::.ctor()
IL_0006: nop
IL_0007: ret
}
}");
var comp = CreateCompilation(@"
using System;
using System.Runtime.InteropServices;
public class Child : Parent
{
public override void M(in int a, [In]in int b, [In]int c, int d)
{
base.M(a, b, c, d);
Console.WriteLine(""Child called"");
}
}
public static class Program
{
public static void Main()
{
var obj = new Child();
obj.M(1, 2, 3, 4);
}
}", new[] { reference }, TestOptions.ReleaseExe);
var parentParameters = comp.GetTypeByMetadataName("Parent").GetMethod("M").GetParameters();
Assert.Equal(4, parentParameters.Length);
Assert.False(parentParameters[0].IsMetadataIn);
Assert.False(parentParameters[1].IsMetadataIn);
Assert.False(parentParameters[2].IsMetadataIn);
Assert.False(parentParameters[3].IsMetadataIn);
var expectedOutput =
@"Parent called
Child called";
CompileAndVerify(comp, expectedOutput: expectedOutput, symbolValidator: module =>
{
var childParameters = module.ContainingAssembly.GetTypeByMetadataName("Child").GetMethod("M").GetParameters();
Assert.Equal(4, childParameters.Length);
Assert.True(childParameters[0].IsMetadataIn);
Assert.True(childParameters[1].IsMetadataIn);
Assert.True(childParameters[2].IsMetadataIn);
Assert.False(childParameters[3].IsMetadataIn);
});
}
[Fact]
public void GeneratingProxyForVirtualMethodInParentCopiesMetadataBitsCorrectly_OutAttribute()
{
var reference = CreateCompilation(@"
using System.Runtime.InteropServices;
public class Parent
{
public void M(out int a, [Out] int b) => throw null;
}");
CompileAndVerify(reference, symbolValidator: module =>
{
var sourceParentParameters = module.GlobalNamespace.GetTypeMember("Parent").GetMethod("M").GetParameters();
Assert.Equal(2, sourceParentParameters.Length);
Assert.True(sourceParentParameters[0].IsMetadataOut);
Assert.True(sourceParentParameters[1].IsMetadataOut);
});
var source = @"
using System.Runtime.InteropServices;
public interface IParent
{
void M(out int a, [Out] int b);
}
public class Child : Parent, IParent
{
}";
CompileAndVerify(
source: source,
references: new[] { reference.EmitToImageReference() },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var interfaceParameters = module.GlobalNamespace.GetTypeMember("IParent").GetMethod("M").GetParameters();
Assert.Equal(2, interfaceParameters.Length);
Assert.True(interfaceParameters[0].IsMetadataOut);
Assert.True(interfaceParameters[1].IsMetadataOut);
var proxyChildParameters = module.GlobalNamespace.GetTypeMember("Child").GetMethod("IParent.M").GetParameters();
Assert.Equal(2, proxyChildParameters.Length);
Assert.True(proxyChildParameters[0].IsMetadataOut);
Assert.False(proxyChildParameters[1].IsMetadataOut); // User placed attributes are not copied.
});
}
[Fact]
public void GeneratingProxyForVirtualMethodInParentCopiesMetadataBitsCorrectly_InAttribute()
{
var reference = CreateCompilation(@"
using System.Runtime.InteropServices;
public class Parent
{
public void M(in int a, [In] int b) => throw null;
}");
CompileAndVerify(reference, symbolValidator: module =>
{
var sourceParentParameters = module.GlobalNamespace.GetTypeMember("Parent").GetMethod("M").GetParameters();
Assert.Equal(2, sourceParentParameters.Length);
Assert.True(sourceParentParameters[0].IsMetadataIn);
Assert.True(sourceParentParameters[1].IsMetadataIn);
});
var source = @"
using System.Runtime.InteropServices;
public interface IParent
{
void M(in int a, [In] int b);
}
public class Child : Parent, IParent
{
}";
CompileAndVerify(
source: source,
references: new[] { reference.EmitToImageReference() },
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var interfaceParameters = module.GlobalNamespace.GetTypeMember("IParent").GetMethod("M").GetParameters();
Assert.Equal(2, interfaceParameters.Length);
Assert.True(interfaceParameters[0].IsMetadataIn);
Assert.True(interfaceParameters[1].IsMetadataIn);
var proxyChildParameters = module.GlobalNamespace.GetTypeMember("Child").GetMethod("IParent.M").GetParameters();
Assert.Equal(2, proxyChildParameters.Length);
Assert.True(proxyChildParameters[0].IsMetadataIn);
Assert.False(proxyChildParameters[1].IsMetadataIn); // User placed attributes are not copied.
});
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharpTest/KeywordHighlighting/CheckedStatementHighlighterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class CheckedStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(CheckedStatementHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"class C
{
void M()
{
short x = 0;
short y = 100;
while (true)
{
{|Cursor:[|checked|]|}
{
x++;
}
unchecked
{
y++;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_2()
{
await TestAsync(
@"class C
{
void M()
{
short x = 0;
short y = 100;
while (true)
{
checked
{
x++;
}
{|Cursor:[|unchecked|]|}
{
y++;
}
}
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class CheckedStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(CheckedStatementHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"class C
{
void M()
{
short x = 0;
short y = 100;
while (true)
{
{|Cursor:[|checked|]|}
{
x++;
}
unchecked
{
y++;
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_2()
{
await TestAsync(
@"class C
{
void M()
{
short x = 0;
short y = 100;
while (true)
{
checked
{
x++;
}
{|Cursor:[|unchecked|]|}
{
y++;
}
}
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Portable/Syntax/BaseSyntaxExtensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Friend Module BaseSyntaxExtensions
' Methods
<Extension()>
Friend Function ToGreen(node As InternalSyntax.VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode
Debug.Assert(False, "just use the node")
Return node
End Function
<Extension()>
Friend Function ToGreen(node As VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode
Return If(node Is Nothing, Nothing, node.VbGreen)
End Function
<Extension()>
Friend Function ToRed(node As InternalSyntax.VisualBasicSyntaxNode) As SyntaxNode
If node Is Nothing Then
Return Nothing
End If
Dim red = node.CreateRed(Nothing, 0)
Return red
End Function
<Extension()>
Friend Function ToRed(node As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
Debug.Assert(False, "just use the node")
Return node
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Friend Module BaseSyntaxExtensions
' Methods
<Extension()>
Friend Function ToGreen(node As InternalSyntax.VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode
Debug.Assert(False, "just use the node")
Return node
End Function
<Extension()>
Friend Function ToGreen(node As VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode
Return If(node Is Nothing, Nothing, node.VbGreen)
End Function
<Extension()>
Friend Function ToRed(node As InternalSyntax.VisualBasicSyntaxNode) As SyntaxNode
If node Is Nothing Then
Return Nothing
End If
Dim red = node.CreateRed(Nothing, 0)
Return red
End Function
<Extension()>
Friend Function ToRed(node As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
Debug.Assert(False, "just use the node")
Return node
End Function
End Module
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompilerFactory.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim
Friend Class TempPECompilerFactory
Implements IVbTempPECompilerFactory
Private ReadOnly _workspace As VisualStudioWorkspace
Public Sub New(workspace As VisualStudioWorkspace)
Me._workspace = workspace
End Sub
Public Function CreateCompiler() As IVbCompiler Implements IVbTempPECompilerFactory.CreateCompiler
Return New TempPECompiler(_workspace)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim
Friend Class TempPECompilerFactory
Implements IVbTempPECompilerFactory
Private ReadOnly _workspace As VisualStudioWorkspace
Public Sub New(workspace As VisualStudioWorkspace)
Me._workspace = workspace
End Sub
Public Function CreateCompiler() As IVbCompiler Implements IVbTempPECompilerFactory.CreateCompiler
Return New TempPECompiler(_workspace)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/LanguageServer/Protocol/RequestDispatcherFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[Shared]
[Export(typeof(RequestDispatcherFactory))]
internal sealed class RequestDispatcherFactory : AbstractRequestDispatcherFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RequestDispatcherFactory([ImportMany] IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders)
: base(requestHandlerProviders)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[Shared]
[Export(typeof(RequestDispatcherFactory))]
internal sealed class RequestDispatcherFactory : AbstractRequestDispatcherFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RequestDispatcherFactory([ImportMany] IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders)
: base(requestHandlerProviders)
{
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/Workspace/Solution/ITextVersionable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
internal interface ITextVersionable
{
bool TryGetTextVersion(out VersionStamp version);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
internal interface ITextVersionable
{
bool TryGetTextVersion(out VersionStamp version);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Core/Portable/Symbols/IAssemblySymbolInternal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Symbols
{
internal interface IAssemblySymbolInternal : ISymbolInternal
{
Version? AssemblyVersionPattern { get; }
/// <summary>
/// Gets the name of this assembly.
/// </summary>
AssemblyIdentity Identity { get; }
IAssemblySymbolInternal CorLibrary { 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;
namespace Microsoft.CodeAnalysis.Symbols
{
internal interface IAssemblySymbolInternal : ISymbolInternal
{
Version? AssemblyVersionPattern { get; }
/// <summary>
/// Gets the name of this assembly.
/// </summary>
AssemblyIdentity Identity { get; }
IAssemblySymbolInternal CorLibrary { get; }
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/EditAndContinue/Remote/RemoteEditAndContinueServiceProxy.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
/// <summary>
/// Facade used to call remote <see cref="IRemoteEditAndContinueService"/> methods.
/// Encapsulates all RPC logic as well as dispatching to the local service if the remote service is disabled.
/// THe facade is useful for targeted testing of serialization/deserialization of EnC service calls.
/// </summary>
internal readonly partial struct RemoteEditAndContinueServiceProxy
{
[ExportRemoteServiceCallbackDispatcher(typeof(IRemoteEditAndContinueService)), Shared]
internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteEditAndContinueService.ICallback
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CallbackDispatcher()
{
}
public ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken)
=> ((ActiveStatementSpanProviderCallback)GetCallback(callbackId)).GetSpansAsync(documentId, filePath, cancellationToken);
public ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).GetActiveStatementsAsync(cancellationToken);
public ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).GetAvailabilityAsync(mvid, cancellationToken);
public ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).GetCapabilitiesAsync(cancellationToken);
public ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).PrepareModuleForUpdateAsync(mvid, cancellationToken);
}
private sealed class EditSessionCallback
{
private readonly IManagedEditAndContinueDebuggerService _debuggerService;
public EditSessionCallback(IManagedEditAndContinueDebuggerService debuggerService)
{
_debuggerService = debuggerService;
}
public async ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken)
{
try
{
return await _debuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ImmutableArray<ManagedActiveStatementDebugInfo>.Empty;
}
}
public async ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken)
{
try
{
return await _debuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.InternalError, e.Message);
}
}
public async ValueTask PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken)
{
try
{
await _debuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
// nop
}
}
public async ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken)
{
try
{
return await _debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ImmutableArray<string>.Empty;
}
}
}
public readonly Workspace Workspace;
public RemoteEditAndContinueServiceProxy(Workspace workspace)
{
Workspace = workspace;
}
private IEditAndContinueWorkspaceService GetLocalService()
=> Workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
public async ValueTask<RemoteDebuggingSessionProxy?> StartDebuggingSessionAsync(
Solution solution,
IManagedEditAndContinueDebuggerService debuggerService,
ImmutableArray<DocumentId> captureMatchingDocuments,
bool captureAllMatchingDocuments,
bool reportDiagnostics,
CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
var sessionId = await GetLocalService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false);
return new RemoteDebuggingSessionProxy(Workspace, LocalConnection.Instance, sessionId);
}
// need to keep the providers alive until the edit session ends:
var connection = client.CreateConnection<IRemoteEditAndContinueService>(
callbackTarget: new EditSessionCallback(debuggerService));
var sessionIdOpt = await connection.TryInvokeAsync(
solution,
async (service, solutionInfo, callbackId, cancellationToken) => await service.StartDebuggingSessionAsync(solutionInfo, callbackId, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false),
cancellationToken).ConfigureAwait(false);
if (sessionIdOpt.HasValue)
{
return new RemoteDebuggingSessionProxy(Workspace, connection, sessionIdOpt.Value);
}
connection.Dispose();
return null;
}
public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, Document designTimeDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
var diagnostics = await GetLocalService().GetDocumentDiagnosticsAsync(document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);
if (designTimeDocument != document)
{
diagnostics = diagnostics.SelectAsArray(diagnostic => RemapLocation(designTimeDocument, DiagnosticData.Create(diagnostic, document.Project)));
}
return diagnostics;
}
var diagnosticData = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DiagnosticData>>(
document.Project.Solution,
(service, solutionInfo, callbackId, cancellationToken) => service.GetDocumentDiagnosticsAsync(solutionInfo, callbackId, document.Id, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
if (!diagnosticData.HasValue)
{
return ImmutableArray<Diagnostic>.Empty;
}
var project = document.Project;
using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var result);
foreach (var data in diagnosticData.Value)
{
Debug.Assert(data.DataLocation != null);
Diagnostic diagnostic;
// Workaround for solution crawler not supporting mapped locations to make Razor work.
// We pretend the diagnostic is in the original document, but use the mapped line span.
// Razor will ignore the column (which will be off because #line directives can't currently map columns) and only use the line number.
if (designTimeDocument != document && data.DataLocation.IsMapped)
{
diagnostic = RemapLocation(designTimeDocument, data);
}
else
{
diagnostic = await data.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false);
}
result.Add(diagnostic);
}
return result.ToImmutable();
}
private static Diagnostic RemapLocation(Document designTimeDocument, DiagnosticData data)
{
Debug.Assert(data.DataLocation != null);
Debug.Assert(designTimeDocument.FilePath != null);
var mappedSpan = data.DataLocation.GetFileLinePositionSpan();
var location = Location.Create(designTimeDocument.FilePath, textSpan: default, mappedSpan.Span);
return data.ToDiagnostic(location, ImmutableArray<Location>.Empty);
}
public async ValueTask OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().OnSourceFileUpdated(document);
return;
}
await client.TryInvokeAsync<IRemoteEditAndContinueService>(
document.Project.Solution,
(service, solutionInfo, cancellationToken) => service.OnSourceFileUpdatedAsync(solutionInfo, document.Id, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
private sealed class LocalConnection : IDisposable
{
public static readonly LocalConnection Instance = new();
public void Dispose()
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
/// <summary>
/// Facade used to call remote <see cref="IRemoteEditAndContinueService"/> methods.
/// Encapsulates all RPC logic as well as dispatching to the local service if the remote service is disabled.
/// THe facade is useful for targeted testing of serialization/deserialization of EnC service calls.
/// </summary>
internal readonly partial struct RemoteEditAndContinueServiceProxy
{
[ExportRemoteServiceCallbackDispatcher(typeof(IRemoteEditAndContinueService)), Shared]
internal sealed class CallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteEditAndContinueService.ICallback
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CallbackDispatcher()
{
}
public ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken)
=> ((ActiveStatementSpanProviderCallback)GetCallback(callbackId)).GetSpansAsync(documentId, filePath, cancellationToken);
public ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).GetActiveStatementsAsync(cancellationToken);
public ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).GetAvailabilityAsync(mvid, cancellationToken);
public ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).GetCapabilitiesAsync(cancellationToken);
public ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken)
=> ((EditSessionCallback)GetCallback(callbackId)).PrepareModuleForUpdateAsync(mvid, cancellationToken);
}
private sealed class EditSessionCallback
{
private readonly IManagedEditAndContinueDebuggerService _debuggerService;
public EditSessionCallback(IManagedEditAndContinueDebuggerService debuggerService)
{
_debuggerService = debuggerService;
}
public async ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken)
{
try
{
return await _debuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ImmutableArray<ManagedActiveStatementDebugInfo>.Empty;
}
}
public async ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken)
{
try
{
return await _debuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.InternalError, e.Message);
}
}
public async ValueTask PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken)
{
try
{
await _debuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
// nop
}
}
public async ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken)
{
try
{
return await _debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ImmutableArray<string>.Empty;
}
}
}
public readonly Workspace Workspace;
public RemoteEditAndContinueServiceProxy(Workspace workspace)
{
Workspace = workspace;
}
private IEditAndContinueWorkspaceService GetLocalService()
=> Workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>();
public async ValueTask<RemoteDebuggingSessionProxy?> StartDebuggingSessionAsync(
Solution solution,
IManagedEditAndContinueDebuggerService debuggerService,
ImmutableArray<DocumentId> captureMatchingDocuments,
bool captureAllMatchingDocuments,
bool reportDiagnostics,
CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
var sessionId = await GetLocalService().StartDebuggingSessionAsync(solution, debuggerService, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false);
return new RemoteDebuggingSessionProxy(Workspace, LocalConnection.Instance, sessionId);
}
// need to keep the providers alive until the edit session ends:
var connection = client.CreateConnection<IRemoteEditAndContinueService>(
callbackTarget: new EditSessionCallback(debuggerService));
var sessionIdOpt = await connection.TryInvokeAsync(
solution,
async (service, solutionInfo, callbackId, cancellationToken) => await service.StartDebuggingSessionAsync(solutionInfo, callbackId, captureMatchingDocuments, captureAllMatchingDocuments, reportDiagnostics, cancellationToken).ConfigureAwait(false),
cancellationToken).ConfigureAwait(false);
if (sessionIdOpt.HasValue)
{
return new RemoteDebuggingSessionProxy(Workspace, connection, sessionIdOpt.Value);
}
connection.Dispose();
return null;
}
public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, Document designTimeDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
var diagnostics = await GetLocalService().GetDocumentDiagnosticsAsync(document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false);
if (designTimeDocument != document)
{
diagnostics = diagnostics.SelectAsArray(diagnostic => RemapLocation(designTimeDocument, DiagnosticData.Create(diagnostic, document.Project)));
}
return diagnostics;
}
var diagnosticData = await client.TryInvokeAsync<IRemoteEditAndContinueService, ImmutableArray<DiagnosticData>>(
document.Project.Solution,
(service, solutionInfo, callbackId, cancellationToken) => service.GetDocumentDiagnosticsAsync(solutionInfo, callbackId, document.Id, cancellationToken),
callbackTarget: new ActiveStatementSpanProviderCallback(activeStatementSpanProvider),
cancellationToken).ConfigureAwait(false);
if (!diagnosticData.HasValue)
{
return ImmutableArray<Diagnostic>.Empty;
}
var project = document.Project;
using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var result);
foreach (var data in diagnosticData.Value)
{
Debug.Assert(data.DataLocation != null);
Diagnostic diagnostic;
// Workaround for solution crawler not supporting mapped locations to make Razor work.
// We pretend the diagnostic is in the original document, but use the mapped line span.
// Razor will ignore the column (which will be off because #line directives can't currently map columns) and only use the line number.
if (designTimeDocument != document && data.DataLocation.IsMapped)
{
diagnostic = RemapLocation(designTimeDocument, data);
}
else
{
diagnostic = await data.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false);
}
result.Add(diagnostic);
}
return result.ToImmutable();
}
private static Diagnostic RemapLocation(Document designTimeDocument, DiagnosticData data)
{
Debug.Assert(data.DataLocation != null);
Debug.Assert(designTimeDocument.FilePath != null);
var mappedSpan = data.DataLocation.GetFileLinePositionSpan();
var location = Location.Create(designTimeDocument.FilePath, textSpan: default, mappedSpan.Span);
return data.ToDiagnostic(location, ImmutableArray<Location>.Empty);
}
public async ValueTask OnSourceFileUpdatedAsync(Document document, CancellationToken cancellationToken)
{
var client = await RemoteHostClient.TryGetClientAsync(Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
GetLocalService().OnSourceFileUpdated(document);
return;
}
await client.TryInvokeAsync<IRemoteEditAndContinueService>(
document.Project.Solution,
(service, solutionInfo, cancellationToken) => service.OnSourceFileUpdatedAsync(solutionInfo, document.Id, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
private sealed class LocalConnection : IDisposable
{
public static readonly LocalConnection Instance = new();
public void Dispose()
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/ExpressionEvaluator/Core/Test/ExpressionCompiler/CustomDiagnosticFormatter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
{
internal sealed class CustomDiagnosticFormatter : DiagnosticFormatter
{
internal static new readonly CustomDiagnosticFormatter Instance = new CustomDiagnosticFormatter();
public override string Format(Diagnostic diagnostic, IFormatProvider formatter = null)
{
var cultureInfo = (CultureInfo)formatter;
return string.Format("LCID={0}, Code={1}", cultureInfo.LCID, diagnostic.Code);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
{
internal sealed class CustomDiagnosticFormatter : DiagnosticFormatter
{
internal static new readonly CustomDiagnosticFormatter Instance = new CustomDiagnosticFormatter();
public override string Format(Diagnostic diagnostic, IFormatProvider formatter = null)
{
var cultureInfo = (CultureInfo)formatter;
return string.Format("LCID={0}, Code={1}", cultureInfo.LCID, diagnostic.Code);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Core.Wpf/Suggestions/PreviewChanges/PreviewChangesSuggestedAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedActionWithNestedFlavors
{
/// <summary>
/// Suggested action for showing the preview-changes dialog. Note: this is only used
/// as a 'flavor' inside CodeFixSuggestionAction and CodeRefactoringSuggestedAction.
/// </summary>
private sealed partial class PreviewChangesSuggestedAction : SuggestedAction
{
private PreviewChangesSuggestedAction(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider,
Workspace workspace,
ITextBuffer subjectBuffer,
object provider,
PreviewChangesCodeAction codeAction)
: base(threadingContext, sourceProvider, workspace, subjectBuffer, provider, codeAction)
{
}
public static async Task<SuggestedAction> CreateAsync(
SuggestedActionWithNestedFlavors suggestedAction, CancellationToken cancellationToken)
{
var previewResult = await suggestedAction.GetPreviewResultAsync(cancellationToken).ConfigureAwait(true);
if (previewResult == null)
{
return null;
}
var changeSummary = previewResult.ChangeSummary;
if (changeSummary == null)
{
return null;
}
return new PreviewChangesSuggestedAction(
suggestedAction.ThreadingContext,
suggestedAction.SourceProvider, suggestedAction.Workspace,
suggestedAction.SubjectBuffer, suggestedAction.Provider,
new PreviewChangesCodeAction(
suggestedAction.Workspace, suggestedAction.CodeAction, changeSummary));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedActionWithNestedFlavors
{
/// <summary>
/// Suggested action for showing the preview-changes dialog. Note: this is only used
/// as a 'flavor' inside CodeFixSuggestionAction and CodeRefactoringSuggestedAction.
/// </summary>
private sealed partial class PreviewChangesSuggestedAction : SuggestedAction
{
private PreviewChangesSuggestedAction(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider,
Workspace workspace,
ITextBuffer subjectBuffer,
object provider,
PreviewChangesCodeAction codeAction)
: base(threadingContext, sourceProvider, workspace, subjectBuffer, provider, codeAction)
{
}
public static async Task<SuggestedAction> CreateAsync(
SuggestedActionWithNestedFlavors suggestedAction, CancellationToken cancellationToken)
{
var previewResult = await suggestedAction.GetPreviewResultAsync(cancellationToken).ConfigureAwait(true);
if (previewResult == null)
{
return null;
}
var changeSummary = previewResult.ChangeSummary;
if (changeSummary == null)
{
return null;
}
return new PreviewChangesSuggestedAction(
suggestedAction.ThreadingContext,
suggestedAction.SourceProvider, suggestedAction.Workspace,
suggestedAction.SubjectBuffer, suggestedAction.Provider,
new PreviewChangesCodeAction(
suggestedAction.Workspace, suggestedAction.CodeAction, changeSummary));
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/VisualBasicTest/AutomaticEndConstructCorrection/AutomaticEndConstructCorrectorTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticEndConstructCorrection
<[UseExportProvider]>
Public Class AutomaticEndConstructCorrectorTests
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestStructureToInterface()
Dim code = <code>[|Structure|] A
End [|Structure|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestEnumToInterface()
Dim code = <code>[|Enum|] A
End [|Enum|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestInterfaceToEnum()
Dim code = <code>[|Interface|] A
End [|Interface|]</code>.Value
Verify(code, "Enum")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestClassToInterface()
Dim code = <code>[|Class|] A
End [|Class|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface()
Dim code = <code>[|Module|] A
End [|Module|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestNamespaceToInterface()
Dim code = <code>[|Namespace|] A
End [|Namespace|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestSubToFunction()
Dim code = <code>Class A
[|Sub|] Test()
End [|Sub|]
End Class</code>.Value
Verify(code, "Function")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestFunctionToSub()
Dim code = <code>Class A
[|Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
Verify(code, "Sub")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface1()
Dim code = <code>[|Module|] A : End [|Module|] : Module B : End Module</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface2()
Dim code = <code>Module A : End Module : [|Module|] B : End [|Module|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface3()
Dim code = <code>Module A : End Module:[|Module|] B : End [|Module|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface4()
Dim code = <code>[|Module|] A : End [|Module|]:Module B : End Module</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestErrorCaseMissingEndFunction()
Dim code = <code>Class A
[|Function|] Test() As Integer
End [|Sub|]
End Class</code>.Value.Replace(vbLf, vbCrLf)
VerifyBegin(code, "Interface", "Sub")
VerifyEnd(code, "Interface", "Function")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterface()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Interface", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterfaceWithLeadingSpaces()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " Interface", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterfaceWithTrailingSpaces()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Interface ", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterfaceWithLeadingAndTrailingSpaces()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " Interface ", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddSharedModifierToFunction()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " Shared ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddSharedModifierToFunction1()
Dim code = <code>Class A
[|Function$$|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Shared ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddTrailingSpaceToFunction()
Dim code = <code>Class A
[|Function$$|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddLeadingSpaceToFunction()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddSharedModifierToFunction2()
Dim code = <code>Class A
[|Function$$|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Shared", Function(s) "Function", removeOriginalContent:=False, split:="Function")
End Sub
<WorkItem(539362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539362")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestMultiLineLambdaSubToFunction()
Dim code = <code>Class A
Public Sub F()
Dim nums() As Integer = {1, 2, 3, 4, 5}
Array.ForEach(nums, [|Sub|](n)
Console.Write("Number: ")
Console.WriteLine(n)
End [|Sub|])
End Sub
End Class</code>.Value
Verify(code, "Function")
End Sub
<WorkItem(539362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539362")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestMultiLineLambdaFunctionToSub()
Dim code = <code>Class A
Public Sub F()
Dim nums() As Integer = {1, 2, 3, 4, 5}
Dim numDelegate = [|Function|](n As Integer)
End [|Function|]
End Sub
End Class</code>.Value
Verify(code, "Sub")
End Sub
<WorkItem(539365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539365")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub BugFix5290()
Dim code = <code>Public Class Class1
Sub M()
[|Class|]
End Sub
End [|Class|]</code>.Value
VerifyBegin(code, "Structure", "Class")
VerifyEnd(code, "Structure", "Class")
End Sub
<WorkItem(539357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539357")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestBugFix5276()
Dim code = <code>Class A
[|Func$$tion|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WorkItem(539360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539360")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestBugFix5283()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Shared Sub", Function(s) If(s.Trim() = "Shared Sub", "Sub", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
<WorkItem(539498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539498")>
Public Sub TestDontThrowDueToSingleLineDeletion()
Dim code = <code>Class A
[|$$Sub M() : End Sub|]
End Class</code>.Value
VerifyContinuousEdits(code, "", Function() "", removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestPropertySet()
Dim code = <code>Class A
Property Test
[|Get|]
End [|Get|]
Set(value)
End Set
End Property
End Class</code>.Value
Verify(code, "Set")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestPropertyGet()
Dim code = <code>Class A
Property Test
Get
End Get
[|Set|](value)
End [|Set|]
End Property
End Class</code>.Value
Verify(code, "Get")
End Sub
Private Shared Sub VerifyContinuousEdits(codeWithMarker As String,
type As String,
expectedStringGetter As Func(Of String, String),
removeOriginalContent As Boolean,
Optional split As String = Nothing)
' do this since xml value put only vbLf
codeWithMarker = codeWithMarker.Replace(vbLf, vbCrLf)
Using workspace = TestWorkspace.CreateVisualBasic(codeWithMarker)
Dim document = workspace.Documents.Single()
Dim buffer = document.GetTextBuffer()
Dim initialTextSnapshot = buffer.CurrentSnapshot
Dim caretPosition = initialTextSnapshot.CreateTrackingPoint(document.CursorPosition.Value,
PointTrackingMode.Positive,
TrackingFidelityMode.Backward)
Dim corrector = New AutomaticEndConstructCorrector(buffer, workspace.GetService(Of IUIThreadOperationExecutor))
corrector.Connect()
If removeOriginalContent Then
Dim spanToRemove = document.SelectedSpans.Single(Function(s) s.Contains(caretPosition.GetPosition(initialTextSnapshot)))
buffer.Replace(spanToRemove.ToSpan(), "")
End If
For i = 0 To type.Length - 1
Dim charToInsert = type(i)
buffer.Insert(caretPosition.GetPosition(buffer.CurrentSnapshot), charToInsert)
Dim insertedString = type.Substring(0, i + 1)
For Each span In document.SelectedSpans.Skip(1)
Dim trackingSpan = New LetterOnlyTrackingSpan(span.ToSnapshotSpan(initialTextSnapshot))
Assert.Equal(expectedStringGetter(insertedString), trackingSpan.GetText(document.GetTextBuffer().CurrentSnapshot))
Next
Next
If split IsNot Nothing Then
Dim beginSpan = document.SelectedSpans.First()
Dim trackingSpan = New LetterOnlyTrackingSpan(beginSpan.ToSnapshotSpan(initialTextSnapshot))
buffer.Insert(trackingSpan.GetEndPoint(buffer.CurrentSnapshot).Position - type.Trim().Length, " ")
Assert.Equal(split, trackingSpan.GetText(buffer.CurrentSnapshot))
End If
corrector.Disconnect()
End Using
End Sub
Private Shared Sub Verify(codeWithMarker As String, keyword As String)
' do this since xml value put only vbLf
codeWithMarker = codeWithMarker.Replace(vbLf, vbCrLf)
VerifyBegin(codeWithMarker, keyword)
VerifyEnd(codeWithMarker, keyword)
End Sub
Private Shared Sub VerifyBegin(code As String, keyword As String, Optional expected As String = Nothing)
Using workspace = TestWorkspace.CreateVisualBasic(code)
Dim document = workspace.Documents.Single()
Dim selectedSpans = document.SelectedSpans
Dim spanToReplace = selectedSpans.First()
Dim spanToVerify = selectedSpans.Skip(1).Single()
Verify(document, keyword, expected, spanToReplace, spanToVerify, workspace)
End Using
End Sub
Private Shared Sub VerifyEnd(code As String, keyword As String, Optional expected As String = Nothing)
Using workspace = TestWorkspace.CreateVisualBasic(code)
Dim document = workspace.Documents.Single()
Dim selectedSpans = document.SelectedSpans
Dim spanToReplace = selectedSpans.Skip(1).Single()
Dim spanToVerify = selectedSpans.First()
Verify(document, keyword, expected, spanToReplace, spanToVerify, workspace)
End Using
End Sub
Private Shared Sub Verify(document As TestHostDocument, keyword As String, expected As String, spanToReplace As TextSpan, spanToVerify As TextSpan, workspace As TestWorkspace)
Dim buffer = document.GetTextBuffer()
Dim uiThreadOperationExecutor = workspace.GetService(Of IUIThreadOperationExecutor)
Dim corrector = New AutomaticEndConstructCorrector(buffer, uiThreadOperationExecutor)
corrector.Connect()
buffer.Replace(spanToReplace.ToSpan(), keyword)
corrector.Disconnect()
expected = If(expected Is Nothing, keyword, expected)
Dim correspondingSpan = document.InitialTextSnapshot.CreateTrackingSpan(spanToVerify.ToSpan(), SpanTrackingMode.EdgeInclusive)
Assert.Equal(expected, correspondingSpan.GetText(buffer.CurrentSnapshot))
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticEndConstructCorrection
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticEndConstructCorrection
<[UseExportProvider]>
Public Class AutomaticEndConstructCorrectorTests
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestStructureToInterface()
Dim code = <code>[|Structure|] A
End [|Structure|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestEnumToInterface()
Dim code = <code>[|Enum|] A
End [|Enum|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestInterfaceToEnum()
Dim code = <code>[|Interface|] A
End [|Interface|]</code>.Value
Verify(code, "Enum")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestClassToInterface()
Dim code = <code>[|Class|] A
End [|Class|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface()
Dim code = <code>[|Module|] A
End [|Module|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestNamespaceToInterface()
Dim code = <code>[|Namespace|] A
End [|Namespace|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestSubToFunction()
Dim code = <code>Class A
[|Sub|] Test()
End [|Sub|]
End Class</code>.Value
Verify(code, "Function")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestFunctionToSub()
Dim code = <code>Class A
[|Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
Verify(code, "Sub")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface1()
Dim code = <code>[|Module|] A : End [|Module|] : Module B : End Module</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface2()
Dim code = <code>Module A : End Module : [|Module|] B : End [|Module|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface3()
Dim code = <code>Module A : End Module:[|Module|] B : End [|Module|]</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestModuleToInterface4()
Dim code = <code>[|Module|] A : End [|Module|]:Module B : End Module</code>.Value
Verify(code, "Interface")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestErrorCaseMissingEndFunction()
Dim code = <code>Class A
[|Function|] Test() As Integer
End [|Sub|]
End Class</code>.Value.Replace(vbLf, vbCrLf)
VerifyBegin(code, "Interface", "Sub")
VerifyEnd(code, "Interface", "Function")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterface()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Interface", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterfaceWithLeadingSpaces()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " Interface", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterfaceWithTrailingSpaces()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Interface ", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestContinuousEditsOnFunctionToInterfaceWithLeadingAndTrailingSpaces()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " Interface ", Function(s) If(s.Trim() = "Interface", "Interface", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddSharedModifierToFunction()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " Shared ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddSharedModifierToFunction1()
Dim code = <code>Class A
[|Function$$|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Shared ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddTrailingSpaceToFunction()
Dim code = <code>Class A
[|Function$$|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddLeadingSpaceToFunction()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestAddSharedModifierToFunction2()
Dim code = <code>Class A
[|Function$$|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Shared", Function(s) "Function", removeOriginalContent:=False, split:="Function")
End Sub
<WorkItem(539362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539362")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestMultiLineLambdaSubToFunction()
Dim code = <code>Class A
Public Sub F()
Dim nums() As Integer = {1, 2, 3, 4, 5}
Array.ForEach(nums, [|Sub|](n)
Console.Write("Number: ")
Console.WriteLine(n)
End [|Sub|])
End Sub
End Class</code>.Value
Verify(code, "Function")
End Sub
<WorkItem(539362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539362")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestMultiLineLambdaFunctionToSub()
Dim code = <code>Class A
Public Sub F()
Dim nums() As Integer = {1, 2, 3, 4, 5}
Dim numDelegate = [|Function|](n As Integer)
End [|Function|]
End Sub
End Class</code>.Value
Verify(code, "Sub")
End Sub
<WorkItem(539365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539365")>
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub BugFix5290()
Dim code = <code>Public Class Class1
Sub M()
[|Class|]
End Sub
End [|Class|]</code>.Value
VerifyBegin(code, "Structure", "Class")
VerifyEnd(code, "Structure", "Class")
End Sub
<WorkItem(539357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539357")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestBugFix5276()
Dim code = <code>Class A
[|Func$$tion|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, " ", Function(s) "Function", removeOriginalContent:=False)
End Sub
<WorkItem(539360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539360")>
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestBugFix5283()
Dim code = <code>Class A
[|$$Function|] Test() As Integer
End [|Function|]
End Class</code>.Value
VerifyContinuousEdits(code, "Shared Sub", Function(s) If(s.Trim() = "Shared Sub", "Sub", "Function"), removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
<WorkItem(539498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539498")>
Public Sub TestDontThrowDueToSingleLineDeletion()
Dim code = <code>Class A
[|$$Sub M() : End Sub|]
End Class</code>.Value
VerifyContinuousEdits(code, "", Function() "", removeOriginalContent:=True)
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestPropertySet()
Dim code = <code>Class A
Property Test
[|Get|]
End [|Get|]
Set(value)
End Set
End Property
End Class</code>.Value
Verify(code, "Set")
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.AutomaticEndConstructCorrection)>
Public Sub TestPropertyGet()
Dim code = <code>Class A
Property Test
Get
End Get
[|Set|](value)
End [|Set|]
End Property
End Class</code>.Value
Verify(code, "Get")
End Sub
Private Shared Sub VerifyContinuousEdits(codeWithMarker As String,
type As String,
expectedStringGetter As Func(Of String, String),
removeOriginalContent As Boolean,
Optional split As String = Nothing)
' do this since xml value put only vbLf
codeWithMarker = codeWithMarker.Replace(vbLf, vbCrLf)
Using workspace = TestWorkspace.CreateVisualBasic(codeWithMarker)
Dim document = workspace.Documents.Single()
Dim buffer = document.GetTextBuffer()
Dim initialTextSnapshot = buffer.CurrentSnapshot
Dim caretPosition = initialTextSnapshot.CreateTrackingPoint(document.CursorPosition.Value,
PointTrackingMode.Positive,
TrackingFidelityMode.Backward)
Dim corrector = New AutomaticEndConstructCorrector(buffer, workspace.GetService(Of IUIThreadOperationExecutor))
corrector.Connect()
If removeOriginalContent Then
Dim spanToRemove = document.SelectedSpans.Single(Function(s) s.Contains(caretPosition.GetPosition(initialTextSnapshot)))
buffer.Replace(spanToRemove.ToSpan(), "")
End If
For i = 0 To type.Length - 1
Dim charToInsert = type(i)
buffer.Insert(caretPosition.GetPosition(buffer.CurrentSnapshot), charToInsert)
Dim insertedString = type.Substring(0, i + 1)
For Each span In document.SelectedSpans.Skip(1)
Dim trackingSpan = New LetterOnlyTrackingSpan(span.ToSnapshotSpan(initialTextSnapshot))
Assert.Equal(expectedStringGetter(insertedString), trackingSpan.GetText(document.GetTextBuffer().CurrentSnapshot))
Next
Next
If split IsNot Nothing Then
Dim beginSpan = document.SelectedSpans.First()
Dim trackingSpan = New LetterOnlyTrackingSpan(beginSpan.ToSnapshotSpan(initialTextSnapshot))
buffer.Insert(trackingSpan.GetEndPoint(buffer.CurrentSnapshot).Position - type.Trim().Length, " ")
Assert.Equal(split, trackingSpan.GetText(buffer.CurrentSnapshot))
End If
corrector.Disconnect()
End Using
End Sub
Private Shared Sub Verify(codeWithMarker As String, keyword As String)
' do this since xml value put only vbLf
codeWithMarker = codeWithMarker.Replace(vbLf, vbCrLf)
VerifyBegin(codeWithMarker, keyword)
VerifyEnd(codeWithMarker, keyword)
End Sub
Private Shared Sub VerifyBegin(code As String, keyword As String, Optional expected As String = Nothing)
Using workspace = TestWorkspace.CreateVisualBasic(code)
Dim document = workspace.Documents.Single()
Dim selectedSpans = document.SelectedSpans
Dim spanToReplace = selectedSpans.First()
Dim spanToVerify = selectedSpans.Skip(1).Single()
Verify(document, keyword, expected, spanToReplace, spanToVerify, workspace)
End Using
End Sub
Private Shared Sub VerifyEnd(code As String, keyword As String, Optional expected As String = Nothing)
Using workspace = TestWorkspace.CreateVisualBasic(code)
Dim document = workspace.Documents.Single()
Dim selectedSpans = document.SelectedSpans
Dim spanToReplace = selectedSpans.Skip(1).Single()
Dim spanToVerify = selectedSpans.First()
Verify(document, keyword, expected, spanToReplace, spanToVerify, workspace)
End Using
End Sub
Private Shared Sub Verify(document As TestHostDocument, keyword As String, expected As String, spanToReplace As TextSpan, spanToVerify As TextSpan, workspace As TestWorkspace)
Dim buffer = document.GetTextBuffer()
Dim uiThreadOperationExecutor = workspace.GetService(Of IUIThreadOperationExecutor)
Dim corrector = New AutomaticEndConstructCorrector(buffer, uiThreadOperationExecutor)
corrector.Connect()
buffer.Replace(spanToReplace.ToSpan(), keyword)
corrector.Disconnect()
expected = If(expected Is Nothing, keyword, expected)
Dim correspondingSpan = document.InitialTextSnapshot.CreateTrackingSpan(spanToVerify.ToSpan(), SpanTrackingMode.EdgeInclusive)
Assert.Equal(expected, correspondingSpan.GetText(buffer.CurrentSnapshot))
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/ConvertToInterpolatedString/AbstractConvertConcatenationToInterpolatedStringRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.ConvertToInterpolatedString
{
/// <summary>
/// Code refactoring that converts expressions of the form: a + b + " str " + d + e
/// into:
/// $"{a + b} str {d}{e}".
/// </summary>
internal abstract class AbstractConvertConcatenationToInterpolatedStringRefactoringProvider<TExpressionSyntax> : CodeRefactoringProvider
where TExpressionSyntax : SyntaxNode
{
protected abstract bool SupportsConstantInterpolatedStrings(Document document);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var possibleExpressions = await context.GetRelevantNodesAsync<TExpressionSyntax>().ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// let's take the largest (last) StringConcat we can given current textSpan
var top = possibleExpressions
.Where(expr => IsStringConcat(syntaxFacts, expr, semanticModel, cancellationToken))
.LastOrDefault();
if (top == null)
{
return;
}
if (!SupportsConstantInterpolatedStrings(context.Document))
{
// if there is a const keyword, the refactoring shouldn't show because interpolated string is not const string
var declarator = top.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsVariableDeclarator);
if (declarator != null)
{
var generator = SyntaxGenerator.GetGenerator(document);
if (generator.GetModifiers(declarator).IsConst)
{
return;
}
}
}
// Currently we can concatenate only full subtrees. Therefore we can't support arbitrary selection. We could
// theoretically support selecting the selections that correspond to full sub-trees (e.g. prefixes of
// correct length but from UX point of view that it would feel arbitrary).
// Thus, we only support selection that takes the whole topmost expression. It breaks some leniency around under-selection
// but it's the best solution so far.
if (CodeRefactoringHelpers.IsNodeUnderselected(top, textSpan) ||
IsStringConcat(syntaxFacts, top.Parent, semanticModel, cancellationToken))
{
return;
}
// Now walk down the concatenation collecting all the pieces that we are
// concatenating.
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var pieces);
CollectPiecesDown(syntaxFacts, pieces, top, semanticModel, cancellationToken);
var stringLiterals = pieces
.Where(x => syntaxFacts.IsStringLiteralExpression(x) || syntaxFacts.IsCharacterLiteralExpression(x))
.ToImmutableArray();
// If the entire expression is just concatenated strings, then don't offer to
// make an interpolated string. The user likely manually split this for
// readability.
if (stringLiterals.Length == pieces.Count)
{
return;
}
var isVerbatimStringLiteral = false;
if (stringLiterals.Length > 0)
{
// Make sure that all the string tokens we're concatenating are the same type
// of string literal. i.e. if we have an expression like: @" "" " + " \r\n "
// then we don't merge this. We don't want to be munging different types of
// escape sequences in these strings, so we only support combining the string
// tokens if they're all the same type.
var firstStringToken = stringLiterals[0].GetFirstToken();
isVerbatimStringLiteral = syntaxFacts.IsVerbatimStringLiteral(firstStringToken);
if (stringLiterals.Any(
lit => isVerbatimStringLiteral != syntaxFacts.IsVerbatimStringLiteral(lit.GetFirstToken())))
{
return;
}
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var interpolatedString = CreateInterpolatedString(document, isVerbatimStringLiteral, pieces);
context.RegisterRefactoring(
new MyCodeAction(
_ => UpdateDocumentAsync(document, root, top, interpolatedString)),
top.Span);
}
private static Task<Document> UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxNode top, SyntaxNode interpolatedString)
{
var newRoot = root.ReplaceNode(top, interpolatedString);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
protected SyntaxNode CreateInterpolatedString(
Document document, bool isVerbatimStringLiteral, ArrayBuilder<SyntaxNode> pieces)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var generator = SyntaxGenerator.GetGenerator(document);
var startToken = generator.CreateInterpolatedStringStartToken(isVerbatimStringLiteral)
.WithLeadingTrivia(pieces.First().GetLeadingTrivia());
var endToken = generator.CreateInterpolatedStringEndToken()
.WithTrailingTrivia(pieces.Last().GetTrailingTrivia());
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(pieces.Count, out var content);
var previousContentWasStringLiteralExpression = false;
foreach (var piece in pieces)
{
var isCharacterLiteral = syntaxFacts.IsCharacterLiteralExpression(piece);
var currentContentIsStringOrCharacterLiteral = syntaxFacts.IsStringLiteralExpression(piece) || isCharacterLiteral;
if (currentContentIsStringOrCharacterLiteral)
{
var text = piece.GetFirstToken().Text;
var value = piece.GetFirstToken().Value?.ToString() ?? piece.GetFirstToken().ValueText;
var textWithEscapedBraces = text.Replace("{", "{{").Replace("}", "}}");
var valueTextWithEscapedBraces = value.Replace("{", "{{").Replace("}", "}}");
var textWithoutQuotes = GetTextWithoutQuotes(textWithEscapedBraces, isVerbatimStringLiteral, isCharacterLiteral);
if (previousContentWasStringLiteralExpression)
{
// Last part we added to the content list was also an interpolated-string-text-node.
// We need to combine these as the API for creating an interpolated strings
// does not expect to be given a list containing non-contiguous string nodes.
// Essentially if we combine '"A" + 1 + "B" + "C"' into '$"A{1}BC"' it must be:
// {InterpolatedStringText}{Interpolation}{InterpolatedStringText}
// not:
// {InterpolatedStringText}{Interpolation}{InterpolatedStringText}{InterpolatedStringText}
var existingInterpolatedStringTextNode = content.Last();
var newText = ConcatenateTextToTextNode(generator, existingInterpolatedStringTextNode, textWithoutQuotes, valueTextWithEscapedBraces);
content[^1] = newText;
}
else
{
// This is either the first string literal we have encountered or it is the most recent one we've seen
// after adding an interpolation. Add a new interpolated-string-text-node to the list.
content.Add(generator.InterpolatedStringText(generator.InterpolatedStringTextToken(textWithoutQuotes, valueTextWithEscapedBraces)));
}
}
else if (syntaxFacts.IsInterpolatedStringExpression(piece) &&
syntaxFacts.IsVerbatimInterpolatedStringExpression(piece) == isVerbatimStringLiteral)
{
// "piece" is itself an interpolated string (of the same "verbatimity" as the new interpolated string)
// "a" + $"{1+ 1}" -> instead of $"a{$"{1 + 1}"}" inline the interpolated part: $"a{1 + 1}"
syntaxFacts.GetPartsOfInterpolationExpression(piece, out var _, out var contentParts, out var _);
foreach (var contentPart in contentParts)
{
// Track the state of currentContentIsStringOrCharacterLiteral for the inlined parts
// so any text at the end of piece can be merge with the next string literal:
// $"{1 + 1}a" + "b" -> "a" and "b" get merged in the next "pieces" loop
currentContentIsStringOrCharacterLiteral = syntaxFacts.IsInterpolatedStringText(contentPart);
if (currentContentIsStringOrCharacterLiteral && previousContentWasStringLiteralExpression)
{
// if piece starts with a text and the previous part was a string, merge the two parts (see also above)
// "a" + $"b{1 + 1}" -> "a" and "b" get merged
var newText = ConcatenateTextToTextNode(generator, content.Last(), contentPart.GetFirstToken().Text, contentPart.GetFirstToken().ValueText);
content[^1] = newText;
}
else
{
content.Add(contentPart);
}
// Only the first contentPart can be merged, therefore we set previousContentWasStringLiteralExpression to false
previousContentWasStringLiteralExpression = false;
}
}
else
{
// Add Simplifier annotation to remove superfluous parenthesis after transformation:
// (1 + 1) + "a" -> $"{1 + 1}a"
var otherExpression = syntaxFacts.IsParenthesizedExpression(piece)
? piece.WithAdditionalAnnotations(Simplifier.Annotation)
: piece;
content.Add(generator.Interpolation(otherExpression.WithoutTrivia()));
}
// Update this variable to be true every time we encounter a new string literal expression
// so we know to concatenate future string literals together if we encounter them.
previousContentWasStringLiteralExpression = currentContentIsStringOrCharacterLiteral;
}
return generator.InterpolatedStringExpression(startToken, content, endToken);
}
private static SyntaxNode ConcatenateTextToTextNode(SyntaxGenerator generator, SyntaxNode interpolatedStringTextNode, string textWithoutQuotes, string value)
{
var existingText = interpolatedStringTextNode.GetFirstToken().Text;
var existingValue = interpolatedStringTextNode.GetFirstToken().ValueText;
var newText = existingText + textWithoutQuotes;
var newValue = existingValue + value;
return generator.InterpolatedStringText(generator.InterpolatedStringTextToken(newText, newValue));
}
protected abstract string GetTextWithoutQuotes(string text, bool isVerbatimStringLiteral, bool isCharacterLiteral);
private void CollectPiecesDown(
ISyntaxFactsService syntaxFacts,
ArrayBuilder<SyntaxNode> pieces,
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (!IsStringConcat(syntaxFacts, node, semanticModel, cancellationToken))
{
pieces.Add(node);
return;
}
syntaxFacts.GetPartsOfBinaryExpression(node, out var left, out var right);
CollectPiecesDown(syntaxFacts, pieces, left, semanticModel, cancellationToken);
pieces.Add(right);
}
private static bool IsStringConcat(
ISyntaxFactsService syntaxFacts, SyntaxNode? expression,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!syntaxFacts.IsBinaryExpression(expression))
{
return false;
}
return semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol is IMethodSymbol method &&
method.MethodKind == MethodKind.BuiltinOperator &&
method.ContainingType?.SpecialType == SpecialType.System_String &&
(method.MetadataName == WellKnownMemberNames.AdditionOperatorName ||
method.MetadataName == WellKnownMemberNames.ConcatenateOperatorName);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Convert_to_interpolated_string, createChangedDocument, nameof(FeaturesResources.Convert_to_interpolated_string))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.ConvertToInterpolatedString
{
/// <summary>
/// Code refactoring that converts expressions of the form: a + b + " str " + d + e
/// into:
/// $"{a + b} str {d}{e}".
/// </summary>
internal abstract class AbstractConvertConcatenationToInterpolatedStringRefactoringProvider<TExpressionSyntax> : CodeRefactoringProvider
where TExpressionSyntax : SyntaxNode
{
protected abstract bool SupportsConstantInterpolatedStrings(Document document);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var possibleExpressions = await context.GetRelevantNodesAsync<TExpressionSyntax>().ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// let's take the largest (last) StringConcat we can given current textSpan
var top = possibleExpressions
.Where(expr => IsStringConcat(syntaxFacts, expr, semanticModel, cancellationToken))
.LastOrDefault();
if (top == null)
{
return;
}
if (!SupportsConstantInterpolatedStrings(context.Document))
{
// if there is a const keyword, the refactoring shouldn't show because interpolated string is not const string
var declarator = top.FirstAncestorOrSelf<SyntaxNode>(syntaxFacts.IsVariableDeclarator);
if (declarator != null)
{
var generator = SyntaxGenerator.GetGenerator(document);
if (generator.GetModifiers(declarator).IsConst)
{
return;
}
}
}
// Currently we can concatenate only full subtrees. Therefore we can't support arbitrary selection. We could
// theoretically support selecting the selections that correspond to full sub-trees (e.g. prefixes of
// correct length but from UX point of view that it would feel arbitrary).
// Thus, we only support selection that takes the whole topmost expression. It breaks some leniency around under-selection
// but it's the best solution so far.
if (CodeRefactoringHelpers.IsNodeUnderselected(top, textSpan) ||
IsStringConcat(syntaxFacts, top.Parent, semanticModel, cancellationToken))
{
return;
}
// Now walk down the concatenation collecting all the pieces that we are
// concatenating.
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var pieces);
CollectPiecesDown(syntaxFacts, pieces, top, semanticModel, cancellationToken);
var stringLiterals = pieces
.Where(x => syntaxFacts.IsStringLiteralExpression(x) || syntaxFacts.IsCharacterLiteralExpression(x))
.ToImmutableArray();
// If the entire expression is just concatenated strings, then don't offer to
// make an interpolated string. The user likely manually split this for
// readability.
if (stringLiterals.Length == pieces.Count)
{
return;
}
var isVerbatimStringLiteral = false;
if (stringLiterals.Length > 0)
{
// Make sure that all the string tokens we're concatenating are the same type
// of string literal. i.e. if we have an expression like: @" "" " + " \r\n "
// then we don't merge this. We don't want to be munging different types of
// escape sequences in these strings, so we only support combining the string
// tokens if they're all the same type.
var firstStringToken = stringLiterals[0].GetFirstToken();
isVerbatimStringLiteral = syntaxFacts.IsVerbatimStringLiteral(firstStringToken);
if (stringLiterals.Any(
lit => isVerbatimStringLiteral != syntaxFacts.IsVerbatimStringLiteral(lit.GetFirstToken())))
{
return;
}
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var interpolatedString = CreateInterpolatedString(document, isVerbatimStringLiteral, pieces);
context.RegisterRefactoring(
new MyCodeAction(
_ => UpdateDocumentAsync(document, root, top, interpolatedString)),
top.Span);
}
private static Task<Document> UpdateDocumentAsync(Document document, SyntaxNode root, SyntaxNode top, SyntaxNode interpolatedString)
{
var newRoot = root.ReplaceNode(top, interpolatedString);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
protected SyntaxNode CreateInterpolatedString(
Document document, bool isVerbatimStringLiteral, ArrayBuilder<SyntaxNode> pieces)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var generator = SyntaxGenerator.GetGenerator(document);
var startToken = generator.CreateInterpolatedStringStartToken(isVerbatimStringLiteral)
.WithLeadingTrivia(pieces.First().GetLeadingTrivia());
var endToken = generator.CreateInterpolatedStringEndToken()
.WithTrailingTrivia(pieces.Last().GetTrailingTrivia());
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(pieces.Count, out var content);
var previousContentWasStringLiteralExpression = false;
foreach (var piece in pieces)
{
var isCharacterLiteral = syntaxFacts.IsCharacterLiteralExpression(piece);
var currentContentIsStringOrCharacterLiteral = syntaxFacts.IsStringLiteralExpression(piece) || isCharacterLiteral;
if (currentContentIsStringOrCharacterLiteral)
{
var text = piece.GetFirstToken().Text;
var value = piece.GetFirstToken().Value?.ToString() ?? piece.GetFirstToken().ValueText;
var textWithEscapedBraces = text.Replace("{", "{{").Replace("}", "}}");
var valueTextWithEscapedBraces = value.Replace("{", "{{").Replace("}", "}}");
var textWithoutQuotes = GetTextWithoutQuotes(textWithEscapedBraces, isVerbatimStringLiteral, isCharacterLiteral);
if (previousContentWasStringLiteralExpression)
{
// Last part we added to the content list was also an interpolated-string-text-node.
// We need to combine these as the API for creating an interpolated strings
// does not expect to be given a list containing non-contiguous string nodes.
// Essentially if we combine '"A" + 1 + "B" + "C"' into '$"A{1}BC"' it must be:
// {InterpolatedStringText}{Interpolation}{InterpolatedStringText}
// not:
// {InterpolatedStringText}{Interpolation}{InterpolatedStringText}{InterpolatedStringText}
var existingInterpolatedStringTextNode = content.Last();
var newText = ConcatenateTextToTextNode(generator, existingInterpolatedStringTextNode, textWithoutQuotes, valueTextWithEscapedBraces);
content[^1] = newText;
}
else
{
// This is either the first string literal we have encountered or it is the most recent one we've seen
// after adding an interpolation. Add a new interpolated-string-text-node to the list.
content.Add(generator.InterpolatedStringText(generator.InterpolatedStringTextToken(textWithoutQuotes, valueTextWithEscapedBraces)));
}
}
else if (syntaxFacts.IsInterpolatedStringExpression(piece) &&
syntaxFacts.IsVerbatimInterpolatedStringExpression(piece) == isVerbatimStringLiteral)
{
// "piece" is itself an interpolated string (of the same "verbatimity" as the new interpolated string)
// "a" + $"{1+ 1}" -> instead of $"a{$"{1 + 1}"}" inline the interpolated part: $"a{1 + 1}"
syntaxFacts.GetPartsOfInterpolationExpression(piece, out var _, out var contentParts, out var _);
foreach (var contentPart in contentParts)
{
// Track the state of currentContentIsStringOrCharacterLiteral for the inlined parts
// so any text at the end of piece can be merge with the next string literal:
// $"{1 + 1}a" + "b" -> "a" and "b" get merged in the next "pieces" loop
currentContentIsStringOrCharacterLiteral = syntaxFacts.IsInterpolatedStringText(contentPart);
if (currentContentIsStringOrCharacterLiteral && previousContentWasStringLiteralExpression)
{
// if piece starts with a text and the previous part was a string, merge the two parts (see also above)
// "a" + $"b{1 + 1}" -> "a" and "b" get merged
var newText = ConcatenateTextToTextNode(generator, content.Last(), contentPart.GetFirstToken().Text, contentPart.GetFirstToken().ValueText);
content[^1] = newText;
}
else
{
content.Add(contentPart);
}
// Only the first contentPart can be merged, therefore we set previousContentWasStringLiteralExpression to false
previousContentWasStringLiteralExpression = false;
}
}
else
{
// Add Simplifier annotation to remove superfluous parenthesis after transformation:
// (1 + 1) + "a" -> $"{1 + 1}a"
var otherExpression = syntaxFacts.IsParenthesizedExpression(piece)
? piece.WithAdditionalAnnotations(Simplifier.Annotation)
: piece;
content.Add(generator.Interpolation(otherExpression.WithoutTrivia()));
}
// Update this variable to be true every time we encounter a new string literal expression
// so we know to concatenate future string literals together if we encounter them.
previousContentWasStringLiteralExpression = currentContentIsStringOrCharacterLiteral;
}
return generator.InterpolatedStringExpression(startToken, content, endToken);
}
private static SyntaxNode ConcatenateTextToTextNode(SyntaxGenerator generator, SyntaxNode interpolatedStringTextNode, string textWithoutQuotes, string value)
{
var existingText = interpolatedStringTextNode.GetFirstToken().Text;
var existingValue = interpolatedStringTextNode.GetFirstToken().ValueText;
var newText = existingText + textWithoutQuotes;
var newValue = existingValue + value;
return generator.InterpolatedStringText(generator.InterpolatedStringTextToken(newText, newValue));
}
protected abstract string GetTextWithoutQuotes(string text, bool isVerbatimStringLiteral, bool isCharacterLiteral);
private void CollectPiecesDown(
ISyntaxFactsService syntaxFacts,
ArrayBuilder<SyntaxNode> pieces,
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (!IsStringConcat(syntaxFacts, node, semanticModel, cancellationToken))
{
pieces.Add(node);
return;
}
syntaxFacts.GetPartsOfBinaryExpression(node, out var left, out var right);
CollectPiecesDown(syntaxFacts, pieces, left, semanticModel, cancellationToken);
pieces.Add(right);
}
private static bool IsStringConcat(
ISyntaxFactsService syntaxFacts, SyntaxNode? expression,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!syntaxFacts.IsBinaryExpression(expression))
{
return false;
}
return semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol is IMethodSymbol method &&
method.MethodKind == MethodKind.BuiltinOperator &&
method.ContainingType?.SpecialType == SpecialType.System_String &&
(method.MetadataName == WellKnownMemberNames.AdditionOperatorName ||
method.MetadataName == WellKnownMemberNames.ConcatenateOperatorName);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Convert_to_interpolated_string, createChangedDocument, nameof(FeaturesResources.Convert_to_interpolated_string))
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Core/Shared/Tagging/EventSources/AbstractWorkspaceTrackingTaggerEventSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
/// <summary>
/// An abstract implementation of a tagger event source that takes a buffer and tracks
/// the workspace that it's attached to.
/// </summary>
internal abstract class AbstractWorkspaceTrackingTaggerEventSource : AbstractTaggerEventSource
{
private readonly WorkspaceRegistration _workspaceRegistration;
protected ITextBuffer SubjectBuffer { get; }
protected Workspace? CurrentWorkspace { get; private set; }
protected AbstractWorkspaceTrackingTaggerEventSource(ITextBuffer subjectBuffer)
{
this.SubjectBuffer = subjectBuffer;
_workspaceRegistration = Workspace.GetWorkspaceRegistration(subjectBuffer.AsTextContainer());
}
protected abstract void ConnectToWorkspace(Workspace workspace);
protected abstract void DisconnectFromWorkspace(Workspace workspace);
public override void Connect()
{
this.CurrentWorkspace = _workspaceRegistration.Workspace;
_workspaceRegistration.WorkspaceChanged += OnWorkspaceRegistrationChanged;
if (this.CurrentWorkspace != null)
{
ConnectToWorkspace(this.CurrentWorkspace);
}
}
private void OnWorkspaceRegistrationChanged(object? sender, EventArgs e)
{
if (this.CurrentWorkspace != null)
{
DisconnectFromWorkspace(this.CurrentWorkspace);
}
this.CurrentWorkspace = _workspaceRegistration.Workspace;
if (this.CurrentWorkspace != null)
{
ConnectToWorkspace(this.CurrentWorkspace);
}
}
public override void Disconnect()
{
if (this.CurrentWorkspace != null)
{
DisconnectFromWorkspace(this.CurrentWorkspace);
this.CurrentWorkspace = null;
}
_workspaceRegistration.WorkspaceChanged -= OnWorkspaceRegistrationChanged;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
/// <summary>
/// An abstract implementation of a tagger event source that takes a buffer and tracks
/// the workspace that it's attached to.
/// </summary>
internal abstract class AbstractWorkspaceTrackingTaggerEventSource : AbstractTaggerEventSource
{
private readonly WorkspaceRegistration _workspaceRegistration;
protected ITextBuffer SubjectBuffer { get; }
protected Workspace? CurrentWorkspace { get; private set; }
protected AbstractWorkspaceTrackingTaggerEventSource(ITextBuffer subjectBuffer)
{
this.SubjectBuffer = subjectBuffer;
_workspaceRegistration = Workspace.GetWorkspaceRegistration(subjectBuffer.AsTextContainer());
}
protected abstract void ConnectToWorkspace(Workspace workspace);
protected abstract void DisconnectFromWorkspace(Workspace workspace);
public override void Connect()
{
this.CurrentWorkspace = _workspaceRegistration.Workspace;
_workspaceRegistration.WorkspaceChanged += OnWorkspaceRegistrationChanged;
if (this.CurrentWorkspace != null)
{
ConnectToWorkspace(this.CurrentWorkspace);
}
}
private void OnWorkspaceRegistrationChanged(object? sender, EventArgs e)
{
if (this.CurrentWorkspace != null)
{
DisconnectFromWorkspace(this.CurrentWorkspace);
}
this.CurrentWorkspace = _workspaceRegistration.Workspace;
if (this.CurrentWorkspace != null)
{
ConnectToWorkspace(this.CurrentWorkspace);
}
}
public override void Disconnect()
{
if (this.CurrentWorkspace != null)
{
DisconnectFromWorkspace(this.CurrentWorkspace);
this.CurrentWorkspace = null;
}
_workspaceRegistration.WorkspaceChanged -= OnWorkspaceRegistrationChanged;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/CSharp/Portable/QuickInfo/CSharpSyntacticQuickInfoProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.QuickInfo
{
[ExportQuickInfoProvider(QuickInfoProviderNames.Syntactic, LanguageNames.CSharp), Shared]
[ExtensionOrder(After = QuickInfoProviderNames.Semantic)]
internal class CSharpSyntacticQuickInfoProvider : CommonQuickInfoProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSyntacticQuickInfoProvider()
{
}
protected override Task<QuickInfoItem?> BuildQuickInfoAsync(
QuickInfoContext context,
SyntaxToken token)
=> Task.FromResult(BuildQuickInfo(token));
protected override Task<QuickInfoItem?> BuildQuickInfoAsync(
CommonQuickInfoContext context,
SyntaxToken token)
=> Task.FromResult(BuildQuickInfo(token));
private static QuickInfoItem? BuildQuickInfo(SyntaxToken token)
{
if (token.Kind() != SyntaxKind.CloseBraceToken)
{
return null;
}
// Don't show for interpolations
if (token.Parent.IsKind(SyntaxKind.Interpolation, out InterpolationSyntax? interpolation) &&
interpolation.CloseBraceToken == token)
{
return null;
}
// Now check if we can find an open brace.
var parent = token.Parent!;
var openBrace = parent.ChildNodesAndTokens().FirstOrDefault(n => n.Kind() == SyntaxKind.OpenBraceToken).AsToken();
if (openBrace.Kind() != SyntaxKind.OpenBraceToken)
{
return null;
}
var spanStart = parent.SpanStart;
var spanEnd = openBrace.Span.End;
// If the parent is a scope block, check and include nearby comments around the open brace
// LeadingTrivia is preferred
if (IsScopeBlock(parent))
{
MarkInterestedSpanNearbyScopeBlock(parent, openBrace, ref spanStart, ref spanEnd);
}
// If the parent is a child of a property/method declaration, object/array creation, or control flow node,
// then walk up one higher so we can show more useful context
else if (parent.GetFirstToken() == openBrace)
{
// parent.Parent must be non-null, because for GetFirstToken() to have returned something it would have had to walk up to its parent
spanStart = parent.Parent!.SpanStart;
}
// encode document spans that correspond to the text to show
var spans = ImmutableArray.Create(TextSpan.FromBounds(spanStart, spanEnd));
return QuickInfoItem.Create(token.Span, relatedSpans: spans);
}
private static bool IsScopeBlock(SyntaxNode node)
{
var parent = node.Parent;
return node.IsKind(SyntaxKind.Block)
&& (parent.IsKind(SyntaxKind.Block)
|| parent.IsKind(SyntaxKind.SwitchSection)
|| parent.IsKind(SyntaxKind.GlobalStatement));
}
private static void MarkInterestedSpanNearbyScopeBlock(SyntaxNode block, SyntaxToken openBrace, ref int spanStart, ref int spanEnd)
{
var searchListAbove = openBrace.LeadingTrivia.Reverse();
if (TryFindFurthestNearbyComment(ref searchListAbove, out var nearbyComment))
{
spanStart = nearbyComment.SpanStart;
return;
}
var nextToken = block.FindToken(openBrace.FullSpan.End);
var searchListBelow = nextToken.LeadingTrivia;
if (TryFindFurthestNearbyComment(ref searchListBelow, out nearbyComment))
{
spanEnd = nearbyComment.Span.End;
return;
}
}
private static bool TryFindFurthestNearbyComment<T>(ref T triviaSearchList, out SyntaxTrivia nearbyTrivia)
where T : IEnumerable<SyntaxTrivia>
{
nearbyTrivia = default;
foreach (var trivia in triviaSearchList)
{
if (trivia.IsSingleOrMultiLineComment())
{
nearbyTrivia = trivia;
}
else if (!trivia.IsKind(SyntaxKind.WhitespaceTrivia) && !trivia.IsKind(SyntaxKind.EndOfLineTrivia))
{
break;
}
}
return nearbyTrivia.IsSingleOrMultiLineComment();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.QuickInfo
{
[ExportQuickInfoProvider(QuickInfoProviderNames.Syntactic, LanguageNames.CSharp), Shared]
[ExtensionOrder(After = QuickInfoProviderNames.Semantic)]
internal class CSharpSyntacticQuickInfoProvider : CommonQuickInfoProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpSyntacticQuickInfoProvider()
{
}
protected override Task<QuickInfoItem?> BuildQuickInfoAsync(
QuickInfoContext context,
SyntaxToken token)
=> Task.FromResult(BuildQuickInfo(token));
protected override Task<QuickInfoItem?> BuildQuickInfoAsync(
CommonQuickInfoContext context,
SyntaxToken token)
=> Task.FromResult(BuildQuickInfo(token));
private static QuickInfoItem? BuildQuickInfo(SyntaxToken token)
{
if (token.Kind() != SyntaxKind.CloseBraceToken)
{
return null;
}
// Don't show for interpolations
if (token.Parent.IsKind(SyntaxKind.Interpolation, out InterpolationSyntax? interpolation) &&
interpolation.CloseBraceToken == token)
{
return null;
}
// Now check if we can find an open brace.
var parent = token.Parent!;
var openBrace = parent.ChildNodesAndTokens().FirstOrDefault(n => n.Kind() == SyntaxKind.OpenBraceToken).AsToken();
if (openBrace.Kind() != SyntaxKind.OpenBraceToken)
{
return null;
}
var spanStart = parent.SpanStart;
var spanEnd = openBrace.Span.End;
// If the parent is a scope block, check and include nearby comments around the open brace
// LeadingTrivia is preferred
if (IsScopeBlock(parent))
{
MarkInterestedSpanNearbyScopeBlock(parent, openBrace, ref spanStart, ref spanEnd);
}
// If the parent is a child of a property/method declaration, object/array creation, or control flow node,
// then walk up one higher so we can show more useful context
else if (parent.GetFirstToken() == openBrace)
{
// parent.Parent must be non-null, because for GetFirstToken() to have returned something it would have had to walk up to its parent
spanStart = parent.Parent!.SpanStart;
}
// encode document spans that correspond to the text to show
var spans = ImmutableArray.Create(TextSpan.FromBounds(spanStart, spanEnd));
return QuickInfoItem.Create(token.Span, relatedSpans: spans);
}
private static bool IsScopeBlock(SyntaxNode node)
{
var parent = node.Parent;
return node.IsKind(SyntaxKind.Block)
&& (parent.IsKind(SyntaxKind.Block)
|| parent.IsKind(SyntaxKind.SwitchSection)
|| parent.IsKind(SyntaxKind.GlobalStatement));
}
private static void MarkInterestedSpanNearbyScopeBlock(SyntaxNode block, SyntaxToken openBrace, ref int spanStart, ref int spanEnd)
{
var searchListAbove = openBrace.LeadingTrivia.Reverse();
if (TryFindFurthestNearbyComment(ref searchListAbove, out var nearbyComment))
{
spanStart = nearbyComment.SpanStart;
return;
}
var nextToken = block.FindToken(openBrace.FullSpan.End);
var searchListBelow = nextToken.LeadingTrivia;
if (TryFindFurthestNearbyComment(ref searchListBelow, out nearbyComment))
{
spanEnd = nearbyComment.Span.End;
return;
}
}
private static bool TryFindFurthestNearbyComment<T>(ref T triviaSearchList, out SyntaxTrivia nearbyTrivia)
where T : IEnumerable<SyntaxTrivia>
{
nearbyTrivia = default;
foreach (var trivia in triviaSearchList)
{
if (trivia.IsSingleOrMultiLineComment())
{
nearbyTrivia = trivia;
}
else if (!trivia.IsKind(SyntaxKind.WhitespaceTrivia) && !trivia.IsKind(SyntaxKind.EndOfLineTrivia))
{
break;
}
}
return nearbyTrivia.IsSingleOrMultiLineComment();
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.BinarySearch.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.BinarySearch.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.Linq;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of the List class.
/// </summary>
public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T>
{
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void BinarySearch_ForEveryItemWithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
foreach (T item in list)
while (list.Count((value) => value.Equals(item)) > 1)
list.Remove(item);
list.Sort();
SegmentedList<T> beforeList = list.ToSegmentedList();
Assert.All(Enumerable.Range(0, list.Count), index =>
{
Assert.Equal(index, list.BinarySearch(beforeList[index]));
Assert.Equal(index, list.BinarySearch(beforeList[index], GetIComparer()));
Assert.Equal(beforeList[index], list[index]);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void BinarySearch_ForEveryItemWithDuplicates(int count)
{
if (count > 0)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
list.Sort();
SegmentedList<T> beforeList = list.ToSegmentedList();
Assert.All(Enumerable.Range(0, list.Count), index =>
{
Assert.True(list.BinarySearch(beforeList[index]) >= 0);
Assert.True(list.BinarySearch(beforeList[index], GetIComparer()) >= 0);
Assert.Equal(beforeList[index], list[index]);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void BinarySearch_Validations(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Sort();
T element = CreateT(3215);
Assert.Throws<ArgumentException>(null, () => list.BinarySearch(0, count + 1, element, GetIComparer())); //"Finding items longer than array should throw ArgumentException"
Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(-1, count, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative index."
Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(0, -1, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative count."
Assert.Throws<ArgumentException>(null, () => list.BinarySearch(count + 1, count, element, GetIComparer())); //"ArgumentException should be thrown on index greater than length of array."
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.BinarySearch.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.Linq;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of the List class.
/// </summary>
public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T>
{
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void BinarySearch_ForEveryItemWithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
foreach (T item in list)
while (list.Count((value) => value.Equals(item)) > 1)
list.Remove(item);
list.Sort();
SegmentedList<T> beforeList = list.ToSegmentedList();
Assert.All(Enumerable.Range(0, list.Count), index =>
{
Assert.Equal(index, list.BinarySearch(beforeList[index]));
Assert.Equal(index, list.BinarySearch(beforeList[index], GetIComparer()));
Assert.Equal(beforeList[index], list[index]);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void BinarySearch_ForEveryItemWithDuplicates(int count)
{
if (count > 0)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
list.Sort();
SegmentedList<T> beforeList = list.ToSegmentedList();
Assert.All(Enumerable.Range(0, list.Count), index =>
{
Assert.True(list.BinarySearch(beforeList[index]) >= 0);
Assert.True(list.BinarySearch(beforeList[index], GetIComparer()) >= 0);
Assert.Equal(beforeList[index], list[index]);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void BinarySearch_Validations(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Sort();
T element = CreateT(3215);
Assert.Throws<ArgumentException>(null, () => list.BinarySearch(0, count + 1, element, GetIComparer())); //"Finding items longer than array should throw ArgumentException"
Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(-1, count, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative index."
Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(0, -1, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative count."
Assert.Throws<ArgumentException>(null, () => list.BinarySearch(count + 1, count, element, GetIComparer())); //"ArgumentException should be thrown on index greater than length of array."
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics.EngineV2;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
[Export(typeof(IDiagnosticAnalyzerService))]
[Shared]
internal partial class DiagnosticAnalyzerService : IDiagnosticAnalyzerService
{
private const string DiagnosticsUpdatedEventName = "DiagnosticsUpdated";
// use eventMap and taskQueue to serialize events
private readonly EventMap _eventMap;
private readonly TaskQueue _eventQueue;
public DiagnosticAnalyzerInfoCache AnalyzerInfoCache { get; private set; }
public IAsynchronousOperationListener Listener { get; }
private readonly ConditionalWeakTable<Workspace, DiagnosticIncrementalAnalyzer> _map;
private readonly ConditionalWeakTable<Workspace, DiagnosticIncrementalAnalyzer>.CreateValueCallback _createIncrementalAnalyzer;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DiagnosticAnalyzerService(
IDiagnosticUpdateSourceRegistrationService registrationService,
IAsynchronousOperationListenerProvider listenerProvider)
{
AnalyzerInfoCache = new DiagnosticAnalyzerInfoCache();
Listener = listenerProvider.GetListener(FeatureAttribute.DiagnosticService);
_map = new ConditionalWeakTable<Workspace, DiagnosticIncrementalAnalyzer>();
_createIncrementalAnalyzer = CreateIncrementalAnalyzerCallback;
_eventMap = new EventMap();
_eventQueue = new TaskQueue(Listener, TaskScheduler.Default);
registrationService.Register(this);
}
public void Reanalyze(Workspace workspace, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false)
{
var service = workspace.Services.GetService<ISolutionCrawlerService>();
if (service != null && _map.TryGetValue(workspace, out var analyzer))
{
service.Reanalyze(workspace, analyzer, projectIds, documentIds, highPriority);
}
}
public Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, ArrayBuilder<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(document.Project.Solution.Workspace, out var analyzer))
{
// always make sure that analyzer is called on background thread.
return Task.Run(() => analyzer.TryAppendDiagnosticsForSpanAsync(
document, range, diagnostics, diagnosticId: null, includeSuppressedDiagnostics, CodeActionRequestPriority.None, blockForData: false, addOperationScope: null, cancellationToken), cancellationToken);
}
return SpecializedTasks.False;
}
public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForSpanAsync(
Document document,
TextSpan? range,
string? diagnosticId,
bool includeSuppressedDiagnostics,
CodeActionRequestPriority priority,
Func<string, IDisposable?>? addOperationScope,
CancellationToken cancellationToken)
{
if (_map.TryGetValue(document.Project.Solution.Workspace, out var analyzer))
{
// always make sure that analyzer is called on background thread.
return Task.Run(() => analyzer.GetDiagnosticsForSpanAsync(
document, range, diagnosticId, includeSuppressedDiagnostics, priority,
blockForData: true, addOperationScope, cancellationToken), cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(workspace, out var analyzer))
{
return analyzer.GetCachedDiagnosticsAsync(workspace.CurrentSolution, projectId, documentId, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Workspace workspace, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(workspace, out var analyzer))
{
return analyzer.GetSpecificCachedDiagnosticsAsync(workspace.CurrentSolution, id, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
return analyzer.GetDiagnosticsAsync(solution, projectId, documentId, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public async Task ForceAnalyzeAsync(Solution solution, Action<Project> onProjectAnalyzed, ProjectId? projectId = null, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
if (projectId != null)
{
var project = solution.GetProject(projectId);
if (project != null)
{
await analyzer.ForceAnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false);
onProjectAnalyzed(project);
}
}
else
{
var tasks = new Task[solution.ProjectIds.Count];
var index = 0;
foreach (var project in solution.Projects)
{
tasks[index++] = Task.Run(async () =>
{
await analyzer.ForceAnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false);
onProjectAnalyzed(project);
}, cancellationToken);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
}
public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(
Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
return analyzer.GetDiagnosticsForIdsAsync(solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(
Solution solution, ProjectId? projectId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
return analyzer.GetProjectDiagnosticsForIdsAsync(solution, projectId, diagnosticIds, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public bool ContainsDiagnostics(Workspace workspace, ProjectId projectId)
{
if (_map.TryGetValue(workspace, out var analyzer))
{
return analyzer.ContainsDiagnostics(projectId);
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Diagnostics.EngineV2;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
[Export(typeof(IDiagnosticAnalyzerService))]
[Shared]
internal partial class DiagnosticAnalyzerService : IDiagnosticAnalyzerService
{
private const string DiagnosticsUpdatedEventName = "DiagnosticsUpdated";
// use eventMap and taskQueue to serialize events
private readonly EventMap _eventMap;
private readonly TaskQueue _eventQueue;
public DiagnosticAnalyzerInfoCache AnalyzerInfoCache { get; private set; }
public IAsynchronousOperationListener Listener { get; }
private readonly ConditionalWeakTable<Workspace, DiagnosticIncrementalAnalyzer> _map;
private readonly ConditionalWeakTable<Workspace, DiagnosticIncrementalAnalyzer>.CreateValueCallback _createIncrementalAnalyzer;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DiagnosticAnalyzerService(
IDiagnosticUpdateSourceRegistrationService registrationService,
IAsynchronousOperationListenerProvider listenerProvider)
{
AnalyzerInfoCache = new DiagnosticAnalyzerInfoCache();
Listener = listenerProvider.GetListener(FeatureAttribute.DiagnosticService);
_map = new ConditionalWeakTable<Workspace, DiagnosticIncrementalAnalyzer>();
_createIncrementalAnalyzer = CreateIncrementalAnalyzerCallback;
_eventMap = new EventMap();
_eventQueue = new TaskQueue(Listener, TaskScheduler.Default);
registrationService.Register(this);
}
public void Reanalyze(Workspace workspace, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false)
{
var service = workspace.Services.GetService<ISolutionCrawlerService>();
if (service != null && _map.TryGetValue(workspace, out var analyzer))
{
service.Reanalyze(workspace, analyzer, projectIds, documentIds, highPriority);
}
}
public Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, ArrayBuilder<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(document.Project.Solution.Workspace, out var analyzer))
{
// always make sure that analyzer is called on background thread.
return Task.Run(() => analyzer.TryAppendDiagnosticsForSpanAsync(
document, range, diagnostics, diagnosticId: null, includeSuppressedDiagnostics, CodeActionRequestPriority.None, blockForData: false, addOperationScope: null, cancellationToken), cancellationToken);
}
return SpecializedTasks.False;
}
public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForSpanAsync(
Document document,
TextSpan? range,
string? diagnosticId,
bool includeSuppressedDiagnostics,
CodeActionRequestPriority priority,
Func<string, IDisposable?>? addOperationScope,
CancellationToken cancellationToken)
{
if (_map.TryGetValue(document.Project.Solution.Workspace, out var analyzer))
{
// always make sure that analyzer is called on background thread.
return Task.Run(() => analyzer.GetDiagnosticsForSpanAsync(
document, range, diagnosticId, includeSuppressedDiagnostics, priority,
blockForData: true, addOperationScope, cancellationToken), cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Workspace workspace, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(workspace, out var analyzer))
{
return analyzer.GetCachedDiagnosticsAsync(workspace.CurrentSolution, projectId, documentId, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Workspace workspace, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(workspace, out var analyzer))
{
return analyzer.GetSpecificCachedDiagnosticsAsync(workspace.CurrentSolution, id, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
return analyzer.GetDiagnosticsAsync(solution, projectId, documentId, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public async Task ForceAnalyzeAsync(Solution solution, Action<Project> onProjectAnalyzed, ProjectId? projectId = null, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
if (projectId != null)
{
var project = solution.GetProject(projectId);
if (project != null)
{
await analyzer.ForceAnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false);
onProjectAnalyzed(project);
}
}
else
{
var tasks = new Task[solution.ProjectIds.Count];
var index = 0;
foreach (var project in solution.Projects)
{
tasks[index++] = Task.Run(async () =>
{
await analyzer.ForceAnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false);
onProjectAnalyzed(project);
}, cancellationToken);
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
}
public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(
Solution solution, ProjectId? projectId = null, DocumentId? documentId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
return analyzer.GetDiagnosticsForIdsAsync(solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(
Solution solution, ProjectId? projectId = null, ImmutableHashSet<string>? diagnosticIds = null, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
if (_map.TryGetValue(solution.Workspace, out var analyzer))
{
return analyzer.GetProjectDiagnosticsForIdsAsync(solution, projectId, diagnosticIds, includeSuppressedDiagnostics, cancellationToken);
}
return SpecializedTasks.EmptyImmutableArray<DiagnosticData>();
}
public bool ContainsDiagnostics(Workspace workspace, ProjectId projectId)
{
if (_map.TryGetValue(workspace, out var analyzer))
{
return analyzer.ContainsDiagnostics(projectId);
}
return false;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharpTest/AutomaticCompletion/AutomaticLiteralCompletionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AutomaticCompletion
{
public class AutomaticLiteralCompletionTests : AbstractAutomaticBraceCompletionTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Creation()
{
using var session = CreateSessionSingleQuote("$$");
Assert.NotNull(session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void String_TopLevel()
{
using var session = CreateSessionDoubleQuote("$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void VerbatimString_TopLevel()
{
using var session = CreateSessionDoubleQuote("@$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void Char_TopLevel()
{
using var session = CreateSessionSingleQuote("$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void String_TopLevel2()
{
using var session = CreateSessionDoubleQuote("using System;$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void VerbatimString_TopLevel2()
{
using var session = CreateSessionDoubleQuote("using System;@$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void String_String()
{
var code = @"class C
{
void Method()
{
var s = """"$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void String_VerbatimString()
{
var code = @"class C
{
void Method()
{
var s = """"@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void String_Char()
{
var code = @"class C
{
void Method()
{
var s = @""""$$
}
}";
using var session = CreateSessionSingleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String_Delete()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String_Tab()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String_Quotation()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String_Delete()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String_Tab()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String_Quotation()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString_Delete()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString_Tab()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString_Quotation()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString_Delete()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString_Tab()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString_Quotation()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Preprocessor1()
{
var code = @"class C
{
void Method()
{
#line $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Preprocessor2()
{
var code = @"class C
{
void Method()
{
#line $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Preprocessor3()
{
var code = @"class C
{
void Method()
{
#line $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WorkItem(546047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546047")]
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimStringDoubleQuote()
{
var code = @"class C
{
void Method()
{
var s = @""""$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session, expectValidSession: false);
}
internal static Holder CreateSessionSingleQuote(string code)
{
return CreateSession(
TestWorkspace.CreateCSharp(code),
SingleQuote.OpenCharacter, SingleQuote.CloseCharacter);
}
internal static Holder CreateSessionDoubleQuote(string code)
{
return CreateSession(
TestWorkspace.CreateCSharp(code),
DoubleQuote.OpenCharacter, DoubleQuote.CloseCharacter);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Implementation.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AutomaticCompletion
{
public class AutomaticLiteralCompletionTests : AbstractAutomaticBraceCompletionTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Creation()
{
using var session = CreateSessionSingleQuote("$$");
Assert.NotNull(session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void String_TopLevel()
{
using var session = CreateSessionDoubleQuote("$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void VerbatimString_TopLevel()
{
using var session = CreateSessionDoubleQuote("@$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void Char_TopLevel()
{
using var session = CreateSessionSingleQuote("$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void String_TopLevel2()
{
using var session = CreateSessionDoubleQuote("using System;$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public void VerbatimString_TopLevel2()
{
using var session = CreateSessionDoubleQuote("using System;@$$");
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void String_String()
{
var code = @"class C
{
void Method()
{
var s = """"$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void String_VerbatimString()
{
var code = @"class C
{
void Method()
{
var s = """"@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void String_Char()
{
var code = @"class C
{
void Method()
{
var s = @""""$$
}
}";
using var session = CreateSessionSingleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String_Delete()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String_Tab()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_String_Quotation()
{
var code = @"class C
{
void Method()
{
var s = $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String_Delete()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String_Tab()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_String_Quotation()
{
var code = @"class C
{
void Method()
{
var s = @$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString_Delete()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString_Tab()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Method_InterpolatedString_Quotation()
{
var code = @"class C
{
void Method()
{
var s = $[||]$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString_Delete()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString_Tab()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimMethod_InterpolatedString_Quotation()
{
var code = @"class C
{
void Method()
{
var s = $@$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Preprocessor1()
{
var code = @"class C
{
void Method()
{
#line $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckTab(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Preprocessor2()
{
var code = @"class C
{
void Method()
{
#line $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckOverType(session.Session);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void Preprocessor3()
{
var code = @"class C
{
void Method()
{
#line $$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session);
CheckBackspace(session.Session);
}
[WorkItem(546047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546047")]
[WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)]
public void VerbatimStringDoubleQuote()
{
var code = @"class C
{
void Method()
{
var s = @""""$$
}
}";
using var session = CreateSessionDoubleQuote(code);
Assert.NotNull(session);
CheckStart(session.Session, expectValidSession: false);
}
internal static Holder CreateSessionSingleQuote(string code)
{
return CreateSession(
TestWorkspace.CreateCSharp(code),
SingleQuote.OpenCharacter, SingleQuote.CloseCharacter);
}
internal static Holder CreateSessionDoubleQuote(string code)
{
return CreateSession(
TestWorkspace.CreateCSharp(code),
DoubleQuote.OpenCharacter, DoubleQuote.CloseCharacter);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Test2/Simplification/TypeInferenceSimplifierTests.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.Options
Imports Microsoft.CodeAnalysis.Simplification
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class TypeInferenceSimplifierTests
Inherits AbstractSimplificationTests
<WorkItem(734369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734369")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
End Class
Class B
Inherits C
Public Shared Function Goo() As Integer
End Function
End Class
Module Program
Sub Main(args As String())
Dim {|SimplifyParent:AA|}
Dim {|SimplifyParent:A As Integer|}
Dim {|SimplifyParent:F(), G() As String|}
Dim {|SimplifyParent:M() As String|}, {|SimplifyParent:N() As String|}
Dim {|SimplifyParent:E As String = 5|}
Dim {|SimplifyParent:arr(,) As Double = {{1,2},{3,2}}|}
Dim {|SimplifyParent:arri() As Double = {1,2}|}
Dim {|SimplifyParent:x As IEnumerable(Of C) = New List(Of B)|}
Dim {|SimplifyParent:obj As C = New B()|}
Dim {|SimplifyParent:ret as Double = B.Goo()|}
Const {|SimplifyParent:con As Double = 1|}
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class C
End Class
Class B
Inherits C
Public Shared Function Goo() As Integer
End Function
End Class
Module Program
Sub Main(args As String())
Dim AA
Dim A As Integer
Dim F(), G() As String
Dim M() As String, N() As String
Dim E As String = 5
Dim arr(,) As Double = {{1,2},{3,2}}
Dim arri() As Double = {1,2}
Dim x As IEnumerable(Of C) = New List(Of B)
Dim obj As C = New B()
Dim ret as Double = B.Goo()
Const con As Double = 1
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(734369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734369")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_ArrayElementConversion() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
Dim {|SimplifyParent:arr(,) As Double = {{1.9,2},{3,2}}|}
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Module Program
Sub Main(args As String())
Dim arr = {{1.9,2},{3,2}}
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify_Using() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Class D
Inherits B
End Class
Class Program
Sub Main(args As String())
Using {|SimplifyParent:b As B|} = New D()
End Using
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Class D
Inherits B
End Class
Class Program
Sub Main(args As String())
Using b As B = New D()
End Using
End Sub
End Class
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify_For_0() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
For {|SimplifyParent:index As Long|} = 1 To 5
Next
For Each {|SimplifyParent:index As Long|} In New Integer() {1, 2, 3}
Next
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Module Program
Sub Main(args As String())
For index As Long = 1 To 5
Next
For Each index As Long In New Integer() {1, 2, 3}
Next
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify_For_1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each {|SimplifyParent:index As B|} In args
Next
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each index As B In args
Next
End Sub
End Class
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(734377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734377")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports I = System.Int32
Module Program
Public Dim {|SimplifyParent:x As Integer = 5|}
Function Goo() As Integer
End Function
Sub Main(args As String())
Dim {|SimplifyParent:A As Integer = 5|}
Dim {|SimplifyParent:M() As String = New String(){}|}, {|SimplifyParent:N() As String|}
Dim {|SimplifyParent:B(,) As Integer = {{1,2},{2,3}}|}
Dim {|SimplifyParent:ret As Integer = Goo()|}
Const {|SimplifyParent:con As Integer = 1|}
Dim {|SimplifyParent:in As I = 1|}
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports I = System.Int32
Module Program
Public Dim x As Integer = 5
Function Goo() As Integer
End Function
Sub Main(args As String())
Dim A = 5
Dim M = New String(){}, N() As String
Dim B = {{1,2},{2,3}}
Dim ret = Goo()
Const con = 1
Dim in = 1
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports I = System.Int32
Module Program
Sub Main(args As String())
Using {|SimplifyParent:proc As Process|} = New Process
End Using
For {|SimplifyParent:index As Integer|} = 1 To 5
Next
For {|SimplifyParent:index As I|} = 1 to 5
Next
For Each {|SimplifyParent:index As Integer|} In New Integer() {1, 2, 3}
Next
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports I = System.Int32
Module Program
Sub Main(args As String())
Using proc = New Process
End Using
For index = 1 To 5
Next
For index = 1 to 5
Next
For Each index In New Integer() {1, 2, 3}
Next
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_For_1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each {|SimplifyParent:index As Program|} In args
Next
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each index In args
Next
End Sub
End Class
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_For_GenericMethods() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
void Goo<T>(T x);
}
class C : I
{
public void Goo<T>(T x) { }
}
class D : C
{
public void Goo(int x)
{
}
public void Sub()
{
{|SimplifyParent:base.Goo<int>(1)|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
interface I
{
void Goo<T>(T x);
}
class C : I
{
public void Goo<T>(T x) { }
}
class D : C
{
public void Goo(int x)
{
}
public void Sub()
{
base.Goo(1);
}
}]]>
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_For_GenericMethods_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
Public Sub Goo(Of T)(ByRef x As T)
End Sub
End Class
Class D
Inherits C
Public Sub Goo(ByRef x As Integer)
End Sub
Public Sub Test()
Dim x As String
{|SimplifyParent:MyBase.Goo(Of String)(x)|}
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Class C
Public Sub Goo(Of T)(ByRef x As T)
End Sub
End Class
Class D
Inherits C
Public Sub Goo(ByRef x As Integer)
End Sub
Public Sub Test()
Dim x As String
MyBase.Goo(x)
End Sub
End Class
]]>
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(734377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734377")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_ExplicitTypeDecl_FieldDecl() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace X
Module Program
Public Dim {|SimplifyParent:t as Integer = {|SimplifyParent:X.A|}.getInt()|}
Sub Main(args As String())
End Sub
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Namespace X
Module Program
Public Dim t as Integer = A.getInt()
Sub Main(args As String())
End Sub
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(860111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860111")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_ExplicitTypeDecl_MustGetNewSMForAnyReducer() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace Y
Namespace X
Module Program
Public Dim {|SimplifyParent:t as Integer = {|SimplifyParentParent:Y.X.A|}.getInt()|}
Sub Main(args As String())
End Function
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Namespace Y
Namespace X
Module Program
Public Dim t as Integer = A.getInt()
Sub Main(args As String())
End Function
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
End Namespace
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
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.Threading.Tasks
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Simplification
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class TypeInferenceSimplifierTests
Inherits AbstractSimplificationTests
<WorkItem(734369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734369")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
End Class
Class B
Inherits C
Public Shared Function Goo() As Integer
End Function
End Class
Module Program
Sub Main(args As String())
Dim {|SimplifyParent:AA|}
Dim {|SimplifyParent:A As Integer|}
Dim {|SimplifyParent:F(), G() As String|}
Dim {|SimplifyParent:M() As String|}, {|SimplifyParent:N() As String|}
Dim {|SimplifyParent:E As String = 5|}
Dim {|SimplifyParent:arr(,) As Double = {{1,2},{3,2}}|}
Dim {|SimplifyParent:arri() As Double = {1,2}|}
Dim {|SimplifyParent:x As IEnumerable(Of C) = New List(Of B)|}
Dim {|SimplifyParent:obj As C = New B()|}
Dim {|SimplifyParent:ret as Double = B.Goo()|}
Const {|SimplifyParent:con As Double = 1|}
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Class C
End Class
Class B
Inherits C
Public Shared Function Goo() As Integer
End Function
End Class
Module Program
Sub Main(args As String())
Dim AA
Dim A As Integer
Dim F(), G() As String
Dim M() As String, N() As String
Dim E As String = 5
Dim arr(,) As Double = {{1,2},{3,2}}
Dim arri() As Double = {1,2}
Dim x As IEnumerable(Of C) = New List(Of B)
Dim obj As C = New B()
Dim ret as Double = B.Goo()
Const con As Double = 1
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(734369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734369")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_ArrayElementConversion() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
Dim {|SimplifyParent:arr(,) As Double = {{1.9,2},{3,2}}|}
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Module Program
Sub Main(args As String())
Dim arr = {{1.9,2},{3,2}}
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify_Using() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Class D
Inherits B
End Class
Class Program
Sub Main(args As String())
Using {|SimplifyParent:b As B|} = New D()
End Using
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
Class D
Inherits B
End Class
Class Program
Sub Main(args As String())
Using b As B = New D()
End Using
End Sub
End Class
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify_For_0() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
For {|SimplifyParent:index As Long|} = 1 To 5
Next
For Each {|SimplifyParent:index As Long|} In New Integer() {1, 2, 3}
Next
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Module Program
Sub Main(args As String())
For index As Long = 1 To 5
Next
For Each index As Long In New Integer() {1, 2, 3}
Next
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestDontSimplify_For_1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each {|SimplifyParent:index As B|} In args
Next
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each index As B In args
Next
End Sub
End Class
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(734377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734377")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports I = System.Int32
Module Program
Public Dim {|SimplifyParent:x As Integer = 5|}
Function Goo() As Integer
End Function
Sub Main(args As String())
Dim {|SimplifyParent:A As Integer = 5|}
Dim {|SimplifyParent:M() As String = New String(){}|}, {|SimplifyParent:N() As String|}
Dim {|SimplifyParent:B(,) As Integer = {{1,2},{2,3}}|}
Dim {|SimplifyParent:ret As Integer = Goo()|}
Const {|SimplifyParent:con As Integer = 1|}
Dim {|SimplifyParent:in As I = 1|}
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports I = System.Int32
Module Program
Public Dim x As Integer = 5
Function Goo() As Integer
End Function
Sub Main(args As String())
Dim A = 5
Dim M = New String(){}, N() As String
Dim B = {{1,2},{2,3}}
Dim ret = Goo()
Const con = 1
Dim in = 1
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify2() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports I = System.Int32
Module Program
Sub Main(args As String())
Using {|SimplifyParent:proc As Process|} = New Process
End Using
For {|SimplifyParent:index As Integer|} = 1 To 5
Next
For {|SimplifyParent:index As I|} = 1 to 5
Next
For Each {|SimplifyParent:index As Integer|} In New Integer() {1, 2, 3}
Next
End Sub
End Module
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports I = System.Int32
Module Program
Sub Main(args As String())
Using proc = New Process
End Using
For index = 1 To 5
Next
For index = 1 to 5
Next
For Each index In New Integer() {1, 2, 3}
Next
End Sub
End Module
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_For_1() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each {|SimplifyParent:index As Program|} In args
Next
End Sub
End Class
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class B
End Class
Class Program
Inherits B
Sub Main(args As String())
End Sub
Sub Madin(args As IEnumerable(Of Program))
For Each index In args
Next
End Sub
End Class
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_For_GenericMethods() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
void Goo<T>(T x);
}
class C : I
{
public void Goo<T>(T x) { }
}
class D : C
{
public void Goo(int x)
{
}
public void Sub()
{
{|SimplifyParent:base.Goo<int>(1)|};
}
}
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
interface I
{
void Goo<T>(T x);
}
class C : I
{
public void Goo<T>(T x) { }
}
class D : C
{
public void Goo(int x)
{
}
public void Sub()
{
base.Goo(1);
}
}]]>
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestSimplify_For_GenericMethods_VB() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Class C
Public Sub Goo(Of T)(ByRef x As T)
End Sub
End Class
Class D
Inherits C
Public Sub Goo(ByRef x As Integer)
End Sub
Public Sub Test()
Dim x As String
{|SimplifyParent:MyBase.Goo(Of String)(x)|}
End Sub
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
<text><![CDATA[
Class C
Public Sub Goo(Of T)(ByRef x As T)
End Sub
End Class
Class D
Inherits C
Public Sub Goo(ByRef x As Integer)
End Sub
Public Sub Test()
Dim x As String
MyBase.Goo(x)
End Sub
End Class
]]>
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(734377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/734377")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_ExplicitTypeDecl_FieldDecl() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace X
Module Program
Public Dim {|SimplifyParent:t as Integer = {|SimplifyParent:X.A|}.getInt()|}
Sub Main(args As String())
End Sub
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Namespace X
Module Program
Public Dim t as Integer = A.getInt()
Sub Main(args As String())
End Sub
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
<WorkItem(860111, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860111")>
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestVisualBasic_ExplicitTypeDecl_MustGetNewSMForAnyReducer() As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace Y
Namespace X
Module Program
Public Dim {|SimplifyParent:t as Integer = {|SimplifyParentParent:Y.X.A|}.getInt()|}
Sub Main(args As String())
End Function
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
End Namespace
</Document>
</Project>
</Workspace>
Dim expected =
<text>
Namespace Y
Namespace X
Module Program
Public Dim t as Integer = A.getInt()
Sub Main(args As String())
End Function
End Module
Class A
Public Shared Function getInt() As Integer
Return 0
End Function
End Class
End Namespace
End Namespace
</text>
Dim simplificationOptionSet = New Dictionary(Of OptionKey2, Object) From {}
Await TestAsync(input, expected, simplificationOptionSet)
End Function
#End Region
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Dependencies/Collections/ImmutableSegmentedDictionary`2.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Collections
{
/// <summary>
/// Represents a segmented dictionary that is immutable; meaning it cannot be changed once it is created.
/// </summary>
/// <remarks>
/// <para>There are different scenarios best for <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> and others
/// best for <see cref="ImmutableDictionary{TKey, TValue}"/>.</para>
///
/// <para>In general, <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> is applicable in scenarios most like
/// the scenarios where <see cref="ImmutableArray{T}"/> is applicable, and
/// <see cref="ImmutableDictionary{TKey, TValue}"/> is applicable in scenarios most like the scenarios where
/// <see cref="ImmutableList{T}"/> is applicable.</para>
///
/// <para>The following table summarizes the performance characteristics of
/// <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/>:</para>
///
/// <list type="table">
/// <item>
/// <description>Operation</description>
/// <description><see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> Complexity</description>
/// <description><see cref="ImmutableDictionary{TKey, TValue}"/> Complexity</description>
/// <description>Comments</description>
/// </item>
/// <item>
/// <description>Item</description>
/// <description>O(1)</description>
/// <description>O(log n)</description>
/// <description>Directly index into the underlying segmented dictionary</description>
/// </item>
/// <item>
/// <description>Add()</description>
/// <description>O(n)</description>
/// <description>O(log n)</description>
/// <description>Requires creating a new segmented dictionary</description>
/// </item>
/// </list>
///
/// <para>This type is backed by segmented arrays to avoid using the Large Object Heap without impacting algorithmic
/// complexity.</para>
/// </remarks>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
/// <devremarks>
/// <para>This type has a documented contract of being exactly one reference-type field in size. Our own
/// <see cref="RoslynImmutableInterlocked"/> class depends on it, as well as others externally.</para>
///
/// <para><strong>IMPORTANT NOTICE FOR MAINTAINERS AND REVIEWERS:</strong></para>
///
/// <para>This type should be thread-safe. As a struct, it cannot protect its own fields from being changed from one
/// thread while its members are executing on other threads because structs can change <em>in place</em> simply by
/// reassigning the field containing this struct. Therefore it is extremely important that <strong>⚠⚠ Every member
/// should only dereference <c>this</c> ONCE ⚠⚠</strong>. If a member needs to reference the
/// <see cref="_dictionary"/> field, that counts as a dereference of <c>this</c>. Calling other instance members
/// (properties or methods) also counts as dereferencing <c>this</c>. Any member that needs to use <c>this</c> more
/// than once must instead assign <c>this</c> to a local variable and use that for the rest of the code instead.
/// This effectively copies the one field in the struct to a local variable so that it is insulated from other
/// threads.</para>
/// </devremarks>
internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary, IEquatable<ImmutableSegmentedDictionary<TKey, TValue>>
where TKey : notnull
{
public static readonly ImmutableSegmentedDictionary<TKey, TValue> Empty = new(new SegmentedDictionary<TKey, TValue>());
private readonly SegmentedDictionary<TKey, TValue> _dictionary;
private ImmutableSegmentedDictionary(SegmentedDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
}
public IEqualityComparer<TKey> KeyComparer => _dictionary.Comparer;
public int Count => _dictionary.Count;
public bool IsEmpty => _dictionary.Count == 0;
public bool IsDefault => _dictionary == null;
public bool IsDefaultOrEmpty => _dictionary?.Count is null or 0;
public KeyCollection Keys => new(this);
public ValueCollection Values => new(this);
ICollection<TKey> IDictionary<TKey, TValue>.Keys => Keys;
ICollection<TValue> IDictionary<TKey, TValue>.Values => Values;
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys;
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values;
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => true;
ICollection IDictionary.Keys => Keys;
ICollection IDictionary.Values => Values;
bool IDictionary.IsReadOnly => true;
bool IDictionary.IsFixedSize => true;
object ICollection.SyncRoot => _dictionary;
bool ICollection.IsSynchronized => true;
public TValue this[TKey key] => _dictionary[key];
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get => this[key];
set => throw new NotSupportedException();
}
object? IDictionary.this[object key]
{
get => ((IDictionary)_dictionary)[key];
set => throw new NotSupportedException();
}
public static bool operator ==(ImmutableSegmentedDictionary<TKey, TValue> left, ImmutableSegmentedDictionary<TKey, TValue> right)
=> left.Equals(right);
public static bool operator !=(ImmutableSegmentedDictionary<TKey, TValue> left, ImmutableSegmentedDictionary<TKey, TValue> right)
=> !left.Equals(right);
public static bool operator ==(ImmutableSegmentedDictionary<TKey, TValue>? left, ImmutableSegmentedDictionary<TKey, TValue>? right)
=> left.GetValueOrDefault().Equals(right.GetValueOrDefault());
public static bool operator !=(ImmutableSegmentedDictionary<TKey, TValue>? left, ImmutableSegmentedDictionary<TKey, TValue>? right)
=> !left.GetValueOrDefault().Equals(right.GetValueOrDefault());
public ImmutableSegmentedDictionary<TKey, TValue> Add(TKey key, TValue value)
{
var self = this;
if (self.Contains(new KeyValuePair<TKey, TValue>(key, value)))
return self;
var dictionary = new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary.Add(key, value);
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
var self = this;
// Optimize the case of adding to an empty collection
if (self.IsEmpty && TryCastToImmutableSegmentedDictionary(pairs, out var other) && self.KeyComparer == other.KeyComparer)
{
return other;
}
SegmentedDictionary<TKey, TValue>? dictionary = null;
foreach (var pair in pairs)
{
ICollection<KeyValuePair<TKey, TValue>> collectionToCheck = dictionary ?? self._dictionary;
if (collectionToCheck.Contains(pair))
continue;
dictionary ??= new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary.Add(pair.Key, pair.Value);
}
if (dictionary is null)
return self;
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> Clear()
{
var self = this;
if (self.IsEmpty)
{
return self;
}
return Empty.WithComparer(self.KeyComparer);
}
public bool Contains(KeyValuePair<TKey, TValue> pair)
{
return TryGetValue(pair.Key, out var value)
&& EqualityComparer<TValue>.Default.Equals(value, pair.Value);
}
public bool ContainsKey(TKey key)
=> _dictionary.ContainsKey(key);
public bool ContainsValue(TValue value)
=> _dictionary.ContainsValue(value);
public Enumerator GetEnumerator()
=> new(_dictionary, Enumerator.ReturnType.KeyValuePair);
public ImmutableSegmentedDictionary<TKey, TValue> Remove(TKey key)
{
var self = this;
if (!self._dictionary.ContainsKey(key))
return self;
var dictionary = new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary.Remove(key);
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
if (keys is null)
throw new ArgumentNullException(nameof(keys));
var result = ToBuilder();
result.RemoveRange(keys);
return result.ToImmutable();
}
public ImmutableSegmentedDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
var self = this;
if (self.Contains(new KeyValuePair<TKey, TValue>(key, value)))
{
return self;
}
var dictionary = new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary[key] = value;
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
if (items is null)
throw new ArgumentNullException(nameof(items));
var result = ToBuilder();
foreach (var item in items)
{
result[item.Key] = item.Value;
}
return result.ToImmutable();
}
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
var self = this;
foreach (var key in self.Keys)
{
if (self.KeyComparer.Equals(key, equalKey))
{
actualKey = key;
return true;
}
}
actualKey = equalKey;
return false;
}
#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
=> _dictionary.TryGetValue(key, out value);
public ImmutableSegmentedDictionary<TKey, TValue> WithComparer(IEqualityComparer<TKey>? keyComparer)
{
keyComparer ??= EqualityComparer<TKey>.Default;
var self = this;
if (self.KeyComparer == keyComparer)
{
// Don't need to reconstruct the dictionary because the key comparer is the same
return self;
}
else if (self.IsEmpty)
{
if (keyComparer == Empty.KeyComparer)
{
return Empty;
}
else
{
return new ImmutableSegmentedDictionary<TKey, TValue>(new SegmentedDictionary<TKey, TValue>(keyComparer));
}
}
else
{
return ImmutableSegmentedDictionary.CreateRange(keyComparer, self);
}
}
public Builder ToBuilder()
=> new(this);
public override int GetHashCode()
=> _dictionary?.GetHashCode() ?? 0;
public override bool Equals(object? obj)
{
return obj is ImmutableSegmentedDictionary<TKey, TValue> other
&& Equals(other);
}
public bool Equals(ImmutableSegmentedDictionary<TKey, TValue> other)
=> _dictionary == other._dictionary;
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
=> Clear();
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> Add(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
=> AddRange(pairs);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
=> SetItem(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
=> SetItems(items);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
=> RemoveRange(keys);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) => Remove(key);
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair);
IDictionaryEnumerator IDictionary.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.DictionaryEntry);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair);
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
=> ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).CopyTo(array, arrayIndex);
bool IDictionary.Contains(object key)
=> ((IDictionary)_dictionary).Contains(key);
void ICollection.CopyTo(Array array, int index)
=> ((ICollection)_dictionary).CopyTo(array, index);
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> throw new NotSupportedException();
bool IDictionary<TKey, TValue>.Remove(TKey key)
=> throw new NotSupportedException();
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
=> throw new NotSupportedException();
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
void IDictionary.Add(object key, object? value)
=> throw new NotSupportedException();
void IDictionary.Clear()
=> throw new NotSupportedException();
void IDictionary.Remove(object key)
=> throw new NotSupportedException();
private static bool TryCastToImmutableSegmentedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> pairs, out ImmutableSegmentedDictionary<TKey, TValue> other)
{
if (pairs is ImmutableSegmentedDictionary<TKey, TValue> dictionary)
{
other = dictionary;
return true;
}
if (pairs is ImmutableSegmentedDictionary<TKey, TValue>.Builder builder)
{
other = builder.ToImmutable();
return true;
}
other = default;
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Collections
{
/// <summary>
/// Represents a segmented dictionary that is immutable; meaning it cannot be changed once it is created.
/// </summary>
/// <remarks>
/// <para>There are different scenarios best for <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> and others
/// best for <see cref="ImmutableDictionary{TKey, TValue}"/>.</para>
///
/// <para>In general, <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> is applicable in scenarios most like
/// the scenarios where <see cref="ImmutableArray{T}"/> is applicable, and
/// <see cref="ImmutableDictionary{TKey, TValue}"/> is applicable in scenarios most like the scenarios where
/// <see cref="ImmutableList{T}"/> is applicable.</para>
///
/// <para>The following table summarizes the performance characteristics of
/// <see cref="ImmutableSegmentedDictionary{TKey, TValue}"/>:</para>
///
/// <list type="table">
/// <item>
/// <description>Operation</description>
/// <description><see cref="ImmutableSegmentedDictionary{TKey, TValue}"/> Complexity</description>
/// <description><see cref="ImmutableDictionary{TKey, TValue}"/> Complexity</description>
/// <description>Comments</description>
/// </item>
/// <item>
/// <description>Item</description>
/// <description>O(1)</description>
/// <description>O(log n)</description>
/// <description>Directly index into the underlying segmented dictionary</description>
/// </item>
/// <item>
/// <description>Add()</description>
/// <description>O(n)</description>
/// <description>O(log n)</description>
/// <description>Requires creating a new segmented dictionary</description>
/// </item>
/// </list>
///
/// <para>This type is backed by segmented arrays to avoid using the Large Object Heap without impacting algorithmic
/// complexity.</para>
/// </remarks>
/// <typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the values in the dictionary.</typeparam>
/// <devremarks>
/// <para>This type has a documented contract of being exactly one reference-type field in size. Our own
/// <see cref="RoslynImmutableInterlocked"/> class depends on it, as well as others externally.</para>
///
/// <para><strong>IMPORTANT NOTICE FOR MAINTAINERS AND REVIEWERS:</strong></para>
///
/// <para>This type should be thread-safe. As a struct, it cannot protect its own fields from being changed from one
/// thread while its members are executing on other threads because structs can change <em>in place</em> simply by
/// reassigning the field containing this struct. Therefore it is extremely important that <strong>⚠⚠ Every member
/// should only dereference <c>this</c> ONCE ⚠⚠</strong>. If a member needs to reference the
/// <see cref="_dictionary"/> field, that counts as a dereference of <c>this</c>. Calling other instance members
/// (properties or methods) also counts as dereferencing <c>this</c>. Any member that needs to use <c>this</c> more
/// than once must instead assign <c>this</c> to a local variable and use that for the rest of the code instead.
/// This effectively copies the one field in the struct to a local variable so that it is insulated from other
/// threads.</para>
/// </devremarks>
internal readonly partial struct ImmutableSegmentedDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary, IEquatable<ImmutableSegmentedDictionary<TKey, TValue>>
where TKey : notnull
{
public static readonly ImmutableSegmentedDictionary<TKey, TValue> Empty = new(new SegmentedDictionary<TKey, TValue>());
private readonly SegmentedDictionary<TKey, TValue> _dictionary;
private ImmutableSegmentedDictionary(SegmentedDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
}
public IEqualityComparer<TKey> KeyComparer => _dictionary.Comparer;
public int Count => _dictionary.Count;
public bool IsEmpty => _dictionary.Count == 0;
public bool IsDefault => _dictionary == null;
public bool IsDefaultOrEmpty => _dictionary?.Count is null or 0;
public KeyCollection Keys => new(this);
public ValueCollection Values => new(this);
ICollection<TKey> IDictionary<TKey, TValue>.Keys => Keys;
ICollection<TValue> IDictionary<TKey, TValue>.Values => Values;
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys;
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values;
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => true;
ICollection IDictionary.Keys => Keys;
ICollection IDictionary.Values => Values;
bool IDictionary.IsReadOnly => true;
bool IDictionary.IsFixedSize => true;
object ICollection.SyncRoot => _dictionary;
bool ICollection.IsSynchronized => true;
public TValue this[TKey key] => _dictionary[key];
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get => this[key];
set => throw new NotSupportedException();
}
object? IDictionary.this[object key]
{
get => ((IDictionary)_dictionary)[key];
set => throw new NotSupportedException();
}
public static bool operator ==(ImmutableSegmentedDictionary<TKey, TValue> left, ImmutableSegmentedDictionary<TKey, TValue> right)
=> left.Equals(right);
public static bool operator !=(ImmutableSegmentedDictionary<TKey, TValue> left, ImmutableSegmentedDictionary<TKey, TValue> right)
=> !left.Equals(right);
public static bool operator ==(ImmutableSegmentedDictionary<TKey, TValue>? left, ImmutableSegmentedDictionary<TKey, TValue>? right)
=> left.GetValueOrDefault().Equals(right.GetValueOrDefault());
public static bool operator !=(ImmutableSegmentedDictionary<TKey, TValue>? left, ImmutableSegmentedDictionary<TKey, TValue>? right)
=> !left.GetValueOrDefault().Equals(right.GetValueOrDefault());
public ImmutableSegmentedDictionary<TKey, TValue> Add(TKey key, TValue value)
{
var self = this;
if (self.Contains(new KeyValuePair<TKey, TValue>(key, value)))
return self;
var dictionary = new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary.Add(key, value);
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
var self = this;
// Optimize the case of adding to an empty collection
if (self.IsEmpty && TryCastToImmutableSegmentedDictionary(pairs, out var other) && self.KeyComparer == other.KeyComparer)
{
return other;
}
SegmentedDictionary<TKey, TValue>? dictionary = null;
foreach (var pair in pairs)
{
ICollection<KeyValuePair<TKey, TValue>> collectionToCheck = dictionary ?? self._dictionary;
if (collectionToCheck.Contains(pair))
continue;
dictionary ??= new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary.Add(pair.Key, pair.Value);
}
if (dictionary is null)
return self;
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> Clear()
{
var self = this;
if (self.IsEmpty)
{
return self;
}
return Empty.WithComparer(self.KeyComparer);
}
public bool Contains(KeyValuePair<TKey, TValue> pair)
{
return TryGetValue(pair.Key, out var value)
&& EqualityComparer<TValue>.Default.Equals(value, pair.Value);
}
public bool ContainsKey(TKey key)
=> _dictionary.ContainsKey(key);
public bool ContainsValue(TValue value)
=> _dictionary.ContainsValue(value);
public Enumerator GetEnumerator()
=> new(_dictionary, Enumerator.ReturnType.KeyValuePair);
public ImmutableSegmentedDictionary<TKey, TValue> Remove(TKey key)
{
var self = this;
if (!self._dictionary.ContainsKey(key))
return self;
var dictionary = new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary.Remove(key);
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
if (keys is null)
throw new ArgumentNullException(nameof(keys));
var result = ToBuilder();
result.RemoveRange(keys);
return result.ToImmutable();
}
public ImmutableSegmentedDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
var self = this;
if (self.Contains(new KeyValuePair<TKey, TValue>(key, value)))
{
return self;
}
var dictionary = new SegmentedDictionary<TKey, TValue>(self._dictionary, self._dictionary.Comparer);
dictionary[key] = value;
return new ImmutableSegmentedDictionary<TKey, TValue>(dictionary);
}
public ImmutableSegmentedDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
if (items is null)
throw new ArgumentNullException(nameof(items));
var result = ToBuilder();
foreach (var item in items)
{
result[item.Key] = item.Value;
}
return result.ToImmutable();
}
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
var self = this;
foreach (var key in self.Keys)
{
if (self.KeyComparer.Equals(key, equalKey))
{
actualKey = key;
return true;
}
}
actualKey = equalKey;
return false;
}
#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
=> _dictionary.TryGetValue(key, out value);
public ImmutableSegmentedDictionary<TKey, TValue> WithComparer(IEqualityComparer<TKey>? keyComparer)
{
keyComparer ??= EqualityComparer<TKey>.Default;
var self = this;
if (self.KeyComparer == keyComparer)
{
// Don't need to reconstruct the dictionary because the key comparer is the same
return self;
}
else if (self.IsEmpty)
{
if (keyComparer == Empty.KeyComparer)
{
return Empty;
}
else
{
return new ImmutableSegmentedDictionary<TKey, TValue>(new SegmentedDictionary<TKey, TValue>(keyComparer));
}
}
else
{
return ImmutableSegmentedDictionary.CreateRange(keyComparer, self);
}
}
public Builder ToBuilder()
=> new(this);
public override int GetHashCode()
=> _dictionary?.GetHashCode() ?? 0;
public override bool Equals(object? obj)
{
return obj is ImmutableSegmentedDictionary<TKey, TValue> other
&& Equals(other);
}
public bool Equals(ImmutableSegmentedDictionary<TKey, TValue> other)
=> _dictionary == other._dictionary;
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear()
=> Clear();
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> Add(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
=> AddRange(pairs);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
=> SetItem(key, value);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
=> SetItems(items);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
=> RemoveRange(keys);
IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) => Remove(key);
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair);
IDictionaryEnumerator IDictionary.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.DictionaryEntry);
IEnumerator IEnumerable.GetEnumerator()
=> new Enumerator(_dictionary, Enumerator.ReturnType.KeyValuePair);
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
=> ((ICollection<KeyValuePair<TKey, TValue>>)_dictionary).CopyTo(array, arrayIndex);
bool IDictionary.Contains(object key)
=> ((IDictionary)_dictionary).Contains(key);
void ICollection.CopyTo(Array array, int index)
=> ((ICollection)_dictionary).CopyTo(array, index);
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
=> throw new NotSupportedException();
bool IDictionary<TKey, TValue>.Remove(TKey key)
=> throw new NotSupportedException();
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
=> throw new NotSupportedException();
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
void IDictionary.Add(object key, object? value)
=> throw new NotSupportedException();
void IDictionary.Clear()
=> throw new NotSupportedException();
void IDictionary.Remove(object key)
=> throw new NotSupportedException();
private static bool TryCastToImmutableSegmentedDictionary(IEnumerable<KeyValuePair<TKey, TValue>> pairs, out ImmutableSegmentedDictionary<TKey, TValue> other)
{
if (pairs is ImmutableSegmentedDictionary<TKey, TValue> dictionary)
{
other = dictionary;
return true;
}
if (pairs is ImmutableSegmentedDictionary<TKey, TValue>.Builder builder)
{
other = builder.ToImmutable();
return true;
}
other = default;
return false;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/BinaryOperatorAnalysisResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
[SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")]
internal struct BinaryOperatorAnalysisResult
{
public readonly Conversion LeftConversion;
public readonly Conversion RightConversion;
public readonly BinaryOperatorSignature Signature;
public readonly OperatorAnalysisResultKind Kind;
private BinaryOperatorAnalysisResult(OperatorAnalysisResultKind kind, BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
{
this.Kind = kind;
this.Signature = signature;
this.LeftConversion = leftConversion;
this.RightConversion = rightConversion;
}
public bool IsValid
{
get { return this.Kind == OperatorAnalysisResultKind.Applicable; }
}
public bool HasValue
{
get { return this.Kind != OperatorAnalysisResultKind.Undefined; }
}
public override bool Equals(object obj)
{
// implement if needed
throw ExceptionUtilities.Unreachable;
}
public override int GetHashCode()
{
// implement if needed
throw ExceptionUtilities.Unreachable;
}
public static BinaryOperatorAnalysisResult Applicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
{
return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Applicable, signature, leftConversion, rightConversion);
}
public static BinaryOperatorAnalysisResult Inapplicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
{
return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Inapplicable, signature, leftConversion, rightConversion);
}
public BinaryOperatorAnalysisResult Worse()
{
return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Worse, this.Signature, this.LeftConversion, this.RightConversion);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
[SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")]
internal struct BinaryOperatorAnalysisResult
{
public readonly Conversion LeftConversion;
public readonly Conversion RightConversion;
public readonly BinaryOperatorSignature Signature;
public readonly OperatorAnalysisResultKind Kind;
private BinaryOperatorAnalysisResult(OperatorAnalysisResultKind kind, BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
{
this.Kind = kind;
this.Signature = signature;
this.LeftConversion = leftConversion;
this.RightConversion = rightConversion;
}
public bool IsValid
{
get { return this.Kind == OperatorAnalysisResultKind.Applicable; }
}
public bool HasValue
{
get { return this.Kind != OperatorAnalysisResultKind.Undefined; }
}
public override bool Equals(object obj)
{
// implement if needed
throw ExceptionUtilities.Unreachable;
}
public override int GetHashCode()
{
// implement if needed
throw ExceptionUtilities.Unreachable;
}
public static BinaryOperatorAnalysisResult Applicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
{
return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Applicable, signature, leftConversion, rightConversion);
}
public static BinaryOperatorAnalysisResult Inapplicable(BinaryOperatorSignature signature, Conversion leftConversion, Conversion rightConversion)
{
return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Inapplicable, signature, leftConversion, rightConversion);
}
public BinaryOperatorAnalysisResult Worse()
{
return new BinaryOperatorAnalysisResult(OperatorAnalysisResultKind.Worse, this.Signature, this.LeftConversion, this.RightConversion);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DynamicDelegatesAndIndexers.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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateWithDynamicArgument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class A
{
delegate void myDelegate(dynamic d);
void Goo()
{
dynamic d = 1;
myDelegate {|Definition:del|} = n => { Console.WriteLine(n); };
[|$$del|](d);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestIndexerWithStaticParameter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class A
{
public int {|Definition:$$this|}[int i] { get { } }
public int this[dynamic i] { get { } }
}
class B
{
public void Goo()
{
A a = new A();
dynamic d = 1;
var a1 = a[||][1];
var a2 = a["hello"];
var a3 = a[||][d];
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestIndexerWithDynamicParameter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class A
{
public int this[int i] { get { } }
public int {|Definition:$$this|}[dynamic i] { get { } }
}
class B
{
public void Goo()
{
A a = new A();
dynamic d = 1;
var a1 = a[1];
var a2 = a[||]["hello"];
var a3 = a[||][d];
}
} </Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
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.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestDelegateWithDynamicArgument(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class A
{
delegate void myDelegate(dynamic d);
void Goo()
{
dynamic d = 1;
myDelegate {|Definition:del|} = n => { Console.WriteLine(n); };
[|$$del|](d);
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestIndexerWithStaticParameter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class A
{
public int {|Definition:$$this|}[int i] { get { } }
public int this[dynamic i] { get { } }
}
class B
{
public void Goo()
{
A a = new A();
dynamic d = 1;
var a1 = a[||][1];
var a2 = a["hello"];
var a3 = a[||][d];
}
}
</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestIndexerWithDynamicParameter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class A
{
public int this[int i] { get { } }
public int {|Definition:$$this|}[dynamic i] { get { } }
}
class B
{
public void Goo()
{
A a = new A();
dynamic d = 1;
var a1 = a[1];
var a2 = a[||]["hello"];
var a3 = a[||][d];
}
} </Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Tools/ExternalAccess/Apex/ApexAsynchronousOperationListenerProviderAccessor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices;
namespace Microsoft.CodeAnalysis.ExternalAccess.Apex
{
[Export(typeof(IApexAsynchronousOperationListenerProviderAccessor))]
[Shared]
internal sealed class ApexAsynchronousOperationListenerProviderAccessor : IApexAsynchronousOperationListenerProviderAccessor
{
private readonly AsynchronousOperationListenerProvider _implementation;
private readonly Workspace? _workspace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ApexAsynchronousOperationListenerProviderAccessor(
AsynchronousOperationListenerProvider implementation,
[Import(AllowDefault = true)] VisualStudioWorkspace? workspace)
{
_implementation = implementation;
_workspace = workspace;
}
public Task WaitAllAsync(string[]? featureNames = null, Action? eventProcessingAction = null, TimeSpan? timeout = null)
=> _implementation.WaitAllAsync(_workspace, featureNames, eventProcessingAction, timeout);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.LanguageServices;
namespace Microsoft.CodeAnalysis.ExternalAccess.Apex
{
[Export(typeof(IApexAsynchronousOperationListenerProviderAccessor))]
[Shared]
internal sealed class ApexAsynchronousOperationListenerProviderAccessor : IApexAsynchronousOperationListenerProviderAccessor
{
private readonly AsynchronousOperationListenerProvider _implementation;
private readonly Workspace? _workspace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ApexAsynchronousOperationListenerProviderAccessor(
AsynchronousOperationListenerProvider implementation,
[Import(AllowDefault = true)] VisualStudioWorkspace? workspace)
{
_implementation = implementation;
_workspace = workspace;
}
public Task WaitAllAsync(string[]? featureNames = null, Action? eventProcessingAction = null, TimeSpan? timeout = null)
=> _implementation.WaitAllAsync(_workspace, featureNames, eventProcessingAction, timeout);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.MoveToNamespace
{
internal class MoveToNamespaceResult
{
public static readonly MoveToNamespaceResult Failed = new();
public bool Succeeded { get; }
public Solution UpdatedSolution { get; }
public Solution OriginalSolution { get; }
public DocumentId UpdatedDocumentId { get; }
public ImmutableDictionary<string, ISymbol> NewNameOriginalSymbolMapping { get; }
public string NewName { get; }
public MoveToNamespaceResult(
Solution originalSolution,
Solution updatedSolution,
DocumentId updatedDocumentId,
ImmutableDictionary<string, ISymbol> newNameOriginalSymbolMapping)
{
OriginalSolution = originalSolution;
UpdatedSolution = updatedSolution;
UpdatedDocumentId = updatedDocumentId;
NewNameOriginalSymbolMapping = newNameOriginalSymbolMapping;
Succeeded = true;
}
private MoveToNamespaceResult()
=> Succeeded = false;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.MoveToNamespace
{
internal class MoveToNamespaceResult
{
public static readonly MoveToNamespaceResult Failed = new();
public bool Succeeded { get; }
public Solution UpdatedSolution { get; }
public Solution OriginalSolution { get; }
public DocumentId UpdatedDocumentId { get; }
public ImmutableDictionary<string, ISymbol> NewNameOriginalSymbolMapping { get; }
public string NewName { get; }
public MoveToNamespaceResult(
Solution originalSolution,
Solution updatedSolution,
DocumentId updatedDocumentId,
ImmutableDictionary<string, ISymbol> newNameOriginalSymbolMapping)
{
OriginalSolution = originalSolution;
UpdatedSolution = updatedSolution;
UpdatedDocumentId = updatedDocumentId;
NewNameOriginalSymbolMapping = newNameOriginalSymbolMapping;
Succeeded = true;
}
private MoveToNamespaceResult()
=> Succeeded = false;
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeActions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Inherit this type to provide source code refactorings.
/// Remember to use <see cref="ExportCodeRefactoringProviderAttribute"/> so the host environment can offer your refactorings in a UI.
/// </summary>
public abstract class CodeRefactoringProvider
{
/// <summary>
/// Computes one or more refactorings for the specified <see cref="CodeRefactoringContext"/>.
/// </summary>
public abstract Task ComputeRefactoringsAsync(CodeRefactoringContext context);
/// <summary>
/// What priority this provider should run at.
/// </summary>
internal CodeActionRequestPriority RequestPriority
{
get
{
var priority = ComputeRequestPriority();
Contract.ThrowIfFalse(priority is CodeActionRequestPriority.Normal or CodeActionRequestPriority.High);
return priority;
}
}
private protected virtual CodeActionRequestPriority ComputeRequestPriority()
=> CodeActionRequestPriority.Normal;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeActions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
/// <summary>
/// Inherit this type to provide source code refactorings.
/// Remember to use <see cref="ExportCodeRefactoringProviderAttribute"/> so the host environment can offer your refactorings in a UI.
/// </summary>
public abstract class CodeRefactoringProvider
{
/// <summary>
/// Computes one or more refactorings for the specified <see cref="CodeRefactoringContext"/>.
/// </summary>
public abstract Task ComputeRefactoringsAsync(CodeRefactoringContext context);
/// <summary>
/// What priority this provider should run at.
/// </summary>
internal CodeActionRequestPriority RequestPriority
{
get
{
var priority = ComputeRequestPriority();
Contract.ThrowIfFalse(priority is CodeActionRequestPriority.Normal or CodeActionRequestPriority.High);
return priority;
}
}
private protected virtual CodeActionRequestPriority ComputeRequestPriority()
=> CodeActionRequestPriority.Normal;
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/Workspace/Solution/AdditionalTextWithState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// An implementation of <see cref="AdditionalText"/> for the compiler that wraps a <see cref="AdditionalDocumentState"/>.
/// </summary>
internal sealed class AdditionalTextWithState : AdditionalText
{
private readonly AdditionalDocumentState _documentState;
/// <summary>
/// Create a <see cref="SourceText"/> from a <see cref="AdditionalDocumentState"/>.
/// </summary>
public AdditionalTextWithState(AdditionalDocumentState documentState)
=> _documentState = documentState ?? throw new ArgumentNullException(nameof(documentState));
/// <summary>
/// Resolved path of the document.
/// </summary>
public override string Path => _documentState.FilePath ?? _documentState.Name;
/// <summary>
/// Retrieves a <see cref="SourceText"/> with the contents of this file.
/// </summary>
public override SourceText GetText(CancellationToken cancellationToken = default)
{
var text = _documentState.GetTextSynchronously(cancellationToken);
return text;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// An implementation of <see cref="AdditionalText"/> for the compiler that wraps a <see cref="AdditionalDocumentState"/>.
/// </summary>
internal sealed class AdditionalTextWithState : AdditionalText
{
private readonly AdditionalDocumentState _documentState;
/// <summary>
/// Create a <see cref="SourceText"/> from a <see cref="AdditionalDocumentState"/>.
/// </summary>
public AdditionalTextWithState(AdditionalDocumentState documentState)
=> _documentState = documentState ?? throw new ArgumentNullException(nameof(documentState));
/// <summary>
/// Resolved path of the document.
/// </summary>
public override string Path => _documentState.FilePath ?? _documentState.Name;
/// <summary>
/// Retrieves a <see cref="SourceText"/> with the contents of this file.
/// </summary>
public override SourceText GetText(CancellationToken cancellationToken = default)
{
var text = _documentState.GetTextSynchronously(cancellationToken);
return text;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncAnonymousFunctionHighlighterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class AsyncAnonymousFunctionHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(AsyncAwaitHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestSimpleLambda()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<int, Task<int>> lambda = {|Cursor:[|async|]|} _ =>
{
return [|await|] AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda(0);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestParenthesizedLambda()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = {|Cursor:[|async|]|} () =>
{
return [|await|] AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestAnonymousMethod()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = {|Cursor:[|async|]|} delegate
{
return [|await|] AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class AsyncAnonymousFunctionHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(AsyncAwaitHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestSimpleLambda()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<int, Task<int>> lambda = {|Cursor:[|async|]|} _ =>
{
return [|await|] AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda(0);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestParenthesizedLambda()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = {|Cursor:[|async|]|} () =>
{
return [|await|] AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestAnonymousMethod()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = {|Cursor:[|async|]|} delegate
{
return [|await|] AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Test2/GoToImplementation/GoToImplementationTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.Editor.FindUsages
Imports System.Threading
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToImplementation
<[UseExportProvider]>
Public Class GoToImplementationTests
Private Shared Async Function TestAsync(workspaceDefinition As XElement, host As TestHost, Optional shouldSucceed As Boolean = True) As Task
Await GoToHelpers.TestAsync(
workspaceDefinition,
host,
Async Function(document As Document, position As Integer, context As SimpleFindUsagesContext) As Task
Dim findUsagesService = document.GetLanguageService(Of IFindUsagesService)
Await findUsagesService.FindImplementationsAsync(document, position, context, CancellationToken.None).ConfigureAwait(False)
End Function,
shouldSucceed)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestEmptyFile(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
$$
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host, shouldSucceed:=False)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSingleClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$C|] { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithAbstractClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
abstract class [|$$C|]
{
}
class [|D|] : C
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithAbstractClassFromInterface(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface $$I { }
abstract class [|C|] : I { }
class [|D|] : C { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSealedClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
sealed class [|$$C|]
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithStruct(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
struct [|$$C|]
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithEnum(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
enum [|$$C|]
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithNonAbstractClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$C|]
{
}
class [|D|] : C
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSingleClassImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|C|] : I { }
interface $$I { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithTwoClassImplementations(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|C|] : I { }
class [|D|] : I { }
interface $$I { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_01(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_02(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public void [|M|]() { } }
interface I { void [|$$M|]() {} }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_03(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { void I.[|M|]() { } }
interface I { void [|$$M|]() {} }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_04(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface C : I
{
void I.[|M|]() { }
void M();
}
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_05(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface C : I
{
void I.[|M|]() { }
void M();
}
interface I { void [|$$M|]() {} }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneEventImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C : I { public event EventHandler [|E|]; }
interface I { event EventHandler $$E; }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithTwoMethodImplementations(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public void [|M|]() { } }
class D : I { public void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithNonInheritedImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C { public void [|M|]() { } }
class D : C, I { }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnBaseClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public virtual void [|M|]() { } }
class D : C { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnDerivedClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C { public virtual void M() { } }
class D : C, I { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithVirtualMethodImplementationAndInterfaceImplementedOnDerivedType(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public virtual void [|M|]() { } }
class D : C, I { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithAbstractMethodImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public abstract void M() { } }
class D : C { public override void [|M|]() { } }}
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithInterfaceMemberFromMetdataAtUseSite(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C : IDisposable
{
public void [|Dispose|]()
{
IDisposable d;
d.$$Dispose();
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSimpleMethod(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public void [|$$M|]() { }
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOverridableMethodOnBase(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void [|$$M|]() { }
}
class D : C
{
public override void [|M|]() { }
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOverridableMethodOnImplementation(host As TestHost) As Task
' Our philosophy is to only show derived in this case, since we know the implementation of
' D could never call C.M here
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void M() { }
}
class D : C
{
public override void [|$$M|]() { }
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(19700, "https://github.com/dotnet/roslyn/issues/19700")>
Public Async Function TestWithIntermediateAbstractOverrides(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
abstract class A {
public virtual void $$[|M|]() { }
}
abstract class B : A {
public abstract override void M();
}
sealed class C1 : B {
public override void [|M|]() { }
}
sealed class C2 : A {
public override void [|M|]() => base.M();
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(43093, "https://github.com/dotnet/roslyn/issues/43093")>
Public Async Function TestMultiTargetting1(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<Document FilePath="C.cs">
public interface $$IInterface
{
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document IsLinkFile="true" LinkProjectName="BaseProjectCore" LinkFilePath="C.cs">
public interface IInterface
{
}
</Document>
</Project>
<Project Name="ImplProject" Language="C#" CommonReferences="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document>
public class [|Impl|] : IInterface
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(46818, "https://github.com/dotnet/roslyn/issues/46818")>
Public Async Function TestCrossTargetting1(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document FilePath="C.cs">
using System;
using System.Threading.Tasks;
namespace MultiTargettingCore
{
public class Class1
{
static async Task Main(string[] args)
{
IStringCreator strCreator = new StringCreator();
var result = await strCreator.$$CreateStringAsync();
}
}
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document>
using System.Threading.Tasks;
public interface IStringCreator
{
Task<string> CreateStringAsync();
}
public class StringCreator : IStringCreator
{
public async Task<string> [|CreateStringAsync|]()
{
return "Another hello world - async!";
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(46818, "https://github.com/dotnet/roslyn/issues/46818")>
Public Async Function TestCrossTargetting2(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document FilePath="C.cs">
using System;
using System.Threading.Tasks;
namespace MultiTargettingCore
{
public class Class1
{
static async Task Main(string[] args)
{
IStringCreator strCreator = new StringCreator();
var result = await strCreator.$$CreateTupleAsync();
}
}
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document>
using System.Threading.Tasks;
public interface IStringCreator
{
Task<(string s, string t)> CreateTupleAsync();
}
public class StringCreator : IStringCreator
{
public async Task<(string x, string y)> [|CreateTupleAsync|]()
{
return default;
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(46818, "https://github.com/dotnet/roslyn/issues/46818")>
Public Async Function TestCrossTargetting3(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document FilePath="C.cs">
using System;
using System.Threading.Tasks;
namespace MultiTargettingCore
{
public class Class1
{
static async Task Main(string[] args)
{
IStringCreator strCreator = new StringCreator();
var result = await strCreator.$$CreateNintAsync();
}
}
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document>
using System.Threading.Tasks;
public interface IStringCreator
{
Task<nint> CreateNintAsync();
}
public class StringCreator : IStringCreator
{
public async Task<nint> [|CreateNintAsync|]()
{
return default;
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(26167, "https://github.com/dotnet/roslyn/issues/26167")>
Public Async Function SkipIntermediaryAbstractMethodIfOverridden(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public abstract void M(); }
class D : C { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(26167, "https://github.com/dotnet/roslyn/issues/26167")>
Public Async Function IncludeAbstractMethodIfNotOverridden(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public abstract void [|M|](); }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.Editor.FindUsages
Imports System.Threading
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToImplementation
<[UseExportProvider]>
Public Class GoToImplementationTests
Private Shared Async Function TestAsync(workspaceDefinition As XElement, host As TestHost, Optional shouldSucceed As Boolean = True) As Task
Await GoToHelpers.TestAsync(
workspaceDefinition,
host,
Async Function(document As Document, position As Integer, context As SimpleFindUsagesContext) As Task
Dim findUsagesService = document.GetLanguageService(Of IFindUsagesService)
Await findUsagesService.FindImplementationsAsync(document, position, context, CancellationToken.None).ConfigureAwait(False)
End Function,
shouldSucceed)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestEmptyFile(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
$$
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host, shouldSucceed:=False)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSingleClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$C|] { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithAbstractClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
abstract class [|$$C|]
{
}
class [|D|] : C
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithAbstractClassFromInterface(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface $$I { }
abstract class [|C|] : I { }
class [|D|] : C { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSealedClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
sealed class [|$$C|]
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithStruct(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
struct [|$$C|]
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithEnum(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
enum [|$$C|]
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithNonAbstractClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|$$C|]
{
}
class [|D|] : C
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSingleClassImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|C|] : I { }
interface $$I { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithTwoClassImplementations(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class [|C|] : I { }
class [|D|] : I { }
interface $$I { }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_01(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_02(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public void [|M|]() { } }
interface I { void [|$$M|]() {} }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_03(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { void I.[|M|]() { } }
interface I { void [|$$M|]() {} }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_04(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface C : I
{
void I.[|M|]() { }
void M();
}
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneMethodImplementation_05(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
interface C : I
{
void I.[|M|]() { }
void M();
}
interface I { void [|$$M|]() {} }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOneEventImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C : I { public event EventHandler [|E|]; }
interface I { event EventHandler $$E; }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithTwoMethodImplementations(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public void [|M|]() { } }
class D : I { public void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithNonInheritedImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C { public void [|M|]() { } }
class D : C, I { }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnBaseClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public virtual void [|M|]() { } }
class D : C { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithVirtualMethodImplementationWithInterfaceOnDerivedClass(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C { public virtual void M() { } }
class D : C, I { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithVirtualMethodImplementationAndInterfaceImplementedOnDerivedType(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public virtual void [|M|]() { } }
class D : C, I { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(6752, "https://github.com/dotnet/roslyn/issues/6752")>
Public Async Function TestWithAbstractMethodImplementation(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public abstract void M() { } }
class D : C { public override void [|M|]() { } }}
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithInterfaceMemberFromMetdataAtUseSite(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C : IDisposable
{
public void [|Dispose|]()
{
IDisposable d;
d.$$Dispose();
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithSimpleMethod(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public void [|$$M|]() { }
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOverridableMethodOnBase(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void [|$$M|]() { }
}
class D : C
{
public override void [|M|]() { }
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
Public Async Function TestWithOverridableMethodOnImplementation(host As TestHost) As Task
' Our philosophy is to only show derived in this case, since we know the implementation of
' D could never call C.M here
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public virtual void M() { }
}
class D : C
{
public override void [|$$M|]() { }
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(19700, "https://github.com/dotnet/roslyn/issues/19700")>
Public Async Function TestWithIntermediateAbstractOverrides(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
abstract class A {
public virtual void $$[|M|]() { }
}
abstract class B : A {
public abstract override void M();
}
sealed class C1 : B {
public override void [|M|]() { }
}
sealed class C2 : A {
public override void [|M|]() => base.M();
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(43093, "https://github.com/dotnet/roslyn/issues/43093")>
Public Async Function TestMultiTargetting1(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<Document FilePath="C.cs">
public interface $$IInterface
{
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document IsLinkFile="true" LinkProjectName="BaseProjectCore" LinkFilePath="C.cs">
public interface IInterface
{
}
</Document>
</Project>
<Project Name="ImplProject" Language="C#" CommonReferences="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document>
public class [|Impl|] : IInterface
{
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(46818, "https://github.com/dotnet/roslyn/issues/46818")>
Public Async Function TestCrossTargetting1(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document FilePath="C.cs">
using System;
using System.Threading.Tasks;
namespace MultiTargettingCore
{
public class Class1
{
static async Task Main(string[] args)
{
IStringCreator strCreator = new StringCreator();
var result = await strCreator.$$CreateStringAsync();
}
}
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document>
using System.Threading.Tasks;
public interface IStringCreator
{
Task<string> CreateStringAsync();
}
public class StringCreator : IStringCreator
{
public async Task<string> [|CreateStringAsync|]()
{
return "Another hello world - async!";
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(46818, "https://github.com/dotnet/roslyn/issues/46818")>
Public Async Function TestCrossTargetting2(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document FilePath="C.cs">
using System;
using System.Threading.Tasks;
namespace MultiTargettingCore
{
public class Class1
{
static async Task Main(string[] args)
{
IStringCreator strCreator = new StringCreator();
var result = await strCreator.$$CreateTupleAsync();
}
}
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document>
using System.Threading.Tasks;
public interface IStringCreator
{
Task<(string s, string t)> CreateTupleAsync();
}
public class StringCreator : IStringCreator
{
public async Task<(string x, string y)> [|CreateTupleAsync|]()
{
return default;
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(46818, "https://github.com/dotnet/roslyn/issues/46818")>
Public Async Function TestCrossTargetting3(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Name="BaseProjectCore" Language="C#" CommonReferencesNetCoreApp="true">
<ProjectReference>BaseProjectStandard</ProjectReference>
<Document FilePath="C.cs">
using System;
using System.Threading.Tasks;
namespace MultiTargettingCore
{
public class Class1
{
static async Task Main(string[] args)
{
IStringCreator strCreator = new StringCreator();
var result = await strCreator.$$CreateNintAsync();
}
}
}
</Document>
</Project>
<Project Name="BaseProjectStandard" Language="C#" CommonReferencesNetStandard20="true">
<Document>
using System.Threading.Tasks;
public interface IStringCreator
{
Task<nint> CreateNintAsync();
}
public class StringCreator : IStringCreator
{
public async Task<nint> [|CreateNintAsync|]()
{
return default;
}
}
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(26167, "https://github.com/dotnet/roslyn/issues/26167")>
Public Async Function SkipIntermediaryAbstractMethodIfOverridden(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public abstract void M(); }
class D : C { public override void [|M|]() { } }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.GoToImplementation)>
<WorkItem(26167, "https://github.com/dotnet/roslyn/issues/26167")>
Public Async Function IncludeAbstractMethodIfNotOverridden(host As TestHost) As Task
Dim workspace =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C : I { public abstract void [|M|](); }
interface I { void $$M(); }
</Document>
</Project>
</Workspace>
Await TestAsync(workspace, host)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Portable/Symbols/Wrapped/WrappedFieldSymbol.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.Globalization
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a field that is based on another field.
''' When inheriting from this class, one shouldn't assume that
''' the default behavior it has is appropriate for every case.
''' That behavior should be carefully reviewed and derived type
''' should override behavior as appropriate.
''' </summary>
Friend MustInherit Class WrappedFieldSymbol
Inherits FieldSymbol
Protected _underlyingField As FieldSymbol
Public ReadOnly Property UnderlyingField As FieldSymbol
Get
Return Me._underlyingField
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return Me._underlyingField.IsImplicitlyDeclared
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Me._underlyingField.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Me._underlyingField.Name
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return Me._underlyingField.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return Me._underlyingField.HasRuntimeSpecialName
End Get
End Property
Friend Overrides ReadOnly Property IsNotSerialized As Boolean
Get
Return Me._underlyingField.IsNotSerialized
End Get
End Property
Friend Overrides ReadOnly Property IsMarshalledExplicitly As Boolean
Get
Return Me._underlyingField.IsMarshalledExplicitly
End Get
End Property
Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return Me._underlyingField.MarshallingInformation
End Get
End Property
Friend Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte)
Get
Return Me._underlyingField.MarshallingDescriptor
End Get
End Property
Friend Overrides ReadOnly Property TypeLayoutOffset As Integer?
Get
Return Me._underlyingField.TypeLayoutOffset
End Get
End Property
Public Overrides ReadOnly Property IsReadOnly As Boolean
Get
Return Me._underlyingField.IsReadOnly
End Get
End Property
Public Overrides ReadOnly Property IsConst As Boolean
Get
Return Me._underlyingField.IsConst
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Me._underlyingField.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property ConstantValue As Object
Get
Return Me._underlyingField.ConstantValue
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return Me._underlyingField.Locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return Me._underlyingField.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return Me._underlyingField.IsShared
End Get
End Property
Public Sub New(underlyingField As FieldSymbol)
Debug.Assert(underlyingField IsNot Nothing)
Me._underlyingField = underlyingField
End Sub
Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
Return Me._underlyingField.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken)
End Function
Friend Overrides Function GetConstantValue(inProgress As ConstantFieldsInProgress) As ConstantValue
Return Me._underlyingField.GetConstantValue(inProgress)
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.Globalization
Imports System.Threading
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a field that is based on another field.
''' When inheriting from this class, one shouldn't assume that
''' the default behavior it has is appropriate for every case.
''' That behavior should be carefully reviewed and derived type
''' should override behavior as appropriate.
''' </summary>
Friend MustInherit Class WrappedFieldSymbol
Inherits FieldSymbol
Protected _underlyingField As FieldSymbol
Public ReadOnly Property UnderlyingField As FieldSymbol
Get
Return Me._underlyingField
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return Me._underlyingField.IsImplicitlyDeclared
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Me._underlyingField.DeclaredAccessibility
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Me._underlyingField.Name
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return Me._underlyingField.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return Me._underlyingField.HasRuntimeSpecialName
End Get
End Property
Friend Overrides ReadOnly Property IsNotSerialized As Boolean
Get
Return Me._underlyingField.IsNotSerialized
End Get
End Property
Friend Overrides ReadOnly Property IsMarshalledExplicitly As Boolean
Get
Return Me._underlyingField.IsMarshalledExplicitly
End Get
End Property
Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return Me._underlyingField.MarshallingInformation
End Get
End Property
Friend Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte)
Get
Return Me._underlyingField.MarshallingDescriptor
End Get
End Property
Friend Overrides ReadOnly Property TypeLayoutOffset As Integer?
Get
Return Me._underlyingField.TypeLayoutOffset
End Get
End Property
Public Overrides ReadOnly Property IsReadOnly As Boolean
Get
Return Me._underlyingField.IsReadOnly
End Get
End Property
Public Overrides ReadOnly Property IsConst As Boolean
Get
Return Me._underlyingField.IsConst
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Me._underlyingField.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property ConstantValue As Object
Get
Return Me._underlyingField.ConstantValue
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return Me._underlyingField.Locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return Me._underlyingField.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return Me._underlyingField.IsShared
End Get
End Property
Public Sub New(underlyingField As FieldSymbol)
Debug.Assert(underlyingField IsNot Nothing)
Me._underlyingField = underlyingField
End Sub
Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
Return Me._underlyingField.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken)
End Function
Friend Overrides Function GetConstantValue(inProgress As ConstantFieldsInProgress) As ConstantValue
Return Me._underlyingField.GetConstantValue(inProgress)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/VisualBasic/Portable/MakeMethodSynchronous/RemoveAsyncModifierHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.MakeMethodSynchronous
Friend Class RemoveAsyncModifierHelpers
Friend Shared Function RemoveAsyncKeyword(subOrFunctionStatement As MethodStatementSyntax) As MethodStatementSyntax
Dim modifiers = subOrFunctionStatement.Modifiers
Dim asyncTokenIndex = modifiers.IndexOf(SyntaxKind.AsyncKeyword)
Dim newSubOrFunctionKeyword = subOrFunctionStatement.SubOrFunctionKeyword
Dim newModifiers As SyntaxTokenList
If asyncTokenIndex = 0 Then
' Have to move the trivia on the async token appropriately.
Dim asyncLeadingTrivia = modifiers(0).LeadingTrivia
If modifiers.Count > 1 Then
' Move the trivia to the next modifier;
newModifiers = modifiers.Replace(
modifiers(1),
modifiers(1).WithPrependedLeadingTrivia(asyncLeadingTrivia))
newModifiers = newModifiers.RemoveAt(0)
Else
' move it to the 'sub' or 'function' keyword.
newModifiers = modifiers.RemoveAt(0)
newSubOrFunctionKeyword = newSubOrFunctionKeyword.WithPrependedLeadingTrivia(asyncLeadingTrivia)
End If
Else
newModifiers = modifiers.RemoveAt(asyncTokenIndex)
End If
Dim newSubOrFunctionStatement = subOrFunctionStatement.WithModifiers(newModifiers).WithSubOrFunctionKeyword(newSubOrFunctionKeyword)
Return newSubOrFunctionStatement
End Function
Friend Shared Function FixMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode
Dim header As LambdaHeaderSyntax = GetNewHeader(node)
Return node.WithSubOrFunctionHeader(header).WithLeadingTrivia(node.GetLeadingTrivia())
End Function
Friend Shared Function FixSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SingleLineLambdaExpressionSyntax
Dim header As LambdaHeaderSyntax = GetNewHeader(node)
Return node.WithSubOrFunctionHeader(header).WithLeadingTrivia(node.GetLeadingTrivia())
End Function
Private Shared Function GetNewHeader(node As LambdaExpressionSyntax) As LambdaHeaderSyntax
Dim header = DirectCast(node.SubOrFunctionHeader, LambdaHeaderSyntax)
Dim asyncKeywordIndex = header.Modifiers.IndexOf(SyntaxKind.AsyncKeyword)
Dim newHeader = header.WithModifiers(header.Modifiers.RemoveAt(asyncKeywordIndex))
Return newHeader
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.MakeMethodSynchronous
Friend Class RemoveAsyncModifierHelpers
Friend Shared Function RemoveAsyncKeyword(subOrFunctionStatement As MethodStatementSyntax) As MethodStatementSyntax
Dim modifiers = subOrFunctionStatement.Modifiers
Dim asyncTokenIndex = modifiers.IndexOf(SyntaxKind.AsyncKeyword)
Dim newSubOrFunctionKeyword = subOrFunctionStatement.SubOrFunctionKeyword
Dim newModifiers As SyntaxTokenList
If asyncTokenIndex = 0 Then
' Have to move the trivia on the async token appropriately.
Dim asyncLeadingTrivia = modifiers(0).LeadingTrivia
If modifiers.Count > 1 Then
' Move the trivia to the next modifier;
newModifiers = modifiers.Replace(
modifiers(1),
modifiers(1).WithPrependedLeadingTrivia(asyncLeadingTrivia))
newModifiers = newModifiers.RemoveAt(0)
Else
' move it to the 'sub' or 'function' keyword.
newModifiers = modifiers.RemoveAt(0)
newSubOrFunctionKeyword = newSubOrFunctionKeyword.WithPrependedLeadingTrivia(asyncLeadingTrivia)
End If
Else
newModifiers = modifiers.RemoveAt(asyncTokenIndex)
End If
Dim newSubOrFunctionStatement = subOrFunctionStatement.WithModifiers(newModifiers).WithSubOrFunctionKeyword(newSubOrFunctionKeyword)
Return newSubOrFunctionStatement
End Function
Friend Shared Function FixMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode
Dim header As LambdaHeaderSyntax = GetNewHeader(node)
Return node.WithSubOrFunctionHeader(header).WithLeadingTrivia(node.GetLeadingTrivia())
End Function
Friend Shared Function FixSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SingleLineLambdaExpressionSyntax
Dim header As LambdaHeaderSyntax = GetNewHeader(node)
Return node.WithSubOrFunctionHeader(header).WithLeadingTrivia(node.GetLeadingTrivia())
End Function
Private Shared Function GetNewHeader(node As LambdaExpressionSyntax) As LambdaHeaderSyntax
Dim header = DirectCast(node.SubOrFunctionHeader, LambdaHeaderSyntax)
Dim asyncKeywordIndex = header.Modifiers.IndexOf(SyntaxKind.AsyncKeyword)
Dim newHeader = header.WithModifiers(header.Modifiers.RemoveAt(asyncKeywordIndex))
Return newHeader
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./docs/compilers/CSharp/Source-Metadata Conflict.md | Conflict Between Name From Metadata And Name In Source
======================================================
When the compiler tries to bind a type name, and the same fully-qualified name designates both a name in the current (source) assembly and also a name imported from metadata, the compiler emits a warning (see ErrorCode.WRM_SameFullName*) and resolves to the one in source.
| Conflict Between Name From Metadata And Name In Source
======================================================
When the compiler tries to bind a type name, and the same fully-qualified name designates both a name in the current (source) assembly and also a name imported from metadata, the compiler emits a warning (see ErrorCode.WRM_SameFullName*) and resolves to the one in source.
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleBinaryOperator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// Rewrite <c>GetTuple() == (1, 2)</c> to <c>tuple.Item1 == 1 && tuple.Item2 == 2</c>.
/// Also supports the != operator, nullable and nested tuples.
///
/// Note that all the side-effects for visible expressions are evaluated first and from left to right. The initialization phase
/// contains side-effects for:
/// - single elements in tuple literals, like <c>a</c> in <c>(a, ...) == (...)</c> for example
/// - nested expressions that aren't tuple literals, like <c>GetTuple()</c> in <c>(..., GetTuple()) == (..., (..., ...))</c>
/// On the other hand, <c>Item1</c> and <c>Item2</c> of <c>GetTuple()</c> are not saved as part of the initialization phase of <c>GetTuple() == (..., ...)</c>
///
/// Element-wise conversions occur late, together with the element-wise comparisons. They might not be evaluated.
/// </summary>
public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node)
{
var boolType = node.Type; // we can re-use the bool type
var initEffects = ArrayBuilder<BoundExpression>.GetInstance();
var temps = ArrayBuilder<LocalSymbol>.GetInstance();
BoundExpression newLeft = ReplaceTerminalElementsWithTemps(node.Left, node.Operators, initEffects, temps);
BoundExpression newRight = ReplaceTerminalElementsWithTemps(node.Right, node.Operators, initEffects, temps);
var returnValue = RewriteTupleNestedOperators(node.Operators, newLeft, newRight, boolType, temps, node.OperatorKind);
BoundExpression result = _factory.Sequence(temps.ToImmutableAndFree(), initEffects.ToImmutableAndFree(), returnValue);
return result;
}
private bool IsLikeTupleExpression(BoundExpression expr, [NotNullWhen(true)] out BoundTupleExpression? tuple)
{
switch (expr)
{
case BoundTupleExpression t:
tuple = t;
return true;
case BoundConversion { Conversion: { Kind: ConversionKind.Identity }, Operand: var o }:
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: ConversionKind.ImplicitTupleLiteral }, Operand: var o }:
// The compiler produces the implicit tuple literal conversion as an identity conversion for
// the benefit of the semantic model only.
Debug.Assert(expr.Type == (object?)o.Type || expr.Type is { } && expr.Type.Equals(o.Type, TypeCompareKind.AllIgnoreOptions));
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: var kind } c, Operand: var o } conversion when
c.IsTupleConversion || c.IsTupleLiteralConversion:
{
// Push tuple conversions down to the elements.
if (!IsLikeTupleExpression(o, out tuple)) return false;
var underlyingConversions = c.UnderlyingConversions;
var resultTypes = conversion.Type.TupleElementTypesWithAnnotations;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var element = tuple.Arguments[i];
var elementConversion = underlyingConversions[i];
var elementType = resultTypes[i].Type;
var newArgument = new BoundConversion(
syntax: expr.Syntax,
operand: element,
conversion: elementConversion,
@checked: conversion.Checked,
explicitCastInCode: conversion.ExplicitCastInCode,
conversionGroupOpt: null,
constantValueOpt: null,
type: elementType,
hasErrors: conversion.HasErrors);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
tuple = new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: true, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, conversion.Type, conversion.HasErrors);
return true;
}
case BoundConversion { Conversion: { Kind: var kind }, Operand: var o } when
(kind == ConversionKind.ImplicitNullable || kind == ConversionKind.ExplicitNullable) &&
expr.Type is { } exprType && exprType.IsNullableType() && exprType.StrippedType().Equals(o.Type, TypeCompareKind.AllIgnoreOptions):
return IsLikeTupleExpression(o, out tuple);
default:
tuple = null;
return false;
}
}
private BoundExpression PushDownImplicitTupleConversion(
BoundExpression expr,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (expr is BoundConversion { ConversionKind: ConversionKind.ImplicitTuple, Conversion: var conversion } boundConversion)
{
// We push an implicit tuple converion down to its elements
var syntax = boundConversion.Syntax;
Debug.Assert(expr.Type is { });
var destElementTypes = expr.Type.TupleElementTypesWithAnnotations;
var numElements = destElementTypes.Length;
Debug.Assert(boundConversion.Operand.Type is { });
var srcElementFields = boundConversion.Operand.Type.TupleElements;
var fieldAccessorsBuilder = ArrayBuilder<BoundExpression>.GetInstance(numElements);
var savedTuple = DeferSideEffectingArgumentToTempForTupleEquality(LowerConversions(boundConversion.Operand), initEffects, temps);
var elementConversions = conversion.UnderlyingConversions;
for (int i = 0; i < numElements; i++)
{
var fieldAccess = MakeTupleFieldAccessAndReportUseSiteDiagnostics(savedTuple, syntax, srcElementFields[i]);
var convertedFieldAccess = new BoundConversion(
syntax, fieldAccess, elementConversions[i], boundConversion.Checked, boundConversion.ExplicitCastInCode, null, null, destElementTypes[i].Type, boundConversion.HasErrors);
fieldAccessorsBuilder.Add(convertedFieldAccess);
}
return new BoundConvertedTupleLiteral(
syntax, sourceTuple: null, wasTargetTyped: true, fieldAccessorsBuilder.ToImmutableAndFree(), ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, expr.Type, expr.HasErrors);
}
return expr;
}
/// <summary>
/// Walk down tuple literals and replace all the side-effecting elements that need saving with temps.
/// Expressions that are not tuple literals need saving, as are tuple literals that are involved in
/// a simple comparison rather than a tuple comparison.
/// </summary>
private BoundExpression ReplaceTerminalElementsWithTemps(
BoundExpression expr,
TupleBinaryOperatorInfo operators,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (operators.InfoKind == TupleBinaryOperatorInfoKind.Multiple)
{
expr = PushDownImplicitTupleConversion(expr, initEffects, temps);
if (IsLikeTupleExpression(expr, out BoundTupleExpression? tuple))
{
// Example:
// in `(expr1, expr2) == (..., ...)` we need to save `expr1` and `expr2`
var multiple = (TupleBinaryOperatorInfo.Multiple)operators;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var argument = tuple.Arguments[i];
var newArgument = ReplaceTerminalElementsWithTemps(argument, multiple.Operators[i], initEffects, temps);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
return new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: false, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, tuple.Type, tuple.HasErrors);
}
}
// Examples:
// in `expr == (..., ...)` we need to save `expr` because it's not a tuple literal
// in `(..., expr) == (..., (..., ...))` we need to save `expr` because it is used in a simple comparison
return DeferSideEffectingArgumentToTempForTupleEquality(expr, initEffects, temps);
}
/// <summary>
/// Evaluate side effects into a temp, if necessary. If there is an implicit user-defined
/// conversion operation near the top of the arg, preserve that in the returned expression to be evaluated later.
/// Conversions at the head of the result are unlowered, though the nested arguments within it are lowered.
/// That resulting expression must be passed through <see cref="LowerConversions(BoundExpression)"/> to
/// complete the lowering.
/// </summary>
private BoundExpression DeferSideEffectingArgumentToTempForTupleEquality(
BoundExpression expr,
ArrayBuilder<BoundExpression> effects,
ArrayBuilder<LocalSymbol> temps,
bool enclosingConversionWasExplicit = false)
{
switch (expr)
{
case { ConstantValue: { } }:
return VisitExpression(expr);
case BoundConversion { Conversion: { Kind: ConversionKind.DefaultLiteral } }:
// This conversion can be performed lazily, but need not be saved. It is treated as non-side-effecting.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { Kind: var conversionKind } conversion } bc when conversionMustBePerformedOnOriginalExpression(bc, conversionKind):
// Some conversions cannot be performed on a copy of the argument and must be done early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { IsUserDefined: true } } conv when conv.ExplicitCastInCode || enclosingConversionWasExplicit:
// A user-defined conversion triggered by a cast must be performed early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion conv:
{
// other conversions are deferred
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(conv.Operand, effects, temps, conv.ExplicitCastInCode || enclosingConversionWasExplicit);
return conv.UpdateOperand(deferredOperand);
}
case BoundObjectCreationExpression { Arguments: { Length: 0 }, Type: { } eType } _ when eType.IsNullableType():
return new BoundLiteral(expr.Syntax, ConstantValue.Null, expr.Type);
case BoundObjectCreationExpression { Arguments: { Length: 1 }, Type: { } eType } creation when eType.IsNullableType():
{
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(
creation.Arguments[0], effects, temps, enclosingConversionWasExplicit: true);
return new BoundConversion(
syntax: expr.Syntax, operand: deferredOperand,
conversion: Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity),
@checked: false, explicitCastInCode: true, conversionGroupOpt: null, constantValueOpt: null,
type: eType, hasErrors: expr.HasErrors);
}
default:
// When in doubt, evaluate early to a temp.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
}
bool conversionMustBePerformedOnOriginalExpression(BoundConversion expr, ConversionKind kind)
{
// These are conversions from-expression that
// must be performed on the original expression, not on a copy of it.
switch (kind)
{
case ConversionKind.AnonymousFunction: // a lambda cannot be saved without a target type
case ConversionKind.MethodGroup: // similarly for a method group
case ConversionKind.InterpolatedString: // an interpolated string must be saved in interpolated form
case ConversionKind.SwitchExpression: // a switch expression must have its arms converted
case ConversionKind.StackAllocToPointerType: // a stack alloc is not well-defined without an enclosing conversion
case ConversionKind.ConditionalExpression: // a conditional expression must have its alternatives converted
case ConversionKind.StackAllocToSpanType:
case ConversionKind.ObjectCreation:
return true;
default:
return false;
}
}
}
private BoundExpression RewriteTupleOperator(TupleBinaryOperatorInfo @operator,
BoundExpression left, BoundExpression right, TypeSymbol boolType,
ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
switch (@operator.InfoKind)
{
case TupleBinaryOperatorInfoKind.Multiple:
return RewriteTupleNestedOperators((TupleBinaryOperatorInfo.Multiple)@operator, left, right, boolType, temps, operatorKind);
case TupleBinaryOperatorInfoKind.Single:
return RewriteTupleSingleOperator((TupleBinaryOperatorInfo.Single)@operator, left, right, boolType, operatorKind);
case TupleBinaryOperatorInfoKind.NullNull:
var nullnull = (TupleBinaryOperatorInfo.NullNull)@operator;
return new BoundLiteral(left.Syntax, ConstantValue.Create(nullnull.Kind == BinaryOperatorKind.Equal), boolType);
default:
throw ExceptionUtilities.UnexpectedValue(@operator.InfoKind);
}
}
private BoundExpression RewriteTupleNestedOperators(TupleBinaryOperatorInfo.Multiple operators, BoundExpression left, BoundExpression right,
TypeSymbol boolType, ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
// If either left or right is nullable, produce:
//
// // outer sequence
// leftHasValue = left.HasValue; (or true if !leftNullable)
// leftHasValue == right.HasValue (or true if !rightNullable)
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
//
// where inner sequence is:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
//
// and true/false and false/true depend on operatorKind (== vs. !=)
//
// But if neither is nullable, then just produce the inner sequence.
//
// Note: all the temps are created in a single bucket (rather than different scopes of applicability) for simplicity
var outerEffects = ArrayBuilder<BoundExpression>.GetInstance();
var innerEffects = ArrayBuilder<BoundExpression>.GetInstance();
BoundExpression leftHasValue, leftValue;
bool isLeftNullable;
MakeNullableParts(left, temps, innerEffects, outerEffects, saveHasValue: true, out leftHasValue, out leftValue, out isLeftNullable);
BoundExpression rightHasValue, rightValue;
bool isRightNullable;
// no need for local for right.HasValue since used once
MakeNullableParts(right, temps, innerEffects, outerEffects, saveHasValue: false, out rightHasValue, out rightValue, out isRightNullable);
// Produces:
// ... logical expression using leftValue and rightValue ...
BoundExpression logicalExpression = RewriteNonNullableNestedTupleOperators(operators, leftValue, rightValue, boolType, temps, innerEffects, operatorKind);
// Produces:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
BoundExpression innerSequence = _factory.Sequence(locals: ImmutableArray<LocalSymbol>.Empty, innerEffects.ToImmutableAndFree(), logicalExpression);
if (!isLeftNullable && !isRightNullable)
{
// The outer sequence degenerates when we know that both `leftHasValue` and `rightHasValue` are true
return innerSequence;
}
bool boolValue = operatorKind == BinaryOperatorKind.Equal; // true/false
if (rightHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `rightHasValue` is false
// Produce: !leftHasValue (or leftHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(leftHasValue) : leftHasValue);
}
if (leftHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `leftHasValue` is false
// Produce: !rightHasValue (or rightHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(rightHasValue) : rightHasValue);
}
// outer sequence:
// leftHasValue == rightHasValue
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
BoundExpression outerSequence =
_factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
_factory.Conditional(
_factory.Binary(BinaryOperatorKind.Equal, boolType, leftHasValue, rightHasValue),
_factory.Conditional(leftHasValue, innerSequence, MakeBooleanConstant(right.Syntax, boolValue), boolType),
MakeBooleanConstant(right.Syntax, !boolValue),
boolType));
return outerSequence;
}
/// <summary>
/// Produce a <c>.HasValue</c> and a <c>.GetValueOrDefault()</c> for nullable expressions that are neither always null or
/// never null, and functionally equivalent parts for other cases.
/// </summary>
private void MakeNullableParts(BoundExpression expr, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> innerEffects,
ArrayBuilder<BoundExpression> outerEffects, bool saveHasValue, out BoundExpression hasValue, out BoundExpression value, out bool isNullable)
{
isNullable = !(expr is BoundTupleExpression) && expr.Type is { } && expr.Type.IsNullableType();
if (!isNullable)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
expr = PushDownImplicitTupleConversion(expr, innerEffects, temps);
value = expr;
return;
}
// Optimization for nullable expressions that are always null
if (NullableNeverHasValue(expr))
{
Debug.Assert(expr.Type is { });
hasValue = MakeBooleanConstant(expr.Syntax, false);
// Since there is no value in this nullable expression, we don't need to construct a `.GetValueOrDefault()`, `default(T)` will suffice
value = new BoundDefaultExpression(expr.Syntax, expr.Type.StrippedType());
return;
}
// Optimization for nullable expressions that are never null
if (NullableAlwaysHasValue(expr) is BoundExpression knownValue)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
// If a tuple conversion, keep its parts around with deferred conversions.
value = PushDownImplicitTupleConversion(knownValue, innerEffects, temps);
value = LowerConversions(value);
isNullable = false;
return;
}
// Regular nullable expressions
hasValue = makeNullableHasValue(expr);
if (saveHasValue)
{
hasValue = MakeTemp(hasValue, temps, outerEffects);
}
value = MakeValueOrDefaultTemp(expr, temps, innerEffects);
BoundExpression makeNullableHasValue(BoundExpression expr)
{
// Optimize conversions where we can use the HasValue of the underlying
Debug.Assert(expr.Type is { });
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return makeNullableHasValue(o);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var underlying }, Operand: var o }
when expr.Type.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && !underlying[0].IsUserDefined:
// Note that a user-defined conversion from K to Nullable<R> which may translate
// a non-null K to a null value gives rise to a lifted conversion from Nullable<K> to Nullable<R> with the same property.
// We therefore do not attempt to optimize nullable conversions with an underlying user-defined conversion.
return makeNullableHasValue(o);
default:
return MakeNullableHasValue(expr.Syntax, expr);
}
}
}
private BoundLocal MakeTemp(BoundExpression loweredExpression, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects)
{
BoundLocal temp = _factory.StoreToTemp(loweredExpression, out BoundAssignmentOperator assignmentToTemp);
effects.Add(assignmentToTemp);
temps.Add(temp.LocalSymbol);
return temp;
}
/// <summary>
/// Returns a temp which is initialized with lowered-expression.HasValue
/// </summary>
private BoundExpression MakeValueOrDefaultTemp(
BoundExpression expr,
ArrayBuilder<LocalSymbol> temps,
ArrayBuilder<BoundExpression> effects)
{
// Optimize conversions where we can use the underlying
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return MakeValueOrDefaultTemp(o, temps, effects);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var nested }, Operand: var o } conv when
expr.Type is { } exprType && exprType.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && nested[0] is { IsTupleConversion: true } tupleConversion:
{
Debug.Assert(expr.Type is { });
var operand = MakeValueOrDefaultTemp(o, temps, effects);
Debug.Assert(operand.Type is { });
var types = expr.Type.GetNullableUnderlyingType().TupleElementTypesWithAnnotations;
int tupleCardinality = operand.Type.TupleElementTypesWithAnnotations.Length;
var underlyingConversions = tupleConversion.UnderlyingConversions;
Debug.Assert(underlyingConversions.Length == tupleCardinality);
var argumentBuilder = ArrayBuilder<BoundExpression>.GetInstance(tupleCardinality);
for (int i = 0; i < tupleCardinality; i++)
{
argumentBuilder.Add(MakeBoundConversion(GetTuplePart(operand, i), underlyingConversions[i], types[i], conv));
}
return new BoundConvertedTupleLiteral(
syntax: operand.Syntax,
sourceTuple: null,
wasTargetTyped: false,
arguments: argumentBuilder.ToImmutableAndFree(),
argumentNamesOpt: ImmutableArray<string?>.Empty,
inferredNamesOpt: ImmutableArray<bool>.Empty,
type: expr.Type,
hasErrors: expr.HasErrors).WithSuppression(expr.IsSuppressed);
throw null;
}
default:
{
BoundExpression valueOrDefaultCall = MakeOptimizedGetValueOrDefault(expr.Syntax, expr);
return MakeTemp(valueOrDefaultCall, temps, effects);
}
}
BoundExpression MakeBoundConversion(BoundExpression expr, Conversion conversion, TypeWithAnnotations type, BoundConversion enclosing)
{
return new BoundConversion(
expr.Syntax, expr, conversion, enclosing.Checked, enclosing.ExplicitCastInCode,
conversionGroupOpt: null, constantValueOpt: null, type: type.Type);
}
}
/// <summary>
/// Produces a chain of equality (or inequality) checks combined logically with AND (or OR)
/// </summary>
private BoundExpression RewriteNonNullableNestedTupleOperators(TupleBinaryOperatorInfo.Multiple operators,
BoundExpression left, BoundExpression right, TypeSymbol type,
ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects, BinaryOperatorKind operatorKind)
{
ImmutableArray<TupleBinaryOperatorInfo> nestedOperators = operators.Operators;
BoundExpression? currentResult = null;
for (int i = 0; i < nestedOperators.Length; i++)
{
BoundExpression leftElement = GetTuplePart(left, i);
BoundExpression rightElement = GetTuplePart(right, i);
BoundExpression nextLogicalOperand = RewriteTupleOperator(nestedOperators[i], leftElement, rightElement, type, temps, operatorKind);
if (currentResult is null)
{
currentResult = nextLogicalOperand;
}
else
{
var logicalOperator = operatorKind == BinaryOperatorKind.Equal ? BinaryOperatorKind.LogicalBoolAnd : BinaryOperatorKind.LogicalBoolOr;
currentResult = _factory.Binary(logicalOperator, type, currentResult, nextLogicalOperand);
}
}
Debug.Assert(currentResult is { });
return currentResult;
}
/// <summary>
/// For tuple literals, we just return the element.
/// For expressions with tuple type, we access <c>Item{i+1}</c>.
/// </summary>
private BoundExpression GetTuplePart(BoundExpression tuple, int i)
{
// Example:
// (1, 2) == (1, 2);
if (tuple is BoundTupleExpression tupleExpression)
{
return tupleExpression.Arguments[i];
}
Debug.Assert(tuple.Type is { IsTupleType: true });
// Example:
// t == GetTuple();
// t == ((byte, byte)) (1, 2);
// t == ((short, short))((int, int))(1L, 2L);
return MakeTupleFieldAccessAndReportUseSiteDiagnostics(tuple, tuple.Syntax, tuple.Type.TupleElements[i]);
}
/// <summary>
/// Produce an element-wise comparison and logic to ensure the result is a bool type.
///
/// If an element-wise comparison doesn't return bool, then:
/// - if it is dynamic, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c>
/// - if it implicitly converts to bool, we'll just do the conversion
/// - otherwise, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c> (as we'd do for <c>if</c> or <c>while</c>)
/// </summary>
private BoundExpression RewriteTupleSingleOperator(TupleBinaryOperatorInfo.Single single,
BoundExpression left, BoundExpression right, TypeSymbol boolType, BinaryOperatorKind operatorKind)
{
// We deferred lowering some of the conversions on the operand, even though the
// code below the conversions were lowered. We lower the conversion part now.
left = LowerConversions(left);
right = LowerConversions(right);
if (single.Kind.IsDynamic())
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression dynamicResult = _dynamicFactory.MakeDynamicBinaryOperator(single.Kind, left, right, isCompoundAssignment: false, _compilation.DynamicType).ToExpression();
if (operatorKind == BinaryOperatorKind.Equal)
{
return _factory.Not(MakeUnaryOperator(UnaryOperatorKind.DynamicFalse, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType));
}
else
{
return MakeUnaryOperator(UnaryOperatorKind.DynamicTrue, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType);
}
}
if (left.IsLiteralNull() && right.IsLiteralNull())
{
// For `null == null` this is special-cased during initial binding
return new BoundLiteral(left.Syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.Equal), boolType);
}
BoundExpression binary = MakeBinaryOperator(_factory.Syntax, single.Kind, left, right, single.MethodSymbolOpt?.ReturnType ?? boolType, single.MethodSymbolOpt, single.ConstrainedToTypeOpt);
UnaryOperatorSignature boolOperator = single.BoolOperator;
Conversion boolConversion = single.ConversionForBool;
BoundExpression result;
if (boolOperator.Kind != UnaryOperatorKind.Error)
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression convertedBinary = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolOperator.OperandType, @checked: false);
Debug.Assert(boolOperator.ReturnType.SpecialType == SpecialType.System_Boolean);
result = MakeUnaryOperator(boolOperator.Kind, binary.Syntax, boolOperator.Method, boolOperator.ConstrainedToTypeOpt, convertedBinary, boolType);
if (operatorKind == BinaryOperatorKind.Equal)
{
result = _factory.Not(result);
}
}
else if (!boolConversion.IsIdentity)
{
// Produce
// (bool)(left == right)
// (bool)(left != right)
result = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolType, @checked: false);
}
else
{
result = binary;
}
return result;
}
/// <summary>
/// Lower any conversions appearing near the top of the bound expression, assuming non-conversions
/// appearing below them have already been lowered.
/// </summary>
private BoundExpression LowerConversions(BoundExpression expr)
{
return (expr is BoundConversion conv)
? MakeConversionNode(
oldNodeOpt: conv, syntax: conv.Syntax, rewrittenOperand: LowerConversions(conv.Operand),
conversion: conv.Conversion, @checked: conv.Checked, explicitCastInCode: conv.ExplicitCastInCode,
constantValueOpt: conv.ConstantValue, rewrittenType: conv.Type)
: expr;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// Rewrite <c>GetTuple() == (1, 2)</c> to <c>tuple.Item1 == 1 && tuple.Item2 == 2</c>.
/// Also supports the != operator, nullable and nested tuples.
///
/// Note that all the side-effects for visible expressions are evaluated first and from left to right. The initialization phase
/// contains side-effects for:
/// - single elements in tuple literals, like <c>a</c> in <c>(a, ...) == (...)</c> for example
/// - nested expressions that aren't tuple literals, like <c>GetTuple()</c> in <c>(..., GetTuple()) == (..., (..., ...))</c>
/// On the other hand, <c>Item1</c> and <c>Item2</c> of <c>GetTuple()</c> are not saved as part of the initialization phase of <c>GetTuple() == (..., ...)</c>
///
/// Element-wise conversions occur late, together with the element-wise comparisons. They might not be evaluated.
/// </summary>
public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node)
{
var boolType = node.Type; // we can re-use the bool type
var initEffects = ArrayBuilder<BoundExpression>.GetInstance();
var temps = ArrayBuilder<LocalSymbol>.GetInstance();
BoundExpression newLeft = ReplaceTerminalElementsWithTemps(node.Left, node.Operators, initEffects, temps);
BoundExpression newRight = ReplaceTerminalElementsWithTemps(node.Right, node.Operators, initEffects, temps);
var returnValue = RewriteTupleNestedOperators(node.Operators, newLeft, newRight, boolType, temps, node.OperatorKind);
BoundExpression result = _factory.Sequence(temps.ToImmutableAndFree(), initEffects.ToImmutableAndFree(), returnValue);
return result;
}
private bool IsLikeTupleExpression(BoundExpression expr, [NotNullWhen(true)] out BoundTupleExpression? tuple)
{
switch (expr)
{
case BoundTupleExpression t:
tuple = t;
return true;
case BoundConversion { Conversion: { Kind: ConversionKind.Identity }, Operand: var o }:
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: ConversionKind.ImplicitTupleLiteral }, Operand: var o }:
// The compiler produces the implicit tuple literal conversion as an identity conversion for
// the benefit of the semantic model only.
Debug.Assert(expr.Type == (object?)o.Type || expr.Type is { } && expr.Type.Equals(o.Type, TypeCompareKind.AllIgnoreOptions));
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: var kind } c, Operand: var o } conversion when
c.IsTupleConversion || c.IsTupleLiteralConversion:
{
// Push tuple conversions down to the elements.
if (!IsLikeTupleExpression(o, out tuple)) return false;
var underlyingConversions = c.UnderlyingConversions;
var resultTypes = conversion.Type.TupleElementTypesWithAnnotations;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var element = tuple.Arguments[i];
var elementConversion = underlyingConversions[i];
var elementType = resultTypes[i].Type;
var newArgument = new BoundConversion(
syntax: expr.Syntax,
operand: element,
conversion: elementConversion,
@checked: conversion.Checked,
explicitCastInCode: conversion.ExplicitCastInCode,
conversionGroupOpt: null,
constantValueOpt: null,
type: elementType,
hasErrors: conversion.HasErrors);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
tuple = new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: true, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, conversion.Type, conversion.HasErrors);
return true;
}
case BoundConversion { Conversion: { Kind: var kind }, Operand: var o } when
(kind == ConversionKind.ImplicitNullable || kind == ConversionKind.ExplicitNullable) &&
expr.Type is { } exprType && exprType.IsNullableType() && exprType.StrippedType().Equals(o.Type, TypeCompareKind.AllIgnoreOptions):
return IsLikeTupleExpression(o, out tuple);
default:
tuple = null;
return false;
}
}
private BoundExpression PushDownImplicitTupleConversion(
BoundExpression expr,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (expr is BoundConversion { ConversionKind: ConversionKind.ImplicitTuple, Conversion: var conversion } boundConversion)
{
// We push an implicit tuple converion down to its elements
var syntax = boundConversion.Syntax;
Debug.Assert(expr.Type is { });
var destElementTypes = expr.Type.TupleElementTypesWithAnnotations;
var numElements = destElementTypes.Length;
Debug.Assert(boundConversion.Operand.Type is { });
var srcElementFields = boundConversion.Operand.Type.TupleElements;
var fieldAccessorsBuilder = ArrayBuilder<BoundExpression>.GetInstance(numElements);
var savedTuple = DeferSideEffectingArgumentToTempForTupleEquality(LowerConversions(boundConversion.Operand), initEffects, temps);
var elementConversions = conversion.UnderlyingConversions;
for (int i = 0; i < numElements; i++)
{
var fieldAccess = MakeTupleFieldAccessAndReportUseSiteDiagnostics(savedTuple, syntax, srcElementFields[i]);
var convertedFieldAccess = new BoundConversion(
syntax, fieldAccess, elementConversions[i], boundConversion.Checked, boundConversion.ExplicitCastInCode, null, null, destElementTypes[i].Type, boundConversion.HasErrors);
fieldAccessorsBuilder.Add(convertedFieldAccess);
}
return new BoundConvertedTupleLiteral(
syntax, sourceTuple: null, wasTargetTyped: true, fieldAccessorsBuilder.ToImmutableAndFree(), ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, expr.Type, expr.HasErrors);
}
return expr;
}
/// <summary>
/// Walk down tuple literals and replace all the side-effecting elements that need saving with temps.
/// Expressions that are not tuple literals need saving, as are tuple literals that are involved in
/// a simple comparison rather than a tuple comparison.
/// </summary>
private BoundExpression ReplaceTerminalElementsWithTemps(
BoundExpression expr,
TupleBinaryOperatorInfo operators,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (operators.InfoKind == TupleBinaryOperatorInfoKind.Multiple)
{
expr = PushDownImplicitTupleConversion(expr, initEffects, temps);
if (IsLikeTupleExpression(expr, out BoundTupleExpression? tuple))
{
// Example:
// in `(expr1, expr2) == (..., ...)` we need to save `expr1` and `expr2`
var multiple = (TupleBinaryOperatorInfo.Multiple)operators;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var argument = tuple.Arguments[i];
var newArgument = ReplaceTerminalElementsWithTemps(argument, multiple.Operators[i], initEffects, temps);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
return new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: false, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, tuple.Type, tuple.HasErrors);
}
}
// Examples:
// in `expr == (..., ...)` we need to save `expr` because it's not a tuple literal
// in `(..., expr) == (..., (..., ...))` we need to save `expr` because it is used in a simple comparison
return DeferSideEffectingArgumentToTempForTupleEquality(expr, initEffects, temps);
}
/// <summary>
/// Evaluate side effects into a temp, if necessary. If there is an implicit user-defined
/// conversion operation near the top of the arg, preserve that in the returned expression to be evaluated later.
/// Conversions at the head of the result are unlowered, though the nested arguments within it are lowered.
/// That resulting expression must be passed through <see cref="LowerConversions(BoundExpression)"/> to
/// complete the lowering.
/// </summary>
private BoundExpression DeferSideEffectingArgumentToTempForTupleEquality(
BoundExpression expr,
ArrayBuilder<BoundExpression> effects,
ArrayBuilder<LocalSymbol> temps,
bool enclosingConversionWasExplicit = false)
{
switch (expr)
{
case { ConstantValue: { } }:
return VisitExpression(expr);
case BoundConversion { Conversion: { Kind: ConversionKind.DefaultLiteral } }:
// This conversion can be performed lazily, but need not be saved. It is treated as non-side-effecting.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { Kind: var conversionKind } conversion } bc when conversionMustBePerformedOnOriginalExpression(bc, conversionKind):
// Some conversions cannot be performed on a copy of the argument and must be done early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { IsUserDefined: true } } conv when conv.ExplicitCastInCode || enclosingConversionWasExplicit:
// A user-defined conversion triggered by a cast must be performed early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion conv:
{
// other conversions are deferred
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(conv.Operand, effects, temps, conv.ExplicitCastInCode || enclosingConversionWasExplicit);
return conv.UpdateOperand(deferredOperand);
}
case BoundObjectCreationExpression { Arguments: { Length: 0 }, Type: { } eType } _ when eType.IsNullableType():
return new BoundLiteral(expr.Syntax, ConstantValue.Null, expr.Type);
case BoundObjectCreationExpression { Arguments: { Length: 1 }, Type: { } eType } creation when eType.IsNullableType():
{
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(
creation.Arguments[0], effects, temps, enclosingConversionWasExplicit: true);
return new BoundConversion(
syntax: expr.Syntax, operand: deferredOperand,
conversion: Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity),
@checked: false, explicitCastInCode: true, conversionGroupOpt: null, constantValueOpt: null,
type: eType, hasErrors: expr.HasErrors);
}
default:
// When in doubt, evaluate early to a temp.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
}
bool conversionMustBePerformedOnOriginalExpression(BoundConversion expr, ConversionKind kind)
{
// These are conversions from-expression that
// must be performed on the original expression, not on a copy of it.
switch (kind)
{
case ConversionKind.AnonymousFunction: // a lambda cannot be saved without a target type
case ConversionKind.MethodGroup: // similarly for a method group
case ConversionKind.InterpolatedString: // an interpolated string must be saved in interpolated form
case ConversionKind.SwitchExpression: // a switch expression must have its arms converted
case ConversionKind.StackAllocToPointerType: // a stack alloc is not well-defined without an enclosing conversion
case ConversionKind.ConditionalExpression: // a conditional expression must have its alternatives converted
case ConversionKind.StackAllocToSpanType:
case ConversionKind.ObjectCreation:
return true;
default:
return false;
}
}
}
private BoundExpression RewriteTupleOperator(TupleBinaryOperatorInfo @operator,
BoundExpression left, BoundExpression right, TypeSymbol boolType,
ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
switch (@operator.InfoKind)
{
case TupleBinaryOperatorInfoKind.Multiple:
return RewriteTupleNestedOperators((TupleBinaryOperatorInfo.Multiple)@operator, left, right, boolType, temps, operatorKind);
case TupleBinaryOperatorInfoKind.Single:
return RewriteTupleSingleOperator((TupleBinaryOperatorInfo.Single)@operator, left, right, boolType, operatorKind);
case TupleBinaryOperatorInfoKind.NullNull:
var nullnull = (TupleBinaryOperatorInfo.NullNull)@operator;
return new BoundLiteral(left.Syntax, ConstantValue.Create(nullnull.Kind == BinaryOperatorKind.Equal), boolType);
default:
throw ExceptionUtilities.UnexpectedValue(@operator.InfoKind);
}
}
private BoundExpression RewriteTupleNestedOperators(TupleBinaryOperatorInfo.Multiple operators, BoundExpression left, BoundExpression right,
TypeSymbol boolType, ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
// If either left or right is nullable, produce:
//
// // outer sequence
// leftHasValue = left.HasValue; (or true if !leftNullable)
// leftHasValue == right.HasValue (or true if !rightNullable)
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
//
// where inner sequence is:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
//
// and true/false and false/true depend on operatorKind (== vs. !=)
//
// But if neither is nullable, then just produce the inner sequence.
//
// Note: all the temps are created in a single bucket (rather than different scopes of applicability) for simplicity
var outerEffects = ArrayBuilder<BoundExpression>.GetInstance();
var innerEffects = ArrayBuilder<BoundExpression>.GetInstance();
BoundExpression leftHasValue, leftValue;
bool isLeftNullable;
MakeNullableParts(left, temps, innerEffects, outerEffects, saveHasValue: true, out leftHasValue, out leftValue, out isLeftNullable);
BoundExpression rightHasValue, rightValue;
bool isRightNullable;
// no need for local for right.HasValue since used once
MakeNullableParts(right, temps, innerEffects, outerEffects, saveHasValue: false, out rightHasValue, out rightValue, out isRightNullable);
// Produces:
// ... logical expression using leftValue and rightValue ...
BoundExpression logicalExpression = RewriteNonNullableNestedTupleOperators(operators, leftValue, rightValue, boolType, temps, innerEffects, operatorKind);
// Produces:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
BoundExpression innerSequence = _factory.Sequence(locals: ImmutableArray<LocalSymbol>.Empty, innerEffects.ToImmutableAndFree(), logicalExpression);
if (!isLeftNullable && !isRightNullable)
{
// The outer sequence degenerates when we know that both `leftHasValue` and `rightHasValue` are true
return innerSequence;
}
bool boolValue = operatorKind == BinaryOperatorKind.Equal; // true/false
if (rightHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `rightHasValue` is false
// Produce: !leftHasValue (or leftHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(leftHasValue) : leftHasValue);
}
if (leftHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `leftHasValue` is false
// Produce: !rightHasValue (or rightHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(rightHasValue) : rightHasValue);
}
// outer sequence:
// leftHasValue == rightHasValue
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
BoundExpression outerSequence =
_factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
_factory.Conditional(
_factory.Binary(BinaryOperatorKind.Equal, boolType, leftHasValue, rightHasValue),
_factory.Conditional(leftHasValue, innerSequence, MakeBooleanConstant(right.Syntax, boolValue), boolType),
MakeBooleanConstant(right.Syntax, !boolValue),
boolType));
return outerSequence;
}
/// <summary>
/// Produce a <c>.HasValue</c> and a <c>.GetValueOrDefault()</c> for nullable expressions that are neither always null or
/// never null, and functionally equivalent parts for other cases.
/// </summary>
private void MakeNullableParts(BoundExpression expr, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> innerEffects,
ArrayBuilder<BoundExpression> outerEffects, bool saveHasValue, out BoundExpression hasValue, out BoundExpression value, out bool isNullable)
{
isNullable = !(expr is BoundTupleExpression) && expr.Type is { } && expr.Type.IsNullableType();
if (!isNullable)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
expr = PushDownImplicitTupleConversion(expr, innerEffects, temps);
value = expr;
return;
}
// Optimization for nullable expressions that are always null
if (NullableNeverHasValue(expr))
{
Debug.Assert(expr.Type is { });
hasValue = MakeBooleanConstant(expr.Syntax, false);
// Since there is no value in this nullable expression, we don't need to construct a `.GetValueOrDefault()`, `default(T)` will suffice
value = new BoundDefaultExpression(expr.Syntax, expr.Type.StrippedType());
return;
}
// Optimization for nullable expressions that are never null
if (NullableAlwaysHasValue(expr) is BoundExpression knownValue)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
// If a tuple conversion, keep its parts around with deferred conversions.
value = PushDownImplicitTupleConversion(knownValue, innerEffects, temps);
value = LowerConversions(value);
isNullable = false;
return;
}
// Regular nullable expressions
hasValue = makeNullableHasValue(expr);
if (saveHasValue)
{
hasValue = MakeTemp(hasValue, temps, outerEffects);
}
value = MakeValueOrDefaultTemp(expr, temps, innerEffects);
BoundExpression makeNullableHasValue(BoundExpression expr)
{
// Optimize conversions where we can use the HasValue of the underlying
Debug.Assert(expr.Type is { });
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return makeNullableHasValue(o);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var underlying }, Operand: var o }
when expr.Type.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && !underlying[0].IsUserDefined:
// Note that a user-defined conversion from K to Nullable<R> which may translate
// a non-null K to a null value gives rise to a lifted conversion from Nullable<K> to Nullable<R> with the same property.
// We therefore do not attempt to optimize nullable conversions with an underlying user-defined conversion.
return makeNullableHasValue(o);
default:
return MakeNullableHasValue(expr.Syntax, expr);
}
}
}
private BoundLocal MakeTemp(BoundExpression loweredExpression, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects)
{
BoundLocal temp = _factory.StoreToTemp(loweredExpression, out BoundAssignmentOperator assignmentToTemp);
effects.Add(assignmentToTemp);
temps.Add(temp.LocalSymbol);
return temp;
}
/// <summary>
/// Returns a temp which is initialized with lowered-expression.HasValue
/// </summary>
private BoundExpression MakeValueOrDefaultTemp(
BoundExpression expr,
ArrayBuilder<LocalSymbol> temps,
ArrayBuilder<BoundExpression> effects)
{
// Optimize conversions where we can use the underlying
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return MakeValueOrDefaultTemp(o, temps, effects);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var nested }, Operand: var o } conv when
expr.Type is { } exprType && exprType.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && nested[0] is { IsTupleConversion: true } tupleConversion:
{
Debug.Assert(expr.Type is { });
var operand = MakeValueOrDefaultTemp(o, temps, effects);
Debug.Assert(operand.Type is { });
var types = expr.Type.GetNullableUnderlyingType().TupleElementTypesWithAnnotations;
int tupleCardinality = operand.Type.TupleElementTypesWithAnnotations.Length;
var underlyingConversions = tupleConversion.UnderlyingConversions;
Debug.Assert(underlyingConversions.Length == tupleCardinality);
var argumentBuilder = ArrayBuilder<BoundExpression>.GetInstance(tupleCardinality);
for (int i = 0; i < tupleCardinality; i++)
{
argumentBuilder.Add(MakeBoundConversion(GetTuplePart(operand, i), underlyingConversions[i], types[i], conv));
}
return new BoundConvertedTupleLiteral(
syntax: operand.Syntax,
sourceTuple: null,
wasTargetTyped: false,
arguments: argumentBuilder.ToImmutableAndFree(),
argumentNamesOpt: ImmutableArray<string?>.Empty,
inferredNamesOpt: ImmutableArray<bool>.Empty,
type: expr.Type,
hasErrors: expr.HasErrors).WithSuppression(expr.IsSuppressed);
throw null;
}
default:
{
BoundExpression valueOrDefaultCall = MakeOptimizedGetValueOrDefault(expr.Syntax, expr);
return MakeTemp(valueOrDefaultCall, temps, effects);
}
}
BoundExpression MakeBoundConversion(BoundExpression expr, Conversion conversion, TypeWithAnnotations type, BoundConversion enclosing)
{
return new BoundConversion(
expr.Syntax, expr, conversion, enclosing.Checked, enclosing.ExplicitCastInCode,
conversionGroupOpt: null, constantValueOpt: null, type: type.Type);
}
}
/// <summary>
/// Produces a chain of equality (or inequality) checks combined logically with AND (or OR)
/// </summary>
private BoundExpression RewriteNonNullableNestedTupleOperators(TupleBinaryOperatorInfo.Multiple operators,
BoundExpression left, BoundExpression right, TypeSymbol type,
ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects, BinaryOperatorKind operatorKind)
{
ImmutableArray<TupleBinaryOperatorInfo> nestedOperators = operators.Operators;
BoundExpression? currentResult = null;
for (int i = 0; i < nestedOperators.Length; i++)
{
BoundExpression leftElement = GetTuplePart(left, i);
BoundExpression rightElement = GetTuplePart(right, i);
BoundExpression nextLogicalOperand = RewriteTupleOperator(nestedOperators[i], leftElement, rightElement, type, temps, operatorKind);
if (currentResult is null)
{
currentResult = nextLogicalOperand;
}
else
{
var logicalOperator = operatorKind == BinaryOperatorKind.Equal ? BinaryOperatorKind.LogicalBoolAnd : BinaryOperatorKind.LogicalBoolOr;
currentResult = _factory.Binary(logicalOperator, type, currentResult, nextLogicalOperand);
}
}
Debug.Assert(currentResult is { });
return currentResult;
}
/// <summary>
/// For tuple literals, we just return the element.
/// For expressions with tuple type, we access <c>Item{i+1}</c>.
/// </summary>
private BoundExpression GetTuplePart(BoundExpression tuple, int i)
{
// Example:
// (1, 2) == (1, 2);
if (tuple is BoundTupleExpression tupleExpression)
{
return tupleExpression.Arguments[i];
}
Debug.Assert(tuple.Type is { IsTupleType: true });
// Example:
// t == GetTuple();
// t == ((byte, byte)) (1, 2);
// t == ((short, short))((int, int))(1L, 2L);
return MakeTupleFieldAccessAndReportUseSiteDiagnostics(tuple, tuple.Syntax, tuple.Type.TupleElements[i]);
}
/// <summary>
/// Produce an element-wise comparison and logic to ensure the result is a bool type.
///
/// If an element-wise comparison doesn't return bool, then:
/// - if it is dynamic, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c>
/// - if it implicitly converts to bool, we'll just do the conversion
/// - otherwise, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c> (as we'd do for <c>if</c> or <c>while</c>)
/// </summary>
private BoundExpression RewriteTupleSingleOperator(TupleBinaryOperatorInfo.Single single,
BoundExpression left, BoundExpression right, TypeSymbol boolType, BinaryOperatorKind operatorKind)
{
// We deferred lowering some of the conversions on the operand, even though the
// code below the conversions were lowered. We lower the conversion part now.
left = LowerConversions(left);
right = LowerConversions(right);
if (single.Kind.IsDynamic())
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression dynamicResult = _dynamicFactory.MakeDynamicBinaryOperator(single.Kind, left, right, isCompoundAssignment: false, _compilation.DynamicType).ToExpression();
if (operatorKind == BinaryOperatorKind.Equal)
{
return _factory.Not(MakeUnaryOperator(UnaryOperatorKind.DynamicFalse, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType));
}
else
{
return MakeUnaryOperator(UnaryOperatorKind.DynamicTrue, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType);
}
}
if (left.IsLiteralNull() && right.IsLiteralNull())
{
// For `null == null` this is special-cased during initial binding
return new BoundLiteral(left.Syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.Equal), boolType);
}
BoundExpression binary = MakeBinaryOperator(_factory.Syntax, single.Kind, left, right, single.MethodSymbolOpt?.ReturnType ?? boolType, single.MethodSymbolOpt, single.ConstrainedToTypeOpt);
UnaryOperatorSignature boolOperator = single.BoolOperator;
Conversion boolConversion = single.ConversionForBool;
BoundExpression result;
if (boolOperator.Kind != UnaryOperatorKind.Error)
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression convertedBinary = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolOperator.OperandType, @checked: false);
Debug.Assert(boolOperator.ReturnType.SpecialType == SpecialType.System_Boolean);
result = MakeUnaryOperator(boolOperator.Kind, binary.Syntax, boolOperator.Method, boolOperator.ConstrainedToTypeOpt, convertedBinary, boolType);
if (operatorKind == BinaryOperatorKind.Equal)
{
result = _factory.Not(result);
}
}
else if (!boolConversion.IsIdentity)
{
// Produce
// (bool)(left == right)
// (bool)(left != right)
result = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolType, @checked: false);
}
else
{
result = binary;
}
return result;
}
/// <summary>
/// Lower any conversions appearing near the top of the bound expression, assuming non-conversions
/// appearing below them have already been lowered.
/// </summary>
private BoundExpression LowerConversions(BoundExpression expr)
{
return (expr is BoundConversion conv)
? MakeConversionNode(
oldNodeOpt: conv, syntax: conv.Syntax, rewrittenOperand: LowerConversions(conv.Operand),
conversion: conv.Conversion, @checked: conv.Checked, explicitCastInCode: conv.ExplicitCastInCode,
constantValueOpt: conv.ConstantValue, rewrittenType: conv.Type)
: expr;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Core/CommandHandlers/ExecuteInInteractiveCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CommandHandlers
{
/// <summary>
/// Implements a execute in interactive command handler.
/// This class is separated from the <see cref="IExecuteInInteractiveCommandHandler"/>
/// in order to ensure that the interactive command can be exposed without the necessity
/// to load any of the interactive dll files just to get the command's status.
/// </summary>
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name("Interactive Command Handler")]
internal class ExecuteInInteractiveCommandHandler
: ICommandHandler<ExecuteInInteractiveCommandArgs>
{
private readonly IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> _executeInInteractiveHandlers;
public string DisplayName => EditorFeaturesResources.Execute_In_Interactive;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExecuteInInteractiveCommandHandler(
[ImportMany] IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> executeInInteractiveHandlers)
{
_executeInInteractiveHandlers = executeInInteractiveHandlers;
}
private Lazy<IExecuteInInteractiveCommandHandler> GetCommandHandler(ITextBuffer textBuffer)
{
return _executeInInteractiveHandlers
.Where(handler => handler.Metadata.ContentTypes.Any(textBuffer.ContentType.IsOfType))
.SingleOrDefault();
}
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
=> GetCommandHandler(args.SubjectBuffer)?.Value.ExecuteCommand(args, context) ?? false;
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
{
return GetCommandHandler(args.SubjectBuffer) == null
? CommandState.Unavailable
: CommandState.Available;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CommandHandlers
{
/// <summary>
/// Implements a execute in interactive command handler.
/// This class is separated from the <see cref="IExecuteInInteractiveCommandHandler"/>
/// in order to ensure that the interactive command can be exposed without the necessity
/// to load any of the interactive dll files just to get the command's status.
/// </summary>
[Export(typeof(ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name("Interactive Command Handler")]
internal class ExecuteInInteractiveCommandHandler
: ICommandHandler<ExecuteInInteractiveCommandArgs>
{
private readonly IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> _executeInInteractiveHandlers;
public string DisplayName => EditorFeaturesResources.Execute_In_Interactive;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExecuteInInteractiveCommandHandler(
[ImportMany] IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> executeInInteractiveHandlers)
{
_executeInInteractiveHandlers = executeInInteractiveHandlers;
}
private Lazy<IExecuteInInteractiveCommandHandler> GetCommandHandler(ITextBuffer textBuffer)
{
return _executeInInteractiveHandlers
.Where(handler => handler.Metadata.ContentTypes.Any(textBuffer.ContentType.IsOfType))
.SingleOrDefault();
}
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
=> GetCommandHandler(args.SubjectBuffer)?.Value.ExecuteCommand(args, context) ?? false;
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
{
return GetCommandHandler(args.SubjectBuffer) == null
? CommandState.Unavailable
: CommandState.Available;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Text/ContentTypeNames.cs | // Licensed to the .NET Foundation under one or more 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.Editor
{
internal static class ContentTypeNames
{
public const string CSharpContentType = "CSharp";
public const string CSharpSignatureHelpContentType = "CSharp Signature Help";
public const string RoslynContentType = "Roslyn Languages";
public const string VisualBasicContentType = "Basic";
public const string VisualBasicSignatureHelpContentType = "Basic Signature Help";
public const string XamlContentType = "XAML";
public const string JavaScriptContentTypeName = "JavaScript";
public const string TypeScriptContentTypeName = "TypeScript";
public const string FSharpContentType = "F#";
public const string FSharpSignatureHelpContentType = "F# Signature Help";
}
}
| // Licensed to the .NET Foundation under one or more 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.Editor
{
internal static class ContentTypeNames
{
public const string CSharpContentType = "CSharp";
public const string CSharpSignatureHelpContentType = "CSharp Signature Help";
public const string RoslynContentType = "Roslyn Languages";
public const string VisualBasicContentType = "Basic";
public const string VisualBasicSignatureHelpContentType = "Basic Signature Help";
public const string XamlContentType = "XAML";
public const string JavaScriptContentTypeName = "JavaScript";
public const string TypeScriptContentTypeName = "TypeScript";
public const string FSharpContentType = "F#";
public const string FSharpSignatureHelpContentType = "F# Signature Help";
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Test2/InteractivePaste/InteractivePasteCommandHandlerTests.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.Text
Imports System.Windows
Imports Microsoft.CodeAnalysis.Editor.CommandHandlers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.VisualStudio.InteractiveWindow
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InteractivePaste
<[UseExportProvider]>
Public Class InteractivePasteCommandhandlerTests
Private Const ClipboardLineBasedCutCopyTag As String = "VisualStudioEditorOperationsLineCutCopyClipboardTag"
Private Const BoxSelectionCutCopyTag As String = "MSDEVColumnSelect"
Private Shared Function CreateCommandHandler(workspace As TestWorkspace) As InteractivePasteCommandHandler
Dim handler = workspace.ExportProvider.GetCommandHandler(Of InteractivePasteCommandHandler)(PredefinedCommandHandlerNames.InteractivePaste)
handler.RoslynClipboard = New MockClipboard()
Return handler
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormat()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""a\u000d\u000abc"",""kind"":1},
{""content"":""> "",""kind"":0},
{""content"":""< "",""kind"":0},
{""content"":""12"",""kind"":2},
{""content"":""3"",""kind"":3},
]"
Dim text = $"a{vbCrLf}bc123"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=False)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("a" & vbCrLf & "bc123", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithOutInteractiveFormat()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""a\u000d\u000abc"",""kind"":1},
{""content"":""> "",""kind"":0},
{""content"":""< "",""kind"":0},
{""content"":""12"",""kind"":2},
{""content"":""3"",""kind"":3}]
]"
Dim text = $"a{vbCrLf}bc123"
CopyToClipboard(clipboard, text, json, includeRepl:=False, isLineCopy:=False, isBoxCopy:=False)
If Not handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()) Then
editorOperations.InsertText("p")
End If
Assert.Equal("p", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsLineCopy()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
Assert.Equal("line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""InsertedLine"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}]
]"
Dim text = $"InsertedLine{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=True, isBoxCopy:=False)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("line1" & vbCrLf & "InsertedLine" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsBoxCopy()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
editorOperations.MoveLineUp(False)
editorOperations.MoveToPreviousCharacter(False)
Assert.Equal("line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""BoxLine1"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4},
{""content"":""> "",""kind"":0},
{""content"":""BoxLine2"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}]
]"
Dim text = $"BoxLine1{vbCrLf}BoxLine2{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=True)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("lineBoxLine11" & vbCrLf & " BoxLine2line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsBoxCopyOnBlankLine()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertNewLine()
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
editorOperations.MoveLineUp(False)
editorOperations.MoveLineUp(False)
Assert.Equal(vbCrLf & "line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""BoxLine1"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4},
{""content"":""> "",""kind"":0},
{""content"":""BoxLine2"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}
]"
Dim text = $"> BoxLine1{vbCrLf}> BoxLine2{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=True)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("BoxLine1" & vbCrLf & "BoxLine2" & vbCrLf & "line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
Private Shared Sub CopyToClipboard(clipboard As MockClipboard, text As String, json As String, includeRepl As Boolean, isLineCopy As Boolean, isBoxCopy As Boolean)
clipboard.Clear()
Dim data = New DataObject()
Dim builder = New StringBuilder()
data.SetData(DataFormats.UnicodeText, text)
data.SetData(DataFormats.StringFormat, text)
If includeRepl Then
data.SetData(InteractiveClipboardFormat.Tag, json)
End If
If isLineCopy Then
data.SetData(ClipboardLineBasedCutCopyTag, True)
End If
If isBoxCopy Then
data.SetData(BoxSelectionCutCopyTag, True)
End If
clipboard.SetDataObject(data)
End Sub
Private Class MockClipboard
Implements InteractivePasteCommandHandler.IRoslynClipboard
Private _data As DataObject
Friend Sub Clear()
_data = Nothing
End Sub
Friend Sub SetDataObject(data As Object)
_data = DirectCast(data, DataObject)
End Sub
Public Function ContainsData(format As String) As Boolean Implements InteractivePasteCommandHandler.IRoslynClipboard.ContainsData
Return _data IsNot Nothing And _data.GetData(format) IsNot Nothing
End Function
Public Function GetData(format As String) As Object Implements InteractivePasteCommandHandler.IRoslynClipboard.GetData
If _data Is Nothing Then
Return Nothing
Else
Return _data.GetData(format)
End If
End Function
Public Function GetDataObject() As IDataObject Implements InteractivePasteCommandHandler.IRoslynClipboard.GetDataObject
Return _data
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Text
Imports System.Windows
Imports Microsoft.CodeAnalysis.Editor.CommandHandlers
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.VisualStudio.InteractiveWindow
Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InteractivePaste
<[UseExportProvider]>
Public Class InteractivePasteCommandhandlerTests
Private Const ClipboardLineBasedCutCopyTag As String = "VisualStudioEditorOperationsLineCutCopyClipboardTag"
Private Const BoxSelectionCutCopyTag As String = "MSDEVColumnSelect"
Private Shared Function CreateCommandHandler(workspace As TestWorkspace) As InteractivePasteCommandHandler
Dim handler = workspace.ExportProvider.GetCommandHandler(Of InteractivePasteCommandHandler)(PredefinedCommandHandlerNames.InteractivePaste)
handler.RoslynClipboard = New MockClipboard()
Return handler
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormat()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""a\u000d\u000abc"",""kind"":1},
{""content"":""> "",""kind"":0},
{""content"":""< "",""kind"":0},
{""content"":""12"",""kind"":2},
{""content"":""3"",""kind"":3},
]"
Dim text = $"a{vbCrLf}bc123"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=False)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("a" & vbCrLf & "bc123", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithOutInteractiveFormat()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""a\u000d\u000abc"",""kind"":1},
{""content"":""> "",""kind"":0},
{""content"":""< "",""kind"":0},
{""content"":""12"",""kind"":2},
{""content"":""3"",""kind"":3}]
]"
Dim text = $"a{vbCrLf}bc123"
CopyToClipboard(clipboard, text, json, includeRepl:=False, isLineCopy:=False, isBoxCopy:=False)
If Not handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()) Then
editorOperations.InsertText("p")
End If
Assert.Equal("p", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsLineCopy()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
Assert.Equal("line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""InsertedLine"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}]
]"
Dim text = $"InsertedLine{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=True, isBoxCopy:=False)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("line1" & vbCrLf & "InsertedLine" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsBoxCopy()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
editorOperations.MoveLineUp(False)
editorOperations.MoveToPreviousCharacter(False)
Assert.Equal("line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""BoxLine1"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4},
{""content"":""> "",""kind"":0},
{""content"":""BoxLine2"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}]
]"
Dim text = $"BoxLine1{vbCrLf}BoxLine2{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=True)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("lineBoxLine11" & vbCrLf & " BoxLine2line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
<WpfFact>
<Trait(Traits.Feature, Traits.Features.Interactive)>
Public Sub PasteCommandWithInteractiveFormatAsBoxCopyOnBlankLine()
Using workspace = TestWorkspace.Create(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document/>
</Project>
</Workspace>,
composition:=EditorTestCompositions.EditorFeaturesWpf)
Dim textView = workspace.Documents.Single().GetTextView()
Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(textView)
editorOperations.InsertNewLine()
editorOperations.InsertText("line1")
editorOperations.InsertNewLine()
editorOperations.InsertText("line2")
editorOperations.MoveLineUp(False)
editorOperations.MoveLineUp(False)
Assert.Equal(vbCrLf & "line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
Dim handler = CreateCommandHandler(workspace)
Dim clipboard = DirectCast(handler.RoslynClipboard, MockClipboard)
Dim json = "
[
{""content"":""> "",""kind"":0},
{""content"":""BoxLine1"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4},
{""content"":""> "",""kind"":0},
{""content"":""BoxLine2"",""kind"":2},
{""content"":""\u000d\u000a"",""kind"":4}
]"
Dim text = $"> BoxLine1{vbCrLf}> BoxLine2{vbCrLf}"
CopyToClipboard(clipboard, text, json, includeRepl:=True, isLineCopy:=False, isBoxCopy:=True)
Assert.True(handler.ExecuteCommand(New PasteCommandArgs(textView, textView.TextBuffer), TestCommandExecutionContext.Create()))
Assert.Equal("BoxLine1" & vbCrLf & "BoxLine2" & vbCrLf & "line1" & vbCrLf & " line2", textView.TextBuffer.CurrentSnapshot.GetText())
End Using
End Sub
Private Shared Sub CopyToClipboard(clipboard As MockClipboard, text As String, json As String, includeRepl As Boolean, isLineCopy As Boolean, isBoxCopy As Boolean)
clipboard.Clear()
Dim data = New DataObject()
Dim builder = New StringBuilder()
data.SetData(DataFormats.UnicodeText, text)
data.SetData(DataFormats.StringFormat, text)
If includeRepl Then
data.SetData(InteractiveClipboardFormat.Tag, json)
End If
If isLineCopy Then
data.SetData(ClipboardLineBasedCutCopyTag, True)
End If
If isBoxCopy Then
data.SetData(BoxSelectionCutCopyTag, True)
End If
clipboard.SetDataObject(data)
End Sub
Private Class MockClipboard
Implements InteractivePasteCommandHandler.IRoslynClipboard
Private _data As DataObject
Friend Sub Clear()
_data = Nothing
End Sub
Friend Sub SetDataObject(data As Object)
_data = DirectCast(data, DataObject)
End Sub
Public Function ContainsData(format As String) As Boolean Implements InteractivePasteCommandHandler.IRoslynClipboard.ContainsData
Return _data IsNot Nothing And _data.GetData(format) IsNot Nothing
End Function
Public Function GetData(format As String) As Object Implements InteractivePasteCommandHandler.IRoslynClipboard.GetData
If _data Is Nothing Then
Return Nothing
Else
Return _data.GetData(format)
End If
End Function
Public Function GetDataObject() As IDataObject Implements InteractivePasteCommandHandler.IRoslynClipboard.GetDataObject
Return _data
End Function
End Class
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.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.
#nullable disable
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private class IntroduceVariableCodeAction : AbstractIntroduceVariableCodeAction
{
internal IntroduceVariableCodeAction(
TService service,
SemanticDocument document,
TExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
bool isLocal,
bool isQueryLocal)
: base(service, document, expression, allOccurrences, isConstant, isLocal, isQueryLocal)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private class IntroduceVariableCodeAction : AbstractIntroduceVariableCodeAction
{
internal IntroduceVariableCodeAction(
TService service,
SemanticDocument document,
TExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
bool isLocal,
bool isQueryLocal)
: base(service, document, expression, allOccurrences, isConstant, isLocal, isQueryLocal)
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/BaseFormattingRule.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal abstract class BaseFormattingRule : AbstractFormattingRule
{
protected static void AddUnindentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
TextSpan textSpan,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, textSpan, indentationDelta: -1, option: option));
}
protected static void AddUnindentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
bool includeTriviaAtEnd = false,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
if (includeTriviaAtEnd)
{
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: -1, option: option));
}
else
{
var startPosition = CommonFormattingHelpers.GetStartPositionOfSpan(startToken);
var endPosition = endToken.Span.End;
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, TextSpan.FromBounds(startPosition, endPosition), indentationDelta: -1, option: option));
}
}
protected static void AddAbsoluteZeroIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.AbsolutePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 0, option: option));
}
protected static void AddIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: option));
}
protected static void AddIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
TextSpan textSpan,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, textSpan, indentationDelta: 1, option: option));
}
protected static void AddIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken baseToken,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, indentationDelta: 1, option: option));
}
protected static void SetAlignmentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken baseToken,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, indentationDelta: 0, option: option));
}
protected static void AddSuppressWrappingIfOnSingleLineOperation(List<SuppressOperation> list, SyntaxToken startToken, SyntaxToken endToken, SuppressOption extraOption = SuppressOption.None)
=> AddSuppressOperation(list, startToken, endToken, SuppressOption.NoWrappingIfOnSingleLine | extraOption);
protected static void AddSuppressAllOperationIfOnMultipleLine(List<SuppressOperation> list, SyntaxToken startToken, SyntaxToken endToken, SuppressOption extraOption = SuppressOption.None)
=> AddSuppressOperation(list, startToken, endToken, SuppressOption.NoSpacingIfOnMultipleLine | SuppressOption.NoWrapping | extraOption);
protected static void AddSuppressOperation(List<SuppressOperation> list, SyntaxToken startToken, SyntaxToken endToken, SuppressOption option)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateSuppressOperation(startToken, endToken, option));
}
protected static void AddAnchorIndentationOperation(List<AnchorIndentationOperation> list, SyntaxToken anchorToken, SyntaxToken endToken)
{
if (anchorToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateAnchorIndentationOperation(anchorToken, endToken));
}
protected static void AddAlignIndentationOfTokensToBaseTokenOperation(List<AlignTokensOperation> list, SyntaxNode containingNode, SyntaxToken baseNode, IEnumerable<SyntaxToken> tokens, AlignTokensOption option = AlignTokensOption.AlignIndentationOfTokensToBaseToken)
{
if (containingNode == null || tokens == null)
{
return;
}
list.Add(FormattingOperations.CreateAlignTokensOperation(baseNode, tokens, option));
}
protected static AdjustNewLinesOperation CreateAdjustNewLinesOperation(int line, AdjustNewLinesOption option)
=> FormattingOperations.CreateAdjustNewLinesOperation(line, option);
protected static AdjustSpacesOperation CreateAdjustSpacesOperation(int space, AdjustSpacesOption option)
=> FormattingOperations.CreateAdjustSpacesOperation(space, option);
protected static void AddBraceSuppressOperations(List<SuppressOperation> list, SyntaxNode node)
{
var bracePair = node.GetBracePair();
if (!bracePair.IsValidBracePair())
{
return;
}
var firstTokenOfNode = node.GetFirstToken(includeZeroWidth: true);
if (node is MemberDeclarationSyntax memberDeclNode)
{
(firstTokenOfNode, _) = memberDeclNode.GetFirstAndLastMemberDeclarationTokensAfterAttributes();
}
if (node.IsLambdaBodyBlock())
{
RoslynDebug.AssertNotNull(node.Parent);
// include lambda itself.
firstTokenOfNode = node.Parent.GetFirstToken(includeZeroWidth: true);
}
else if (node.IsKind(SyntaxKind.PropertyPatternClause))
{
// include the pattern recursive pattern syntax and/or subpattern
firstTokenOfNode = firstTokenOfNode.GetPreviousToken();
}
// suppress wrapping on whole construct that owns braces and also brace pair itself if
// it is on same line
AddSuppressWrappingIfOnSingleLineOperation(list, firstTokenOfNode, bracePair.closeBrace);
AddSuppressWrappingIfOnSingleLineOperation(list, bracePair.openBrace, bracePair.closeBrace);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal abstract class BaseFormattingRule : AbstractFormattingRule
{
protected static void AddUnindentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
TextSpan textSpan,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, textSpan, indentationDelta: -1, option: option));
}
protected static void AddUnindentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
bool includeTriviaAtEnd = false,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
if (includeTriviaAtEnd)
{
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: -1, option: option));
}
else
{
var startPosition = CommonFormattingHelpers.GetStartPositionOfSpan(startToken);
var endPosition = endToken.Span.End;
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, TextSpan.FromBounds(startPosition, endPosition), indentationDelta: -1, option: option));
}
}
protected static void AddAbsoluteZeroIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.AbsolutePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 0, option: option));
}
protected static void AddIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: option));
}
protected static void AddIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken startToken,
SyntaxToken endToken,
TextSpan textSpan,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, textSpan, indentationDelta: 1, option: option));
}
protected static void AddIndentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken baseToken,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, indentationDelta: 1, option: option));
}
protected static void SetAlignmentBlockOperation(
List<IndentBlockOperation> list,
SyntaxToken baseToken,
SyntaxToken startToken,
SyntaxToken endToken,
IndentBlockOption option = IndentBlockOption.RelativePosition)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, indentationDelta: 0, option: option));
}
protected static void AddSuppressWrappingIfOnSingleLineOperation(List<SuppressOperation> list, SyntaxToken startToken, SyntaxToken endToken, SuppressOption extraOption = SuppressOption.None)
=> AddSuppressOperation(list, startToken, endToken, SuppressOption.NoWrappingIfOnSingleLine | extraOption);
protected static void AddSuppressAllOperationIfOnMultipleLine(List<SuppressOperation> list, SyntaxToken startToken, SyntaxToken endToken, SuppressOption extraOption = SuppressOption.None)
=> AddSuppressOperation(list, startToken, endToken, SuppressOption.NoSpacingIfOnMultipleLine | SuppressOption.NoWrapping | extraOption);
protected static void AddSuppressOperation(List<SuppressOperation> list, SyntaxToken startToken, SyntaxToken endToken, SuppressOption option)
{
if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateSuppressOperation(startToken, endToken, option));
}
protected static void AddAnchorIndentationOperation(List<AnchorIndentationOperation> list, SyntaxToken anchorToken, SyntaxToken endToken)
{
if (anchorToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None)
{
return;
}
list.Add(FormattingOperations.CreateAnchorIndentationOperation(anchorToken, endToken));
}
protected static void AddAlignIndentationOfTokensToBaseTokenOperation(List<AlignTokensOperation> list, SyntaxNode containingNode, SyntaxToken baseNode, IEnumerable<SyntaxToken> tokens, AlignTokensOption option = AlignTokensOption.AlignIndentationOfTokensToBaseToken)
{
if (containingNode == null || tokens == null)
{
return;
}
list.Add(FormattingOperations.CreateAlignTokensOperation(baseNode, tokens, option));
}
protected static AdjustNewLinesOperation CreateAdjustNewLinesOperation(int line, AdjustNewLinesOption option)
=> FormattingOperations.CreateAdjustNewLinesOperation(line, option);
protected static AdjustSpacesOperation CreateAdjustSpacesOperation(int space, AdjustSpacesOption option)
=> FormattingOperations.CreateAdjustSpacesOperation(space, option);
protected static void AddBraceSuppressOperations(List<SuppressOperation> list, SyntaxNode node)
{
var bracePair = node.GetBracePair();
if (!bracePair.IsValidBracePair())
{
return;
}
var firstTokenOfNode = node.GetFirstToken(includeZeroWidth: true);
if (node is MemberDeclarationSyntax memberDeclNode)
{
(firstTokenOfNode, _) = memberDeclNode.GetFirstAndLastMemberDeclarationTokensAfterAttributes();
}
if (node.IsLambdaBodyBlock())
{
RoslynDebug.AssertNotNull(node.Parent);
// include lambda itself.
firstTokenOfNode = node.Parent.GetFirstToken(includeZeroWidth: true);
}
else if (node.IsKind(SyntaxKind.PropertyPatternClause))
{
// include the pattern recursive pattern syntax and/or subpattern
firstTokenOfNode = firstTokenOfNode.GetPreviousToken();
}
// suppress wrapping on whole construct that owns braces and also brace pair itself if
// it is on same line
AddSuppressWrappingIfOnSingleLineOperation(list, firstTokenOfNode, bracePair.closeBrace);
AddSuppressWrappingIfOnSingleLineOperation(list, bracePair.openBrace, bracePair.closeBrace);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/VisualStudio/Core/Def/Implementation/DocumentationComments/VisualStudioDocumentationProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using System.Xml;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DocumentationComments
{
internal class VisualStudioDocumentationProvider : DocumentationProvider
{
private readonly string _filePath;
private readonly IVsXMLMemberIndexService _memberIndexService;
private readonly Lazy<IVsXMLMemberIndex> _lazyMemberIndex;
public VisualStudioDocumentationProvider(string filePath, IVsXMLMemberIndexService memberIndexService)
{
Contract.ThrowIfNull(memberIndexService);
Contract.ThrowIfNull(filePath);
_filePath = filePath;
_memberIndexService = memberIndexService;
_lazyMemberIndex = new Lazy<IVsXMLMemberIndex>(CreateXmlMemberIndex, isThreadSafe: true);
}
protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken token = default)
{
var memberIndex = _lazyMemberIndex.Value;
if (memberIndex == null)
{
return "";
}
if (ErrorHandler.Failed(memberIndex.ParseMemberSignature(documentationMemberID, out var methodID)))
{
return "";
}
if (ErrorHandler.Failed(memberIndex.GetMemberXML(methodID, out var xml)))
{
return "";
}
return xml;
}
private IVsXMLMemberIndex CreateXmlMemberIndex()
{
// This may fail if there is no XML file available for this assembly. We'll just leave
// memberIndex null in this case.
_memberIndexService.CreateXMLMemberIndex(_filePath, out var memberIndex);
return memberIndex;
}
public override bool Equals(object obj)
=> obj is VisualStudioDocumentationProvider other &&
string.Equals(_filePath, other._filePath, StringComparison.OrdinalIgnoreCase);
public override int GetHashCode()
=> StringComparer.OrdinalIgnoreCase.GetHashCode(_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.Globalization;
using System.Threading;
using System.Xml;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.DocumentationComments
{
internal class VisualStudioDocumentationProvider : DocumentationProvider
{
private readonly string _filePath;
private readonly IVsXMLMemberIndexService _memberIndexService;
private readonly Lazy<IVsXMLMemberIndex> _lazyMemberIndex;
public VisualStudioDocumentationProvider(string filePath, IVsXMLMemberIndexService memberIndexService)
{
Contract.ThrowIfNull(memberIndexService);
Contract.ThrowIfNull(filePath);
_filePath = filePath;
_memberIndexService = memberIndexService;
_lazyMemberIndex = new Lazy<IVsXMLMemberIndex>(CreateXmlMemberIndex, isThreadSafe: true);
}
protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken token = default)
{
var memberIndex = _lazyMemberIndex.Value;
if (memberIndex == null)
{
return "";
}
if (ErrorHandler.Failed(memberIndex.ParseMemberSignature(documentationMemberID, out var methodID)))
{
return "";
}
if (ErrorHandler.Failed(memberIndex.GetMemberXML(methodID, out var xml)))
{
return "";
}
return xml;
}
private IVsXMLMemberIndex CreateXmlMemberIndex()
{
// This may fail if there is no XML file available for this assembly. We'll just leave
// memberIndex null in this case.
_memberIndexService.CreateXMLMemberIndex(_filePath, out var memberIndex);
return memberIndex;
}
public override bool Equals(object obj)
=> obj is VisualStudioDocumentationProvider other &&
string.Equals(_filePath, other._filePath, StringComparison.OrdinalIgnoreCase);
public override int GetHashCode()
=> StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Tools/AnalyzerRunner/Statistic.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 AnalyzerRunner
{
internal struct Statistic
{
public Statistic(int numberOfNodes, int numberOfTokens, int numberOfTrivia)
{
this.NumberofNodes = numberOfNodes;
this.NumberOfTokens = numberOfTokens;
this.NumberOfTrivia = numberOfTrivia;
}
public int NumberofNodes { get; }
public int NumberOfTokens { get; }
public int NumberOfTrivia { get; }
public static Statistic operator +(Statistic statistic1, Statistic statistic2)
{
return new Statistic(
statistic1.NumberofNodes + statistic2.NumberofNodes,
statistic1.NumberOfTokens + statistic2.NumberOfTokens,
statistic1.NumberOfTrivia + statistic2.NumberOfTrivia);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 AnalyzerRunner
{
internal struct Statistic
{
public Statistic(int numberOfNodes, int numberOfTokens, int numberOfTrivia)
{
this.NumberofNodes = numberOfNodes;
this.NumberOfTokens = numberOfTokens;
this.NumberOfTrivia = numberOfTrivia;
}
public int NumberofNodes { get; }
public int NumberOfTokens { get; }
public int NumberOfTrivia { get; }
public static Statistic operator +(Statistic statistic1, Statistic statistic2)
{
return new Statistic(
statistic1.NumberofNodes + statistic2.NumberofNodes,
statistic1.NumberOfTokens + statistic2.NumberOfTokens,
statistic1.NumberOfTrivia + statistic2.NumberOfTrivia);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./eng/config/app.manifest | <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="{generated}" name="{generated}"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly> | <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="{generated}" name="{generated}"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly> | -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/VisualStudio/Core/Def/Implementation/Snippets/SnippetFunctions/AbstractSnippetFunctionClassName.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetFunctionClassName : AbstractSnippetFunction
{
protected readonly string FieldName;
public AbstractSnippetFunctionClassName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName)
: base(snippetExpansionClient, subjectBuffer)
{
this.FieldName = fieldName;
}
protected abstract int GetContainingClassName(Document document, SnapshotSpan subjectBufferFieldSpan, CancellationToken cancellationToken, ref string value, ref int hasDefaultValue);
protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue)
{
hasDefaultValue = 0;
value = string.Empty;
if (!TryGetDocument(out var document))
{
return VSConstants.E_FAIL;
}
var surfaceBufferFieldSpan = new VsTextSpan[1];
if (snippetExpansionClient.ExpansionSession.GetFieldSpan(FieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
{
return VSConstants.E_FAIL;
}
if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan))
{
return VSConstants.E_FAIL;
}
return GetContainingClassName(document, subjectBufferFieldSpan, cancellationToken, ref value, ref hasDefaultValue);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetFunctionClassName : AbstractSnippetFunction
{
protected readonly string FieldName;
public AbstractSnippetFunctionClassName(AbstractSnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName)
: base(snippetExpansionClient, subjectBuffer)
{
this.FieldName = fieldName;
}
protected abstract int GetContainingClassName(Document document, SnapshotSpan subjectBufferFieldSpan, CancellationToken cancellationToken, ref string value, ref int hasDefaultValue);
protected override int GetDefaultValue(CancellationToken cancellationToken, out string value, out int hasDefaultValue)
{
hasDefaultValue = 0;
value = string.Empty;
if (!TryGetDocument(out var document))
{
return VSConstants.E_FAIL;
}
var surfaceBufferFieldSpan = new VsTextSpan[1];
if (snippetExpansionClient.ExpansionSession.GetFieldSpan(FieldName, surfaceBufferFieldSpan) != VSConstants.S_OK)
{
return VSConstants.E_FAIL;
}
if (!snippetExpansionClient.TryGetSubjectBufferSpan(surfaceBufferFieldSpan[0], out var subjectBufferFieldSpan))
{
return VSConstants.E_FAIL;
}
return GetContainingClassName(document, subjectBufferFieldSpan, cancellationToken, ref value, ref hasDefaultValue);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaSymbolMatchPriority.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Completion.Providers;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaSymbolMatchPriority
{
internal static readonly int Keyword = SymbolMatchPriority.Keyword;
internal static readonly int PreferType = SymbolMatchPriority.PreferType;
internal static readonly int PreferNamedArgument = SymbolMatchPriority.PreferNamedArgument;
internal static readonly int PreferEventOrMethod = SymbolMatchPriority.PreferEventOrMethod;
internal static readonly int PreferFieldOrProperty = SymbolMatchPriority.PreferFieldOrProperty;
internal static readonly int PreferLocalOrParameterOrRangeVariable = SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Completion.Providers;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaSymbolMatchPriority
{
internal static readonly int Keyword = SymbolMatchPriority.Keyword;
internal static readonly int PreferType = SymbolMatchPriority.PreferType;
internal static readonly int PreferNamedArgument = SymbolMatchPriority.PreferNamedArgument;
internal static readonly int PreferEventOrMethod = SymbolMatchPriority.PreferEventOrMethod;
internal static readonly int PreferFieldOrProperty = SymbolMatchPriority.PreferFieldOrProperty;
internal static readonly int PreferLocalOrParameterOrRangeVariable = SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable;
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/PickMembersDialog_InProc.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class PickMembersDialog_InProc : InProcComponent
{
private PickMembersDialog_InProc()
{
}
public static PickMembersDialog_InProc Create()
=> new PickMembersDialog_InProc();
public void VerifyOpen()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
var cancellationToken = cancellationTokenSource.Token;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken));
if (window is null)
{
// Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread
// message at lower priority than the Background priority used in testing.
WaitForApplicationIdle(Helper.HangMitigatingTimeout);
continue;
}
WaitForApplicationIdle(Helper.HangMitigatingTimeout);
return;
}
}
}
public void VerifyClosed()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
var cancellationToken = cancellationTokenSource.Token;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken));
if (window is null)
{
return;
}
Thread.Yield();
}
}
}
public bool CloseWindow()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null)
{
return false;
}
}
ClickCancel();
return true;
}
public void ClickOK()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token));
}
}
public void ClickCancel()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token));
}
}
public void ClickDown()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DownButton, cancellationTokenSource.Token));
}
}
private async Task<PickMembersDialog> GetDialogAsync(CancellationToken cancellationToken)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
return Application.Current.Windows.OfType<PickMembersDialog>().Single();
}
private async Task<PickMembersDialog> TryGetDialogAsync(CancellationToken cancellationToken)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
return Application.Current.Windows.OfType<PickMembersDialog>().SingleOrDefault();
}
private async Task ClickAsync(Func<PickMembersDialog.TestAccessor, ButtonBase> buttonSelector, CancellationToken cancellationToken)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
var dialog = await GetDialogAsync(cancellationToken);
var button = buttonSelector(dialog.GetTestAccessor());
Contract.ThrowIfFalse(await button.SimulateClickAsync(JoinableTaskFactory));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess
{
internal class PickMembersDialog_InProc : InProcComponent
{
private PickMembersDialog_InProc()
{
}
public static PickMembersDialog_InProc Create()
=> new PickMembersDialog_InProc();
public void VerifyOpen()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
var cancellationToken = cancellationTokenSource.Token;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken));
if (window is null)
{
// Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread
// message at lower priority than the Background priority used in testing.
WaitForApplicationIdle(Helper.HangMitigatingTimeout);
continue;
}
WaitForApplicationIdle(Helper.HangMitigatingTimeout);
return;
}
}
}
public void VerifyClosed()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
var cancellationToken = cancellationTokenSource.Token;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken));
if (window is null)
{
return;
}
Thread.Yield();
}
}
}
public bool CloseWindow()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null)
{
return false;
}
}
ClickCancel();
return true;
}
public void ClickOK()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token));
}
}
public void ClickCancel()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token));
}
}
public void ClickDown()
{
using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout))
{
JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.DownButton, cancellationTokenSource.Token));
}
}
private async Task<PickMembersDialog> GetDialogAsync(CancellationToken cancellationToken)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
return Application.Current.Windows.OfType<PickMembersDialog>().Single();
}
private async Task<PickMembersDialog> TryGetDialogAsync(CancellationToken cancellationToken)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
return Application.Current.Windows.OfType<PickMembersDialog>().SingleOrDefault();
}
private async Task ClickAsync(Func<PickMembersDialog.TestAccessor, ButtonBase> buttonSelector, CancellationToken cancellationToken)
{
await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
var dialog = await GetDialogAsync(cancellationToken);
var button = buttonSelector(dialog.GetTestAccessor());
Contract.ThrowIfFalse(await button.SimulateClickAsync(JoinableTaskFactory));
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./docs/compilers/Visual Basic/Compiler Breaking Changes - VS2019.md | **This document lists known breaking changes in Roslyn 3.0 (Visual Studio 2019) from Roslyn 2.* (Visual Studio 2017)
<!--
*Breaks are formatted with a monotonically increasing numbered list to allow them to referenced via shorthand (i.e., "known break #1").
Each entry should include a short description of the break, followed by either a link to the issue describing the full details of the break or the full details of the break inline.*
-->
1. Previously, reference assemblies were emitted including embedded resources. In Visual Studio 2019, embedded resources are no longer emitted into ref assemblies.
See https://github.com/dotnet/roslyn/issues/31197
| **This document lists known breaking changes in Roslyn 3.0 (Visual Studio 2019) from Roslyn 2.* (Visual Studio 2017)
<!--
*Breaks are formatted with a monotonically increasing numbered list to allow them to referenced via shorthand (i.e., "known break #1").
Each entry should include a short description of the break, followed by either a link to the issue describing the full details of the break or the full details of the break inline.*
-->
1. Previously, reference assemblies were emitted including embedded resources. In Visual Studio 2019, embedded resources are no longer emitted into ref assemblies.
See https://github.com/dotnet/roslyn/issues/31197
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Lsif/GeneratorTest/Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<StartupObject />
<TargetFramework>net472</TargetFramework>
<OutputType>Library</OutputType>
<RootNamespace></RootNamespace>
<RoslynProjectType>UnitTest</RoslynProjectType>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Workspaces\TestSourceGenerator\Microsoft.CodeAnalysis.TestSourceGenerator.csproj" />
<ProjectReference Include="..\Generator\Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj" />
<!-- Below is the transitive closure of the project references above to placate BuildBoss. If changes are made above this line,
please update the stuff here accordingly. -->
<ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" />
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" />
<ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" />
<ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" />
<ProjectReference Include="..\..\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" />
<ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
<ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Xunit.Combinatorial" Version="$(XunitCombinatorialVersion)" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.Utilities" />
<Import Include="System.Threading.Tasks" />
<Import Include="Xunit" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<StartupObject />
<TargetFramework>net472</TargetFramework>
<OutputType>Library</OutputType>
<RootNamespace></RootNamespace>
<RoslynProjectType>UnitTest</RoslynProjectType>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Workspaces\TestSourceGenerator\Microsoft.CodeAnalysis.TestSourceGenerator.csproj" />
<ProjectReference Include="..\Generator\Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.csproj" />
<!-- Below is the transitive closure of the project references above to placate BuildBoss. If changes are made above this line,
please update the stuff here accordingly. -->
<ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" />
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" />
<ProjectReference Include="..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" />
<ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" />
<ProjectReference Include="..\..\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" />
<ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
<ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Xunit.Combinatorial" Version="$(XunitCombinatorialVersion)" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests.Utilities" />
<Import Include="System.Threading.Tasks" />
<Import Include="Xunit" />
</ItemGroup>
</Project> | -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Dependencies/Microsoft.NetFX20/Readme.txt | Generated from mscorlib 2.0 using RefAsmGen:
refasmgen /contracts+ mscorlib.dll /o:Contracts\mscorlib.dll
and then clearing the CorFlags.Requires32Bit big in the COR header flag to change the architecture to AnyCPU.
Script to clear the flag:
#r "System.Reflection.Metadata.1.0.19-rc.nupkg"
using (var stream = new FileStream(args[0], FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var peReader = new PEReader(stream))
using (var writer = new BinaryWriter(stream))
{
const int OffsetFromStartOfCorHeaderToFlags =
sizeof(int) // byte count
+ sizeof(short) // major version
+ sizeof(short) // minor version
+ sizeof(long); // metadata directory
stream.Position = peReader.PEHeaders.CorHeaderStartOffset + OffsetFromStartOfCorHeaderToFlags;
var flags = peReader.PEHeaders.CorHeader.Flags;
Console.WriteLine($"Current flags: {flags}");
flags &= ~CorFlags.Requires32Bit;
Console.WriteLine($"New flags: {flags}");
writer.Write((uint)flags);
} | Generated from mscorlib 2.0 using RefAsmGen:
refasmgen /contracts+ mscorlib.dll /o:Contracts\mscorlib.dll
and then clearing the CorFlags.Requires32Bit big in the COR header flag to change the architecture to AnyCPU.
Script to clear the flag:
#r "System.Reflection.Metadata.1.0.19-rc.nupkg"
using (var stream = new FileStream(args[0], FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var peReader = new PEReader(stream))
using (var writer = new BinaryWriter(stream))
{
const int OffsetFromStartOfCorHeaderToFlags =
sizeof(int) // byte count
+ sizeof(short) // major version
+ sizeof(short) // minor version
+ sizeof(long); // metadata directory
stream.Position = peReader.PEHeaders.CorHeaderStartOffset + OffsetFromStartOfCorHeaderToFlags;
var flags = peReader.PEHeaders.CorHeader.Flags;
Console.WriteLine($"Current flags: {flags}");
flags &= ~CorFlags.Requires32Bit;
Console.WriteLine($"New flags: {flags}");
writer.Write((uint)flags);
} | -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Analyzers/VisualBasic/Analyzers/UseAutoProperty/Utilities.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty
Friend Module Utilities
Friend Function GetNodeToRemove(identifier As ModifiedIdentifierSyntax) As SyntaxNode
Dim declarator = DirectCast(identifier.Parent, VariableDeclaratorSyntax)
If declarator.Names.Count > 1 Then
' more than one name in this declarator group. just remove this name.
Return identifier
End If
' only name in this declarator group. if our field has multiple declarator groups,
' just remove this one. otherwise remove the field entirely.
Dim field = DirectCast(declarator.Parent, FieldDeclarationSyntax)
If field.Declarators.Count > 1 Then
Return declarator
End If
Return field
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseAutoProperty
Friend Module Utilities
Friend Function GetNodeToRemove(identifier As ModifiedIdentifierSyntax) As SyntaxNode
Dim declarator = DirectCast(identifier.Parent, VariableDeclaratorSyntax)
If declarator.Names.Count > 1 Then
' more than one name in this declarator group. just remove this name.
Return identifier
End If
' only name in this declarator group. if our field has multiple declarator groups,
' just remove this one. otherwise remove the field entirely.
Dim field = DirectCast(declarator.Parent, FieldDeclarationSyntax)
If field.Declarators.Count > 1 Then
Return declarator
End If
Return field
End Function
End Module
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/SymbolSpecification.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal sealed class SymbolSpecification : IEquatable<SymbolSpecification>, IObjectWritable
{
private static readonly SymbolSpecification DefaultSymbolSpecificationTemplate = CreateDefaultSymbolSpecification();
public Guid ID { get; }
public string Name { get; }
public ImmutableArray<SymbolKindOrTypeKind> ApplicableSymbolKindList { get; }
public ImmutableArray<Accessibility> ApplicableAccessibilityList { get; }
public ImmutableArray<ModifierKind> RequiredModifierList { get; }
public SymbolSpecification(
Guid? id, string symbolSpecName,
ImmutableArray<SymbolKindOrTypeKind> symbolKindList,
ImmutableArray<Accessibility> accessibilityList = default,
ImmutableArray<ModifierKind> modifiers = default)
{
ID = id ?? Guid.NewGuid();
Name = symbolSpecName;
ApplicableSymbolKindList = symbolKindList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableSymbolKindList : symbolKindList;
ApplicableAccessibilityList = accessibilityList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableAccessibilityList : accessibilityList;
RequiredModifierList = modifiers.IsDefault ? DefaultSymbolSpecificationTemplate.RequiredModifierList : modifiers;
}
public static SymbolSpecification CreateDefaultSymbolSpecification()
{
// This is used to create new, empty symbol specifications for users to then customize.
// Since these customized specifications will eventually coexist with all the other
// existing specifications, always use a new, distinct guid.
return new SymbolSpecification(
id: Guid.NewGuid(),
symbolSpecName: null,
symbolKindList: ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Namespace),
new SymbolKindOrTypeKind(TypeKind.Class),
new SymbolKindOrTypeKind(TypeKind.Struct),
new SymbolKindOrTypeKind(TypeKind.Interface),
new SymbolKindOrTypeKind(TypeKind.Delegate),
new SymbolKindOrTypeKind(TypeKind.Enum),
new SymbolKindOrTypeKind(TypeKind.Module),
new SymbolKindOrTypeKind(TypeKind.Pointer),
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(MethodKind.LocalFunction),
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Event),
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(TypeKind.TypeParameter),
new SymbolKindOrTypeKind(SymbolKind.Local)),
accessibilityList: ImmutableArray.Create(
Accessibility.NotApplicable,
Accessibility.Public,
Accessibility.Internal,
Accessibility.Private,
Accessibility.Protected,
Accessibility.ProtectedAndInternal,
Accessibility.ProtectedOrInternal),
modifiers: ImmutableArray<ModifierKind>.Empty);
}
public bool AppliesTo(ISymbol symbol)
=> AnyMatches(this.ApplicableSymbolKindList, symbol) &&
AllMatches(this.RequiredModifierList, symbol) &&
AnyMatches(this.ApplicableAccessibilityList, symbol);
public bool AppliesTo(SymbolKind symbolKind, Accessibility accessibility)
=> this.AppliesTo(new SymbolKindOrTypeKind(symbolKind), new DeclarationModifiers(), accessibility);
public bool AppliesTo(SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility)
{
if (!ApplicableSymbolKindList.Any(k => k.Equals(kind)))
{
return false;
}
var collapsedModifiers = CollapseModifiers(RequiredModifierList);
if ((modifiers & collapsedModifiers) != collapsedModifiers)
{
return false;
}
if (accessibility.HasValue && !ApplicableAccessibilityList.Any(k => k == accessibility))
{
return false;
}
return true;
}
private static DeclarationModifiers CollapseModifiers(ImmutableArray<ModifierKind> requiredModifierList)
{
if (requiredModifierList == default)
{
return new DeclarationModifiers();
}
var result = new DeclarationModifiers();
foreach (var modifier in requiredModifierList)
{
switch (modifier.ModifierKindWrapper)
{
case ModifierKindEnum.IsAbstract:
result = result.WithIsAbstract(true);
break;
case ModifierKindEnum.IsStatic:
result = result.WithIsStatic(true);
break;
case ModifierKindEnum.IsAsync:
result = result.WithAsync(true);
break;
case ModifierKindEnum.IsReadOnly:
result = result.WithIsReadOnly(true);
break;
case ModifierKindEnum.IsConst:
result = result.WithIsConst(true);
break;
}
}
return result;
}
private static bool AnyMatches<TSymbolMatcher>(ImmutableArray<TSymbolMatcher> matchers, ISymbol symbol)
where TSymbolMatcher : ISymbolMatcher
{
foreach (var matcher in matchers)
{
if (matcher.MatchesSymbol(symbol))
{
return true;
}
}
return false;
}
private static bool AnyMatches(ImmutableArray<Accessibility> matchers, ISymbol symbol)
{
foreach (var matcher in matchers)
{
if (matcher.MatchesSymbol(symbol))
{
return true;
}
}
return false;
}
private static bool AllMatches<TSymbolMatcher>(ImmutableArray<TSymbolMatcher> matchers, ISymbol symbol)
where TSymbolMatcher : ISymbolMatcher
{
foreach (var matcher in matchers)
{
if (!matcher.MatchesSymbol(symbol))
{
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
return Equals(obj as SymbolSpecification);
}
public bool Equals(SymbolSpecification other)
{
if (other is null)
return false;
return ID == other.ID
&& Name == other.Name
&& ApplicableSymbolKindList.SequenceEqual(other.ApplicableSymbolKindList)
&& ApplicableAccessibilityList.SequenceEqual(other.ApplicableAccessibilityList)
&& RequiredModifierList.SequenceEqual(other.RequiredModifierList);
}
public override int GetHashCode()
{
return Hash.Combine(ID.GetHashCode(),
Hash.Combine(Name.GetHashCode(),
Hash.Combine(Hash.CombineValues(ApplicableSymbolKindList),
Hash.Combine(Hash.CombineValues(ApplicableAccessibilityList),
Hash.CombineValues(RequiredModifierList)))));
}
internal XElement CreateXElement()
{
return new XElement(nameof(SymbolSpecification),
new XAttribute(nameof(ID), ID),
new XAttribute(nameof(Name), Name),
CreateSymbolKindsXElement(),
CreateAccessibilitiesXElement(),
CreateModifiersXElement());
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteGuid(ID);
writer.WriteString(Name);
writer.WriteArray(ApplicableSymbolKindList, (w, v) => v.WriteTo(w));
writer.WriteArray(ApplicableAccessibilityList, (w, v) => w.WriteInt32((int)v));
writer.WriteArray(RequiredModifierList, (w, v) => v.WriteTo(w));
}
public static SymbolSpecification ReadFrom(ObjectReader reader)
{
return new SymbolSpecification(
reader.ReadGuid(),
reader.ReadString(),
reader.ReadArray(r => SymbolKindOrTypeKind.ReadFrom(r)),
reader.ReadArray(r => (Accessibility)r.ReadInt32()),
reader.ReadArray(r => ModifierKind.ReadFrom(r)));
}
private XElement CreateSymbolKindsXElement()
{
var symbolKindsElement = new XElement(nameof(ApplicableSymbolKindList));
foreach (var symbolKind in ApplicableSymbolKindList)
{
symbolKindsElement.Add(symbolKind.CreateXElement());
}
return symbolKindsElement;
}
private XElement CreateAccessibilitiesXElement()
{
var accessibilitiesElement = new XElement(nameof(ApplicableAccessibilityList));
foreach (var accessibility in ApplicableAccessibilityList)
{
accessibilitiesElement.Add(accessibility.CreateXElement());
}
return accessibilitiesElement;
}
private XElement CreateModifiersXElement()
{
var modifiersElement = new XElement(nameof(RequiredModifierList));
foreach (var modifier in RequiredModifierList)
{
modifiersElement.Add(modifier.CreateXElement());
}
return modifiersElement;
}
internal static SymbolSpecification FromXElement(XElement symbolSpecificationElement)
=> new(
id: Guid.Parse(symbolSpecificationElement.Attribute(nameof(ID)).Value),
symbolSpecName: symbolSpecificationElement.Attribute(nameof(Name)).Value,
symbolKindList: GetSymbolKindListFromXElement(symbolSpecificationElement.Element(nameof(ApplicableSymbolKindList))),
accessibilityList: GetAccessibilityListFromXElement(symbolSpecificationElement.Element(nameof(ApplicableAccessibilityList))),
modifiers: GetModifierListFromXElement(symbolSpecificationElement.Element(nameof(RequiredModifierList))));
private static ImmutableArray<SymbolKindOrTypeKind> GetSymbolKindListFromXElement(XElement symbolKindListElement)
{
var applicableSymbolKindList = ArrayBuilder<SymbolKindOrTypeKind>.GetInstance();
foreach (var symbolKindElement in symbolKindListElement.Elements(nameof(SymbolKind)))
{
applicableSymbolKindList.Add(SymbolKindOrTypeKind.AddSymbolKindFromXElement(symbolKindElement));
}
foreach (var typeKindElement in symbolKindListElement.Elements(nameof(TypeKind)))
{
applicableSymbolKindList.Add(SymbolKindOrTypeKind.AddTypeKindFromXElement(typeKindElement));
}
foreach (var methodKindElement in symbolKindListElement.Elements(nameof(MethodKind)))
{
applicableSymbolKindList.Add(SymbolKindOrTypeKind.AddMethodKindFromXElement(methodKindElement));
}
return applicableSymbolKindList.ToImmutableAndFree();
}
private static ImmutableArray<Accessibility> GetAccessibilityListFromXElement(XElement accessibilityListElement)
{
var applicableAccessibilityList = ArrayBuilder<Accessibility>.GetInstance();
foreach (var accessibilityElement in accessibilityListElement.Elements("AccessibilityKind"))
{
applicableAccessibilityList.Add(AccessibilityExtensions.FromXElement(accessibilityElement));
}
return applicableAccessibilityList.ToImmutableAndFree();
}
private static ImmutableArray<ModifierKind> GetModifierListFromXElement(XElement modifierListElement)
{
var result = ArrayBuilder<ModifierKind>.GetInstance();
foreach (var modifierElement in modifierListElement.Elements(nameof(ModifierKind)))
{
result.Add(ModifierKind.FromXElement(modifierElement));
}
return result.ToImmutableAndFree();
}
private interface ISymbolMatcher
{
bool MatchesSymbol(ISymbol symbol);
}
public struct SymbolKindOrTypeKind : IEquatable<SymbolKindOrTypeKind>, ISymbolMatcher, IObjectWritable
{
public SymbolKind? SymbolKind { get; }
public TypeKind? TypeKind { get; }
public MethodKind? MethodKind { get; }
public SymbolKindOrTypeKind(SymbolKind symbolKind) : this()
{
SymbolKind = symbolKind;
TypeKind = null;
MethodKind = null;
}
public SymbolKindOrTypeKind(TypeKind typeKind) : this()
{
SymbolKind = null;
TypeKind = typeKind;
MethodKind = null;
}
public SymbolKindOrTypeKind(MethodKind methodKind) : this()
{
SymbolKind = null;
TypeKind = null;
MethodKind = methodKind;
}
public bool MatchesSymbol(ISymbol symbol)
=> SymbolKind.HasValue ? symbol.IsKind(SymbolKind.Value) :
TypeKind.HasValue ? symbol is ITypeSymbol type && type.TypeKind == TypeKind.Value :
MethodKind.HasValue ? symbol is IMethodSymbol method && method.MethodKind == MethodKind.Value :
throw ExceptionUtilities.Unreachable;
internal XElement CreateXElement()
=> SymbolKind.HasValue ? new XElement(nameof(SymbolKind), SymbolKind) :
TypeKind.HasValue ? new XElement(nameof(TypeKind), GetTypeKindString(TypeKind.Value)) :
MethodKind.HasValue ? new XElement(nameof(MethodKind), GetMethodKindString(MethodKind.Value)) :
throw ExceptionUtilities.Unreachable;
private static string GetTypeKindString(TypeKind typeKind)
{
// We have two members in TypeKind that point to the same value, Struct and Structure. Because of this,
// Enum.ToString(), which under the covers uses a binary search, isn't stable which one it will pick and it can
// change if other TypeKinds are added. This ensures we keep using the same string consistently.
return typeKind switch
{
CodeAnalysis.TypeKind.Structure => nameof(CodeAnalysis.TypeKind.Struct),
_ => typeKind.ToString()
};
}
private static string GetMethodKindString(MethodKind methodKind)
{
// We ehave some members in TypeKind that point to the same value. Because of this,
// Enum.ToString(), which under the covers uses a binary search, isn't stable which one it will pick and it can
// change if other MethodKinds are added. This ensures we keep using the same string consistently.
return methodKind switch
{
CodeAnalysis.MethodKind.SharedConstructor => nameof(CodeAnalysis.MethodKind.StaticConstructor),
CodeAnalysis.MethodKind.AnonymousFunction => nameof(CodeAnalysis.MethodKind.LambdaMethod),
_ => methodKind.ToString()
};
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
if (SymbolKind != null)
{
writer.WriteInt32(1);
writer.WriteInt32((int)SymbolKind);
}
else if (TypeKind != null)
{
writer.WriteInt32(2);
writer.WriteInt32((int)TypeKind);
}
else if (MethodKind != null)
{
writer.WriteInt32(3);
writer.WriteInt32((int)MethodKind);
}
else
{
writer.WriteInt32(0);
}
}
public static SymbolKindOrTypeKind ReadFrom(ObjectReader reader)
{
return reader.ReadInt32() switch
{
0 => default,
1 => new SymbolKindOrTypeKind((SymbolKind)reader.ReadInt32()),
2 => new SymbolKindOrTypeKind((TypeKind)reader.ReadInt32()),
3 => new SymbolKindOrTypeKind((MethodKind)reader.ReadInt32()),
var v => throw ExceptionUtilities.UnexpectedValue(v),
};
}
internal static SymbolKindOrTypeKind AddSymbolKindFromXElement(XElement symbolKindElement)
=> new((SymbolKind)Enum.Parse(typeof(SymbolKind), symbolKindElement.Value));
internal static SymbolKindOrTypeKind AddTypeKindFromXElement(XElement typeKindElement)
=> new((TypeKind)Enum.Parse(typeof(TypeKind), typeKindElement.Value));
internal static SymbolKindOrTypeKind AddMethodKindFromXElement(XElement methodKindElement)
=> new((MethodKind)Enum.Parse(typeof(MethodKind), methodKindElement.Value));
public override bool Equals(object obj)
=> Equals((SymbolKindOrTypeKind)obj);
public bool Equals(SymbolKindOrTypeKind other)
=> this.SymbolKind == other.SymbolKind && this.TypeKind == other.TypeKind && this.MethodKind == other.MethodKind;
public override int GetHashCode()
{
return Hash.Combine((int)SymbolKind.GetValueOrDefault(),
Hash.Combine((int)TypeKind.GetValueOrDefault(), (int)MethodKind.GetValueOrDefault()));
}
}
public struct ModifierKind : ISymbolMatcher, IEquatable<ModifierKind>, IObjectWritable
{
public ModifierKindEnum ModifierKindWrapper;
internal DeclarationModifiers Modifier { get; }
public ModifierKind(DeclarationModifiers modifier) : this()
{
this.Modifier = modifier;
if (modifier.IsAbstract)
{
ModifierKindWrapper = ModifierKindEnum.IsAbstract;
}
else if (modifier.IsStatic)
{
ModifierKindWrapper = ModifierKindEnum.IsStatic;
}
else if (modifier.IsAsync)
{
ModifierKindWrapper = ModifierKindEnum.IsAsync;
}
else if (modifier.IsReadOnly)
{
ModifierKindWrapper = ModifierKindEnum.IsReadOnly;
}
else if (modifier.IsConst)
{
ModifierKindWrapper = ModifierKindEnum.IsConst;
}
else
{
throw new InvalidOperationException();
}
}
public ModifierKind(ModifierKindEnum modifierKind) : this()
{
ModifierKindWrapper = modifierKind;
Modifier = new DeclarationModifiers(
isAbstract: ModifierKindWrapper == ModifierKindEnum.IsAbstract,
isStatic: ModifierKindWrapper == ModifierKindEnum.IsStatic,
isAsync: ModifierKindWrapper == ModifierKindEnum.IsAsync,
isReadOnly: ModifierKindWrapper == ModifierKindEnum.IsReadOnly,
isConst: ModifierKindWrapper == ModifierKindEnum.IsConst);
}
public bool MatchesSymbol(ISymbol symbol)
{
if ((Modifier.IsAbstract && symbol.IsAbstract) ||
(Modifier.IsStatic && symbol.IsStatic))
{
return true;
}
var kind = symbol.Kind;
if (Modifier.IsAsync && kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsAsync)
{
return true;
}
if (Modifier.IsReadOnly)
{
if (kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsReadOnly)
{
return true;
}
}
if (Modifier.IsConst)
{
if ((kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsConst) ||
(kind == SymbolKind.Local && ((ILocalSymbol)symbol).IsConst))
{
return true;
}
}
return false;
}
internal XElement CreateXElement()
=> new(nameof(ModifierKind), ModifierKindWrapper);
internal static ModifierKind FromXElement(XElement modifierElement)
=> new((ModifierKindEnum)Enum.Parse(typeof(ModifierKindEnum), modifierElement.Value));
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
=> writer.WriteInt32((int)ModifierKindWrapper);
public static ModifierKind ReadFrom(ObjectReader reader)
=> new((ModifierKindEnum)reader.ReadInt32());
public override bool Equals(object obj)
=> obj is ModifierKind kind && Equals(kind);
public override int GetHashCode()
=> (int)ModifierKindWrapper;
public bool Equals(ModifierKind other)
=> ModifierKindWrapper == other.ModifierKindWrapper;
}
public enum ModifierKindEnum
{
IsAbstract,
IsStatic,
IsAsync,
IsReadOnly,
IsConst,
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal sealed class SymbolSpecification : IEquatable<SymbolSpecification>, IObjectWritable
{
private static readonly SymbolSpecification DefaultSymbolSpecificationTemplate = CreateDefaultSymbolSpecification();
public Guid ID { get; }
public string Name { get; }
public ImmutableArray<SymbolKindOrTypeKind> ApplicableSymbolKindList { get; }
public ImmutableArray<Accessibility> ApplicableAccessibilityList { get; }
public ImmutableArray<ModifierKind> RequiredModifierList { get; }
public SymbolSpecification(
Guid? id, string symbolSpecName,
ImmutableArray<SymbolKindOrTypeKind> symbolKindList,
ImmutableArray<Accessibility> accessibilityList = default,
ImmutableArray<ModifierKind> modifiers = default)
{
ID = id ?? Guid.NewGuid();
Name = symbolSpecName;
ApplicableSymbolKindList = symbolKindList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableSymbolKindList : symbolKindList;
ApplicableAccessibilityList = accessibilityList.IsDefault ? DefaultSymbolSpecificationTemplate.ApplicableAccessibilityList : accessibilityList;
RequiredModifierList = modifiers.IsDefault ? DefaultSymbolSpecificationTemplate.RequiredModifierList : modifiers;
}
public static SymbolSpecification CreateDefaultSymbolSpecification()
{
// This is used to create new, empty symbol specifications for users to then customize.
// Since these customized specifications will eventually coexist with all the other
// existing specifications, always use a new, distinct guid.
return new SymbolSpecification(
id: Guid.NewGuid(),
symbolSpecName: null,
symbolKindList: ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Namespace),
new SymbolKindOrTypeKind(TypeKind.Class),
new SymbolKindOrTypeKind(TypeKind.Struct),
new SymbolKindOrTypeKind(TypeKind.Interface),
new SymbolKindOrTypeKind(TypeKind.Delegate),
new SymbolKindOrTypeKind(TypeKind.Enum),
new SymbolKindOrTypeKind(TypeKind.Module),
new SymbolKindOrTypeKind(TypeKind.Pointer),
new SymbolKindOrTypeKind(SymbolKind.Property),
new SymbolKindOrTypeKind(MethodKind.Ordinary),
new SymbolKindOrTypeKind(MethodKind.LocalFunction),
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Event),
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(TypeKind.TypeParameter),
new SymbolKindOrTypeKind(SymbolKind.Local)),
accessibilityList: ImmutableArray.Create(
Accessibility.NotApplicable,
Accessibility.Public,
Accessibility.Internal,
Accessibility.Private,
Accessibility.Protected,
Accessibility.ProtectedAndInternal,
Accessibility.ProtectedOrInternal),
modifiers: ImmutableArray<ModifierKind>.Empty);
}
public bool AppliesTo(ISymbol symbol)
=> AnyMatches(this.ApplicableSymbolKindList, symbol) &&
AllMatches(this.RequiredModifierList, symbol) &&
AnyMatches(this.ApplicableAccessibilityList, symbol);
public bool AppliesTo(SymbolKind symbolKind, Accessibility accessibility)
=> this.AppliesTo(new SymbolKindOrTypeKind(symbolKind), new DeclarationModifiers(), accessibility);
public bool AppliesTo(SymbolKindOrTypeKind kind, DeclarationModifiers modifiers, Accessibility? accessibility)
{
if (!ApplicableSymbolKindList.Any(k => k.Equals(kind)))
{
return false;
}
var collapsedModifiers = CollapseModifiers(RequiredModifierList);
if ((modifiers & collapsedModifiers) != collapsedModifiers)
{
return false;
}
if (accessibility.HasValue && !ApplicableAccessibilityList.Any(k => k == accessibility))
{
return false;
}
return true;
}
private static DeclarationModifiers CollapseModifiers(ImmutableArray<ModifierKind> requiredModifierList)
{
if (requiredModifierList == default)
{
return new DeclarationModifiers();
}
var result = new DeclarationModifiers();
foreach (var modifier in requiredModifierList)
{
switch (modifier.ModifierKindWrapper)
{
case ModifierKindEnum.IsAbstract:
result = result.WithIsAbstract(true);
break;
case ModifierKindEnum.IsStatic:
result = result.WithIsStatic(true);
break;
case ModifierKindEnum.IsAsync:
result = result.WithAsync(true);
break;
case ModifierKindEnum.IsReadOnly:
result = result.WithIsReadOnly(true);
break;
case ModifierKindEnum.IsConst:
result = result.WithIsConst(true);
break;
}
}
return result;
}
private static bool AnyMatches<TSymbolMatcher>(ImmutableArray<TSymbolMatcher> matchers, ISymbol symbol)
where TSymbolMatcher : ISymbolMatcher
{
foreach (var matcher in matchers)
{
if (matcher.MatchesSymbol(symbol))
{
return true;
}
}
return false;
}
private static bool AnyMatches(ImmutableArray<Accessibility> matchers, ISymbol symbol)
{
foreach (var matcher in matchers)
{
if (matcher.MatchesSymbol(symbol))
{
return true;
}
}
return false;
}
private static bool AllMatches<TSymbolMatcher>(ImmutableArray<TSymbolMatcher> matchers, ISymbol symbol)
where TSymbolMatcher : ISymbolMatcher
{
foreach (var matcher in matchers)
{
if (!matcher.MatchesSymbol(symbol))
{
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
return Equals(obj as SymbolSpecification);
}
public bool Equals(SymbolSpecification other)
{
if (other is null)
return false;
return ID == other.ID
&& Name == other.Name
&& ApplicableSymbolKindList.SequenceEqual(other.ApplicableSymbolKindList)
&& ApplicableAccessibilityList.SequenceEqual(other.ApplicableAccessibilityList)
&& RequiredModifierList.SequenceEqual(other.RequiredModifierList);
}
public override int GetHashCode()
{
return Hash.Combine(ID.GetHashCode(),
Hash.Combine(Name.GetHashCode(),
Hash.Combine(Hash.CombineValues(ApplicableSymbolKindList),
Hash.Combine(Hash.CombineValues(ApplicableAccessibilityList),
Hash.CombineValues(RequiredModifierList)))));
}
internal XElement CreateXElement()
{
return new XElement(nameof(SymbolSpecification),
new XAttribute(nameof(ID), ID),
new XAttribute(nameof(Name), Name),
CreateSymbolKindsXElement(),
CreateAccessibilitiesXElement(),
CreateModifiersXElement());
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteGuid(ID);
writer.WriteString(Name);
writer.WriteArray(ApplicableSymbolKindList, (w, v) => v.WriteTo(w));
writer.WriteArray(ApplicableAccessibilityList, (w, v) => w.WriteInt32((int)v));
writer.WriteArray(RequiredModifierList, (w, v) => v.WriteTo(w));
}
public static SymbolSpecification ReadFrom(ObjectReader reader)
{
return new SymbolSpecification(
reader.ReadGuid(),
reader.ReadString(),
reader.ReadArray(r => SymbolKindOrTypeKind.ReadFrom(r)),
reader.ReadArray(r => (Accessibility)r.ReadInt32()),
reader.ReadArray(r => ModifierKind.ReadFrom(r)));
}
private XElement CreateSymbolKindsXElement()
{
var symbolKindsElement = new XElement(nameof(ApplicableSymbolKindList));
foreach (var symbolKind in ApplicableSymbolKindList)
{
symbolKindsElement.Add(symbolKind.CreateXElement());
}
return symbolKindsElement;
}
private XElement CreateAccessibilitiesXElement()
{
var accessibilitiesElement = new XElement(nameof(ApplicableAccessibilityList));
foreach (var accessibility in ApplicableAccessibilityList)
{
accessibilitiesElement.Add(accessibility.CreateXElement());
}
return accessibilitiesElement;
}
private XElement CreateModifiersXElement()
{
var modifiersElement = new XElement(nameof(RequiredModifierList));
foreach (var modifier in RequiredModifierList)
{
modifiersElement.Add(modifier.CreateXElement());
}
return modifiersElement;
}
internal static SymbolSpecification FromXElement(XElement symbolSpecificationElement)
=> new(
id: Guid.Parse(symbolSpecificationElement.Attribute(nameof(ID)).Value),
symbolSpecName: symbolSpecificationElement.Attribute(nameof(Name)).Value,
symbolKindList: GetSymbolKindListFromXElement(symbolSpecificationElement.Element(nameof(ApplicableSymbolKindList))),
accessibilityList: GetAccessibilityListFromXElement(symbolSpecificationElement.Element(nameof(ApplicableAccessibilityList))),
modifiers: GetModifierListFromXElement(symbolSpecificationElement.Element(nameof(RequiredModifierList))));
private static ImmutableArray<SymbolKindOrTypeKind> GetSymbolKindListFromXElement(XElement symbolKindListElement)
{
var applicableSymbolKindList = ArrayBuilder<SymbolKindOrTypeKind>.GetInstance();
foreach (var symbolKindElement in symbolKindListElement.Elements(nameof(SymbolKind)))
{
applicableSymbolKindList.Add(SymbolKindOrTypeKind.AddSymbolKindFromXElement(symbolKindElement));
}
foreach (var typeKindElement in symbolKindListElement.Elements(nameof(TypeKind)))
{
applicableSymbolKindList.Add(SymbolKindOrTypeKind.AddTypeKindFromXElement(typeKindElement));
}
foreach (var methodKindElement in symbolKindListElement.Elements(nameof(MethodKind)))
{
applicableSymbolKindList.Add(SymbolKindOrTypeKind.AddMethodKindFromXElement(methodKindElement));
}
return applicableSymbolKindList.ToImmutableAndFree();
}
private static ImmutableArray<Accessibility> GetAccessibilityListFromXElement(XElement accessibilityListElement)
{
var applicableAccessibilityList = ArrayBuilder<Accessibility>.GetInstance();
foreach (var accessibilityElement in accessibilityListElement.Elements("AccessibilityKind"))
{
applicableAccessibilityList.Add(AccessibilityExtensions.FromXElement(accessibilityElement));
}
return applicableAccessibilityList.ToImmutableAndFree();
}
private static ImmutableArray<ModifierKind> GetModifierListFromXElement(XElement modifierListElement)
{
var result = ArrayBuilder<ModifierKind>.GetInstance();
foreach (var modifierElement in modifierListElement.Elements(nameof(ModifierKind)))
{
result.Add(ModifierKind.FromXElement(modifierElement));
}
return result.ToImmutableAndFree();
}
private interface ISymbolMatcher
{
bool MatchesSymbol(ISymbol symbol);
}
public struct SymbolKindOrTypeKind : IEquatable<SymbolKindOrTypeKind>, ISymbolMatcher, IObjectWritable
{
public SymbolKind? SymbolKind { get; }
public TypeKind? TypeKind { get; }
public MethodKind? MethodKind { get; }
public SymbolKindOrTypeKind(SymbolKind symbolKind) : this()
{
SymbolKind = symbolKind;
TypeKind = null;
MethodKind = null;
}
public SymbolKindOrTypeKind(TypeKind typeKind) : this()
{
SymbolKind = null;
TypeKind = typeKind;
MethodKind = null;
}
public SymbolKindOrTypeKind(MethodKind methodKind) : this()
{
SymbolKind = null;
TypeKind = null;
MethodKind = methodKind;
}
public bool MatchesSymbol(ISymbol symbol)
=> SymbolKind.HasValue ? symbol.IsKind(SymbolKind.Value) :
TypeKind.HasValue ? symbol is ITypeSymbol type && type.TypeKind == TypeKind.Value :
MethodKind.HasValue ? symbol is IMethodSymbol method && method.MethodKind == MethodKind.Value :
throw ExceptionUtilities.Unreachable;
internal XElement CreateXElement()
=> SymbolKind.HasValue ? new XElement(nameof(SymbolKind), SymbolKind) :
TypeKind.HasValue ? new XElement(nameof(TypeKind), GetTypeKindString(TypeKind.Value)) :
MethodKind.HasValue ? new XElement(nameof(MethodKind), GetMethodKindString(MethodKind.Value)) :
throw ExceptionUtilities.Unreachable;
private static string GetTypeKindString(TypeKind typeKind)
{
// We have two members in TypeKind that point to the same value, Struct and Structure. Because of this,
// Enum.ToString(), which under the covers uses a binary search, isn't stable which one it will pick and it can
// change if other TypeKinds are added. This ensures we keep using the same string consistently.
return typeKind switch
{
CodeAnalysis.TypeKind.Structure => nameof(CodeAnalysis.TypeKind.Struct),
_ => typeKind.ToString()
};
}
private static string GetMethodKindString(MethodKind methodKind)
{
// We ehave some members in TypeKind that point to the same value. Because of this,
// Enum.ToString(), which under the covers uses a binary search, isn't stable which one it will pick and it can
// change if other MethodKinds are added. This ensures we keep using the same string consistently.
return methodKind switch
{
CodeAnalysis.MethodKind.SharedConstructor => nameof(CodeAnalysis.MethodKind.StaticConstructor),
CodeAnalysis.MethodKind.AnonymousFunction => nameof(CodeAnalysis.MethodKind.LambdaMethod),
_ => methodKind.ToString()
};
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
if (SymbolKind != null)
{
writer.WriteInt32(1);
writer.WriteInt32((int)SymbolKind);
}
else if (TypeKind != null)
{
writer.WriteInt32(2);
writer.WriteInt32((int)TypeKind);
}
else if (MethodKind != null)
{
writer.WriteInt32(3);
writer.WriteInt32((int)MethodKind);
}
else
{
writer.WriteInt32(0);
}
}
public static SymbolKindOrTypeKind ReadFrom(ObjectReader reader)
{
return reader.ReadInt32() switch
{
0 => default,
1 => new SymbolKindOrTypeKind((SymbolKind)reader.ReadInt32()),
2 => new SymbolKindOrTypeKind((TypeKind)reader.ReadInt32()),
3 => new SymbolKindOrTypeKind((MethodKind)reader.ReadInt32()),
var v => throw ExceptionUtilities.UnexpectedValue(v),
};
}
internal static SymbolKindOrTypeKind AddSymbolKindFromXElement(XElement symbolKindElement)
=> new((SymbolKind)Enum.Parse(typeof(SymbolKind), symbolKindElement.Value));
internal static SymbolKindOrTypeKind AddTypeKindFromXElement(XElement typeKindElement)
=> new((TypeKind)Enum.Parse(typeof(TypeKind), typeKindElement.Value));
internal static SymbolKindOrTypeKind AddMethodKindFromXElement(XElement methodKindElement)
=> new((MethodKind)Enum.Parse(typeof(MethodKind), methodKindElement.Value));
public override bool Equals(object obj)
=> Equals((SymbolKindOrTypeKind)obj);
public bool Equals(SymbolKindOrTypeKind other)
=> this.SymbolKind == other.SymbolKind && this.TypeKind == other.TypeKind && this.MethodKind == other.MethodKind;
public override int GetHashCode()
{
return Hash.Combine((int)SymbolKind.GetValueOrDefault(),
Hash.Combine((int)TypeKind.GetValueOrDefault(), (int)MethodKind.GetValueOrDefault()));
}
}
public struct ModifierKind : ISymbolMatcher, IEquatable<ModifierKind>, IObjectWritable
{
public ModifierKindEnum ModifierKindWrapper;
internal DeclarationModifiers Modifier { get; }
public ModifierKind(DeclarationModifiers modifier) : this()
{
this.Modifier = modifier;
if (modifier.IsAbstract)
{
ModifierKindWrapper = ModifierKindEnum.IsAbstract;
}
else if (modifier.IsStatic)
{
ModifierKindWrapper = ModifierKindEnum.IsStatic;
}
else if (modifier.IsAsync)
{
ModifierKindWrapper = ModifierKindEnum.IsAsync;
}
else if (modifier.IsReadOnly)
{
ModifierKindWrapper = ModifierKindEnum.IsReadOnly;
}
else if (modifier.IsConst)
{
ModifierKindWrapper = ModifierKindEnum.IsConst;
}
else
{
throw new InvalidOperationException();
}
}
public ModifierKind(ModifierKindEnum modifierKind) : this()
{
ModifierKindWrapper = modifierKind;
Modifier = new DeclarationModifiers(
isAbstract: ModifierKindWrapper == ModifierKindEnum.IsAbstract,
isStatic: ModifierKindWrapper == ModifierKindEnum.IsStatic,
isAsync: ModifierKindWrapper == ModifierKindEnum.IsAsync,
isReadOnly: ModifierKindWrapper == ModifierKindEnum.IsReadOnly,
isConst: ModifierKindWrapper == ModifierKindEnum.IsConst);
}
public bool MatchesSymbol(ISymbol symbol)
{
if ((Modifier.IsAbstract && symbol.IsAbstract) ||
(Modifier.IsStatic && symbol.IsStatic))
{
return true;
}
var kind = symbol.Kind;
if (Modifier.IsAsync && kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsAsync)
{
return true;
}
if (Modifier.IsReadOnly)
{
if (kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsReadOnly)
{
return true;
}
}
if (Modifier.IsConst)
{
if ((kind == SymbolKind.Field && ((IFieldSymbol)symbol).IsConst) ||
(kind == SymbolKind.Local && ((ILocalSymbol)symbol).IsConst))
{
return true;
}
}
return false;
}
internal XElement CreateXElement()
=> new(nameof(ModifierKind), ModifierKindWrapper);
internal static ModifierKind FromXElement(XElement modifierElement)
=> new((ModifierKindEnum)Enum.Parse(typeof(ModifierKindEnum), modifierElement.Value));
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
=> writer.WriteInt32((int)ModifierKindWrapper);
public static ModifierKind ReadFrom(ObjectReader reader)
=> new((ModifierKindEnum)reader.ReadInt32());
public override bool Equals(object obj)
=> obj is ModifierKind kind && Equals(kind);
public override int GetHashCode()
=> (int)ModifierKindWrapper;
public bool Equals(ModifierKind other)
=> ModifierKindWrapper == other.ModifierKindWrapper;
}
public enum ModifierKindEnum
{
IsAbstract,
IsStatic,
IsAsync,
IsReadOnly,
IsConst,
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
internal sealed partial class WorkCoordinator
{
private readonly Registration _registration;
private readonly object _gate;
private readonly LogAggregator _logAggregator;
private readonly IAsynchronousOperationListener _listener;
private readonly IOptionService _optionService;
private readonly IDocumentTrackingService _documentTrackingService;
private readonly CancellationTokenSource _shutdownNotificationSource;
private readonly CancellationToken _shutdownToken;
private readonly TaskQueue _eventProcessingQueue;
// points to processor task
private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor;
private readonly SemanticChangeProcessor _semanticChangeProcessor;
public WorkCoordinator(
IAsynchronousOperationListener listener,
IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
bool initializeLazily,
Registration registration)
{
_logAggregator = new LogAggregator();
_registration = registration;
_gate = new object();
_listener = listener;
_optionService = _registration.Workspace.Services.GetRequiredService<IOptionService>();
_documentTrackingService = _registration.Workspace.Services.GetRequiredService<IDocumentTrackingService>();
// event and worker queues
_shutdownNotificationSource = new CancellationTokenSource();
_shutdownToken = _shutdownNotificationSource.Token;
_eventProcessingQueue = new TaskQueue(listener, TaskScheduler.Default);
var activeFileBackOffTimeSpan = InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpan;
var allFilesWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan;
var entireProjectWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpan;
_documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor(
listener, analyzerProviders, initializeLazily, _registration,
activeFileBackOffTimeSpan, allFilesWorkerBackOffTimeSpan, entireProjectWorkerBackOffTimeSpan, _shutdownToken);
var semanticBackOffTimeSpan = InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpan;
var projectBackOffTimeSpan = InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpan;
_semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpan, projectBackOffTimeSpan, _shutdownToken);
// if option is on
if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
// subscribe to option changed event after all required fields are set
// otherwise, we can get null exception when running OnOptionChanged handler
_optionService.OptionChanged += OnOptionChanged;
// subscribe to active document changed event for active file background analysis scope.
_documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged;
}
public int CorrelationId => _registration.CorrelationId;
public void AddAnalyzer(IIncrementalAnalyzer analyzer, bool highPriorityForActiveFile)
{
// add analyzer
_documentAndProjectWorkerProcessor.AddAnalyzer(analyzer, highPriorityForActiveFile);
// and ask to re-analyze whole solution for the given analyzer
var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id);
Reanalyze(analyzer, scope);
}
public void Shutdown(bool blockingShutdown)
{
_optionService.OptionChanged -= OnOptionChanged;
_documentTrackingService.ActiveDocumentChanged -= OnActiveDocumentChanged;
// detach from the workspace
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
// cancel any pending blocks
_shutdownNotificationSource.Cancel();
_documentAndProjectWorkerProcessor.Shutdown();
SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator);
if (blockingShutdown)
{
var shutdownTask = Task.WhenAll(
_eventProcessingQueue.LastScheduledTask,
_documentAndProjectWorkerProcessor.AsyncProcessorTask,
_semanticChangeProcessor.AsyncProcessorTask);
try
{
shutdownTask.Wait(TimeSpan.FromSeconds(5));
}
catch (AggregateException ex)
{
ex.Handle(e => e is OperationCanceledException);
}
if (!shutdownTask.IsCompleted)
{
SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId);
}
}
}
private void OnOptionChanged(object? sender, OptionChangedEventArgs e)
{
// if solution crawler got turned off or on.
if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler)
{
Contract.ThrowIfNull(e.Value);
var value = (bool)e.Value;
if (value)
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
else
{
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
}
SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value);
return;
}
if (!_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
// Bail out if solution crawler is disabled.
return;
}
ReanalyzeOnOptionChange(sender, e);
}
private void ReanalyzeOnOptionChange(object? sender, OptionChangedEventArgs e)
{
// get off from option changed event handler since it runs on UI thread
// getting analyzer can be slow for the very first time since it is lazily initialized
_eventProcessingQueue.ScheduleTask(nameof(ReanalyzeOnOptionChange), () =>
{
// let each analyzer decide what they want on option change
foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers)
{
if (analyzer.NeedsReanalysisOnOptionChanged(sender, e))
{
var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id);
Reanalyze(analyzer, scope);
}
}
}, _shutdownToken);
}
public void Reanalyze(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority = false)
{
_eventProcessingQueue.ScheduleTask("Reanalyze",
() => EnqueueWorkItemAsync(analyzer, scope, highPriority), _shutdownToken);
if (scope.HasMultipleDocuments)
{
// log big reanalysis request from things like fix all, suppress all or option changes
// we are not interested in 1 file re-analysis request which can happen from like venus typing
var solution = _registration.GetSolutionToAnalyze();
SolutionCrawlerLogger.LogReanalyze(
CorrelationId, analyzer, scope.GetDocumentCount(solution), scope.GetLanguagesStringForTelemetry(solution), highPriority);
}
}
private void OnActiveDocumentChanged(object? sender, DocumentId? activeDocumentId)
{
var solution = _registration.GetSolutionToAnalyze();
if (solution.GetProject(activeDocumentId?.ProjectId) is not { } activeProject)
return;
RoslynDebug.AssertNotNull(activeDocumentId);
var analysisScope = SolutionCrawlerOptions.GetBackgroundAnalysisScope(activeProject);
if (analysisScope == BackgroundAnalysisScope.ActiveFile)
{
// When the active document changes and we are only analyzing the active file, trigger a document
// changed event to reanalyze the newly-active file.
EnqueueEvent(solution, activeDocumentId, InvocationReasons.DocumentChanged, nameof(OnActiveDocumentChanged));
}
}
private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs args)
{
// guard us from cancellation
try
{
ProcessEvent(args, "OnWorkspaceChanged");
}
catch (OperationCanceledException oce)
{
if (NotOurShutdownToken(oce))
{
throw;
}
// it is our cancellation, ignore
}
catch (AggregateException ae)
{
ae = ae.Flatten();
// If we had a mix of exceptions, don't eat it
if (ae.InnerExceptions.Any(e => e is not OperationCanceledException) ||
ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken))
{
// We had a cancellation with a different token, so don't eat it
throw;
}
// it is our cancellation, ignore
}
}
private bool NotOurShutdownToken(OperationCanceledException oce)
=> oce.CancellationToken == _shutdownToken;
private void ProcessEvent(WorkspaceChangeEventArgs args, string eventName)
{
SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind);
// TODO: add telemetry that record how much it takes to process an event (max, min, average and etc)
switch (args.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
ProcessSolutionEvent(args, eventName);
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectRemoved:
ProcessProjectEvent(args, eventName);
break;
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:
case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved:
case WorkspaceChangeKind.AnalyzerConfigDocumentChanged:
case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded:
ProcessDocumentEvent(args, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(args.Kind);
}
}
private void OnDocumentOpened(object? sender, DocumentEventArgs e)
{
_eventProcessingQueue.ScheduleTask("OnDocumentOpened",
() => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentOpened), _shutdownToken);
}
private void OnDocumentClosed(object? sender, DocumentEventArgs e)
{
_eventProcessingQueue.ScheduleTask("OnDocumentClosed",
() => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentClosed), _shutdownToken);
}
private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, string eventName)
{
switch (e.Kind)
{
case WorkspaceChangeKind.DocumentAdded:
Contract.ThrowIfNull(e.DocumentId);
EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, eventName);
break;
case WorkspaceChangeKind.DocumentRemoved:
Contract.ThrowIfNull(e.DocumentId);
EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, eventName);
break;
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
Contract.ThrowIfNull(e.DocumentId);
EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, eventName);
break;
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:
case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved:
case WorkspaceChangeKind.AnalyzerConfigDocumentChanged:
case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded:
// If an additional file or .editorconfig has changed we need to reanalyze the entire project.
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(e.Kind);
}
}
private void ProcessProjectEvent(WorkspaceChangeEventArgs e, string eventName)
{
switch (e.Kind)
{
case WorkspaceChangeKind.ProjectAdded:
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, eventName);
break;
case WorkspaceChangeKind.ProjectRemoved:
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, eventName);
break;
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(e.Kind);
}
}
private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, string eventName)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, eventName);
break;
case WorkspaceChangeKind.SolutionRemoved:
EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, eventName);
break;
case WorkspaceChangeKind.SolutionCleared:
EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, eventName);
break;
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(e.Kind);
}
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken);
}
private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken);
}
private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken);
}
private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, string eventName)
{
// document changed event is the special one.
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken);
}
private async Task EnqueueWorkItemAsync(Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons, SyntaxNode? changedMember = null)
{
// we are shutting down
_shutdownToken.ThrowIfCancellationRequested();
var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false);
var currentMember = GetSyntaxPath(changedMember);
// call to this method is serialized. and only this method does the writing.
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem")));
// enqueue semantic work planner
if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
// must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later.
// due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual.
_semanticChangeProcessor.Enqueue(project, documentId, document, currentMember);
}
}
private static Document GetRequiredDocument(Project project, DocumentId documentId, Document? document)
=> document ?? project.GetRequiredDocument(documentId);
private static SyntaxPath? GetSyntaxPath(SyntaxNode? changedMember)
{
// using syntax path might be too expansive since it will be created on every keystroke.
// but currently, we have no other way to track a node between two different tree (even for incrementally parsed one)
if (changedMember == null)
{
return null;
}
return new SyntaxPath(changedMember);
}
private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons)
{
foreach (var documentId in project.DocumentIds)
await EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons).ConfigureAwait(false);
}
private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority)
{
var solution = _registration.GetSolutionToAnalyze();
var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze;
foreach (var (project, documentId) in scope.GetDocumentIds(solution))
await EnqueueWorkItemAsync(analyzer, project, documentId, document: null, invocationReasons).ConfigureAwait(false);
}
private async Task EnqueueWorkItemAsync(
IIncrementalAnalyzer analyzer, Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons)
{
var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(
GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false);
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, project.Language, invocationReasons,
isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem")));
}
private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
// TODO: Async version for GetXXX methods?
foreach (var addedProject in solutionChanges.GetAddedProjects())
{
await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedProject in solutionChanges.GetRemovedProjects())
{
await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges)
{
await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false);
foreach (var addedDocumentId in projectChanges.GetAddedDocuments())
await EnqueueWorkItemAsync(projectChanges.NewProject, addedDocumentId, document: null, InvocationReasons.DocumentAdded).ConfigureAwait(false);
foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetRequiredDocument(changedDocumentId), projectChanges.NewProject.GetRequiredDocument(changedDocumentId))
.ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedDocumentId in projectChanges.GetRemovedDocuments())
await EnqueueWorkItemAsync(projectChanges.OldProject, removedDocumentId, document: null, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges)
{
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
// TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document?
var projectConfigurationChange = InvocationReasons.Empty;
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged);
}
if (projectChanges.GetAddedMetadataReferences().Any() ||
projectChanges.GetAddedProjectReferences().Any() ||
projectChanges.GetAddedAnalyzerReferences().Any() ||
projectChanges.GetRemovedMetadataReferences().Any() ||
projectChanges.GetRemovedProjectReferences().Any() ||
projectChanges.GetRemovedAnalyzerReferences().Any() ||
!object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) ||
!object.Equals(oldProject.AssemblyName, newProject.AssemblyName) ||
!object.Equals(oldProject.Name, newProject.Name) ||
!object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions) ||
!object.Equals(oldProject.DefaultNamespace, newProject.DefaultNamespace) ||
!object.Equals(oldProject.OutputFilePath, newProject.OutputFilePath) ||
!object.Equals(oldProject.OutputRefFilePath, newProject.OutputRefFilePath) ||
!oldProject.CompilationOutputInfo.Equals(newProject.CompilationOutputInfo) ||
oldProject.State.RunAnalyzers != newProject.State.RunAnalyzers)
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged);
}
if (!projectConfigurationChange.IsEmpty)
{
await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument)
{
var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>();
if (differenceService == null)
{
// For languages that don't use a Roslyn syntax tree, they don't export a document difference service.
// The whole document should be considered as changed in that case.
await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, InvocationReasons.DocumentChanged).ConfigureAwait(false);
}
else
{
var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false);
if (differenceResult != null)
await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false);
}
}
private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons)
{
var project = solution.GetRequiredProject(documentId.ProjectId);
return EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons);
}
private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons)
{
var project = solution.GetRequiredProject(projectId);
return EnqueueWorkItemAsync(project, invocationReasons);
}
private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons)
{
foreach (var projectId in solution.ProjectIds)
{
await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId)
{
var oldProject = oldSolution.GetRequiredProject(projectId);
var newProject = newSolution.GetRequiredProject(projectId);
await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false);
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId)
{
var oldProject = oldSolution.GetRequiredProject(documentId.ProjectId);
var newProject = newSolution.GetRequiredProject(documentId.ProjectId);
await EnqueueWorkItemAsync(oldProject.GetRequiredDocument(documentId), newProject.GetRequiredDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false);
}
internal TestAccessor GetTestAccessor()
{
return new TestAccessor(this);
}
internal readonly struct TestAccessor
{
private readonly WorkCoordinator _workCoordinator;
internal TestAccessor(WorkCoordinator workCoordinator)
{
_workCoordinator = workCoordinator;
}
internal void WaitUntilCompletion(ImmutableArray<IIncrementalAnalyzer> workers)
{
var solution = _workCoordinator._registration.GetSolutionToAnalyze();
var list = new List<WorkItem>();
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, isLowPriority: false, activeMember: null, EmptyAsyncToken.Instance));
}
}
_workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion(workers, list);
}
internal void WaitUntilCompletion()
=> _workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion();
}
}
internal readonly struct ReanalyzeScope
{
private readonly SolutionId? _solutionId;
private readonly ISet<object>? _projectOrDocumentIds;
public ReanalyzeScope(SolutionId solutionId)
{
_solutionId = solutionId;
_projectOrDocumentIds = null;
}
public ReanalyzeScope(IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null)
{
projectIds ??= SpecializedCollections.EmptyEnumerable<ProjectId>();
documentIds ??= SpecializedCollections.EmptyEnumerable<DocumentId>();
_solutionId = null;
_projectOrDocumentIds = new HashSet<object>(projectIds);
foreach (var documentId in documentIds)
{
if (_projectOrDocumentIds.Contains(documentId.ProjectId))
{
continue;
}
_projectOrDocumentIds.Add(documentId);
}
}
public bool HasMultipleDocuments => _solutionId != null || _projectOrDocumentIds?.Count > 1;
public string GetLanguagesStringForTelemetry(Solution solution)
{
if (_solutionId != null && solution.Id != _solutionId)
{
// return empty if given solution is not
// same as solution this scope is created for
return string.Empty;
}
using var pool = SharedPools.Default<HashSet<string>>().GetPooledObject();
if (_solutionId != null)
{
pool.Object.UnionWith(solution.State.ProjectStates.Select(kv => kv.Value.Language));
return string.Join(",", pool.Object);
}
Contract.ThrowIfNull(_projectOrDocumentIds);
foreach (var projectOrDocumentId in _projectOrDocumentIds)
{
switch (projectOrDocumentId)
{
case ProjectId projectId:
var project = solution.GetProject(projectId);
if (project != null)
{
pool.Object.Add(project.Language);
}
break;
case DocumentId documentId:
var document = solution.GetDocument(documentId);
if (document != null)
{
pool.Object.Add(document.Project.Language);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId);
}
}
return string.Join(",", pool.Object);
}
public int GetDocumentCount(Solution solution)
{
if (_solutionId != null && solution.Id != _solutionId)
{
return 0;
}
var count = 0;
if (_solutionId != null)
{
foreach (var projectState in solution.State.ProjectStates)
{
count += projectState.Value.DocumentStates.Count;
}
return count;
}
Contract.ThrowIfNull(_projectOrDocumentIds);
foreach (var projectOrDocumentId in _projectOrDocumentIds)
{
switch (projectOrDocumentId)
{
case ProjectId projectId:
var project = solution.GetProject(projectId);
if (project != null)
{
count += project.DocumentIds.Count;
}
break;
case DocumentId documentId:
count++;
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId);
}
}
return count;
}
public IEnumerable<(Project project, DocumentId documentId)> GetDocumentIds(Solution solution)
{
if (_solutionId != null && solution.Id != _solutionId)
{
yield break;
}
if (_solutionId != null)
{
foreach (var project in solution.Projects)
{
foreach (var documentId in project.DocumentIds)
yield return (project, documentId);
}
yield break;
}
Contract.ThrowIfNull(_projectOrDocumentIds);
foreach (var projectOrDocumentId in _projectOrDocumentIds)
{
switch (projectOrDocumentId)
{
case ProjectId projectId:
{
var project = solution.GetProject(projectId);
if (project != null)
{
foreach (var documentId in project.DocumentIds)
yield return (project, documentId);
}
break;
}
case DocumentId documentId:
{
var project = solution.GetProject(documentId.ProjectId);
if (project != null)
yield return (project, documentId);
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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
internal sealed partial class WorkCoordinator
{
private readonly Registration _registration;
private readonly object _gate;
private readonly LogAggregator _logAggregator;
private readonly IAsynchronousOperationListener _listener;
private readonly IOptionService _optionService;
private readonly IDocumentTrackingService _documentTrackingService;
private readonly CancellationTokenSource _shutdownNotificationSource;
private readonly CancellationToken _shutdownToken;
private readonly TaskQueue _eventProcessingQueue;
// points to processor task
private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor;
private readonly SemanticChangeProcessor _semanticChangeProcessor;
public WorkCoordinator(
IAsynchronousOperationListener listener,
IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
bool initializeLazily,
Registration registration)
{
_logAggregator = new LogAggregator();
_registration = registration;
_gate = new object();
_listener = listener;
_optionService = _registration.Workspace.Services.GetRequiredService<IOptionService>();
_documentTrackingService = _registration.Workspace.Services.GetRequiredService<IDocumentTrackingService>();
// event and worker queues
_shutdownNotificationSource = new CancellationTokenSource();
_shutdownToken = _shutdownNotificationSource.Token;
_eventProcessingQueue = new TaskQueue(listener, TaskScheduler.Default);
var activeFileBackOffTimeSpan = InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpan;
var allFilesWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpan;
var entireProjectWorkerBackOffTimeSpan = InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpan;
_documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor(
listener, analyzerProviders, initializeLazily, _registration,
activeFileBackOffTimeSpan, allFilesWorkerBackOffTimeSpan, entireProjectWorkerBackOffTimeSpan, _shutdownToken);
var semanticBackOffTimeSpan = InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpan;
var projectBackOffTimeSpan = InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpan;
_semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpan, projectBackOffTimeSpan, _shutdownToken);
// if option is on
if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
// subscribe to option changed event after all required fields are set
// otherwise, we can get null exception when running OnOptionChanged handler
_optionService.OptionChanged += OnOptionChanged;
// subscribe to active document changed event for active file background analysis scope.
_documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged;
}
public int CorrelationId => _registration.CorrelationId;
public void AddAnalyzer(IIncrementalAnalyzer analyzer, bool highPriorityForActiveFile)
{
// add analyzer
_documentAndProjectWorkerProcessor.AddAnalyzer(analyzer, highPriorityForActiveFile);
// and ask to re-analyze whole solution for the given analyzer
var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id);
Reanalyze(analyzer, scope);
}
public void Shutdown(bool blockingShutdown)
{
_optionService.OptionChanged -= OnOptionChanged;
_documentTrackingService.ActiveDocumentChanged -= OnActiveDocumentChanged;
// detach from the workspace
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
// cancel any pending blocks
_shutdownNotificationSource.Cancel();
_documentAndProjectWorkerProcessor.Shutdown();
SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator);
if (blockingShutdown)
{
var shutdownTask = Task.WhenAll(
_eventProcessingQueue.LastScheduledTask,
_documentAndProjectWorkerProcessor.AsyncProcessorTask,
_semanticChangeProcessor.AsyncProcessorTask);
try
{
shutdownTask.Wait(TimeSpan.FromSeconds(5));
}
catch (AggregateException ex)
{
ex.Handle(e => e is OperationCanceledException);
}
if (!shutdownTask.IsCompleted)
{
SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId);
}
}
}
private void OnOptionChanged(object? sender, OptionChangedEventArgs e)
{
// if solution crawler got turned off or on.
if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler)
{
Contract.ThrowIfNull(e.Value);
var value = (bool)e.Value;
if (value)
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
else
{
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
}
SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value);
return;
}
if (!_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
// Bail out if solution crawler is disabled.
return;
}
ReanalyzeOnOptionChange(sender, e);
}
private void ReanalyzeOnOptionChange(object? sender, OptionChangedEventArgs e)
{
// get off from option changed event handler since it runs on UI thread
// getting analyzer can be slow for the very first time since it is lazily initialized
_eventProcessingQueue.ScheduleTask(nameof(ReanalyzeOnOptionChange), () =>
{
// let each analyzer decide what they want on option change
foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers)
{
if (analyzer.NeedsReanalysisOnOptionChanged(sender, e))
{
var scope = new ReanalyzeScope(_registration.GetSolutionToAnalyze().Id);
Reanalyze(analyzer, scope);
}
}
}, _shutdownToken);
}
public void Reanalyze(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority = false)
{
_eventProcessingQueue.ScheduleTask("Reanalyze",
() => EnqueueWorkItemAsync(analyzer, scope, highPriority), _shutdownToken);
if (scope.HasMultipleDocuments)
{
// log big reanalysis request from things like fix all, suppress all or option changes
// we are not interested in 1 file re-analysis request which can happen from like venus typing
var solution = _registration.GetSolutionToAnalyze();
SolutionCrawlerLogger.LogReanalyze(
CorrelationId, analyzer, scope.GetDocumentCount(solution), scope.GetLanguagesStringForTelemetry(solution), highPriority);
}
}
private void OnActiveDocumentChanged(object? sender, DocumentId? activeDocumentId)
{
var solution = _registration.GetSolutionToAnalyze();
if (solution.GetProject(activeDocumentId?.ProjectId) is not { } activeProject)
return;
RoslynDebug.AssertNotNull(activeDocumentId);
var analysisScope = SolutionCrawlerOptions.GetBackgroundAnalysisScope(activeProject);
if (analysisScope == BackgroundAnalysisScope.ActiveFile)
{
// When the active document changes and we are only analyzing the active file, trigger a document
// changed event to reanalyze the newly-active file.
EnqueueEvent(solution, activeDocumentId, InvocationReasons.DocumentChanged, nameof(OnActiveDocumentChanged));
}
}
private void OnWorkspaceChanged(object? sender, WorkspaceChangeEventArgs args)
{
// guard us from cancellation
try
{
ProcessEvent(args, "OnWorkspaceChanged");
}
catch (OperationCanceledException oce)
{
if (NotOurShutdownToken(oce))
{
throw;
}
// it is our cancellation, ignore
}
catch (AggregateException ae)
{
ae = ae.Flatten();
// If we had a mix of exceptions, don't eat it
if (ae.InnerExceptions.Any(e => e is not OperationCanceledException) ||
ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken))
{
// We had a cancellation with a different token, so don't eat it
throw;
}
// it is our cancellation, ignore
}
}
private bool NotOurShutdownToken(OperationCanceledException oce)
=> oce.CancellationToken == _shutdownToken;
private void ProcessEvent(WorkspaceChangeEventArgs args, string eventName)
{
SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind);
// TODO: add telemetry that record how much it takes to process an event (max, min, average and etc)
switch (args.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
ProcessSolutionEvent(args, eventName);
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectRemoved:
ProcessProjectEvent(args, eventName);
break;
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:
case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved:
case WorkspaceChangeKind.AnalyzerConfigDocumentChanged:
case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded:
ProcessDocumentEvent(args, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(args.Kind);
}
}
private void OnDocumentOpened(object? sender, DocumentEventArgs e)
{
_eventProcessingQueue.ScheduleTask("OnDocumentOpened",
() => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentOpened), _shutdownToken);
}
private void OnDocumentClosed(object? sender, DocumentEventArgs e)
{
_eventProcessingQueue.ScheduleTask("OnDocumentClosed",
() => EnqueueWorkItemAsync(e.Document.Project, e.Document.Id, e.Document, InvocationReasons.DocumentClosed), _shutdownToken);
}
private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, string eventName)
{
switch (e.Kind)
{
case WorkspaceChangeKind.DocumentAdded:
Contract.ThrowIfNull(e.DocumentId);
EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, eventName);
break;
case WorkspaceChangeKind.DocumentRemoved:
Contract.ThrowIfNull(e.DocumentId);
EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, eventName);
break;
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
Contract.ThrowIfNull(e.DocumentId);
EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, eventName);
break;
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:
case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved:
case WorkspaceChangeKind.AnalyzerConfigDocumentChanged:
case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded:
// If an additional file or .editorconfig has changed we need to reanalyze the entire project.
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(e.Kind);
}
}
private void ProcessProjectEvent(WorkspaceChangeEventArgs e, string eventName)
{
switch (e.Kind)
{
case WorkspaceChangeKind.ProjectAdded:
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, eventName);
break;
case WorkspaceChangeKind.ProjectRemoved:
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, eventName);
break;
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
Contract.ThrowIfNull(e.ProjectId);
EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(e.Kind);
}
}
private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, string eventName)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, eventName);
break;
case WorkspaceChangeKind.SolutionRemoved:
EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, eventName);
break;
case WorkspaceChangeKind.SolutionCleared:
EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, eventName);
break;
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, eventName);
break;
default:
throw ExceptionUtilities.UnexpectedValue(e.Kind);
}
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken);
}
private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken);
}
private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken);
}
private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, string eventName)
{
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, string eventName)
{
// document changed event is the special one.
_eventProcessingQueue.ScheduleTask(eventName,
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken);
}
private async Task EnqueueWorkItemAsync(Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons, SyntaxNode? changedMember = null)
{
// we are shutting down
_shutdownToken.ThrowIfCancellationRequested();
var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false);
var currentMember = GetSyntaxPath(changedMember);
// call to this method is serialized. and only this method does the writing.
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, project.Language, invocationReasons, isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem")));
// enqueue semantic work planner
if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
// must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later.
// due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual.
_semanticChangeProcessor.Enqueue(project, documentId, document, currentMember);
}
}
private static Document GetRequiredDocument(Project project, DocumentId documentId, Document? document)
=> document ?? project.GetRequiredDocument(documentId);
private static SyntaxPath? GetSyntaxPath(SyntaxNode? changedMember)
{
// using syntax path might be too expansive since it will be created on every keystroke.
// but currently, we have no other way to track a node between two different tree (even for incrementally parsed one)
if (changedMember == null)
{
return null;
}
return new SyntaxPath(changedMember);
}
private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons)
{
foreach (var documentId in project.DocumentIds)
await EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons).ConfigureAwait(false);
}
private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, ReanalyzeScope scope, bool highPriority)
{
var solution = _registration.GetSolutionToAnalyze();
var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze;
foreach (var (project, documentId) in scope.GetDocumentIds(solution))
await EnqueueWorkItemAsync(analyzer, project, documentId, document: null, invocationReasons).ConfigureAwait(false);
}
private async Task EnqueueWorkItemAsync(
IIncrementalAnalyzer analyzer, Project project, DocumentId documentId, Document? document, InvocationReasons invocationReasons)
{
var priorityService = project.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(
GetRequiredDocument(project, documentId, document), _shutdownToken).ConfigureAwait(false);
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, project.Language, invocationReasons,
isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem")));
}
private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
// TODO: Async version for GetXXX methods?
foreach (var addedProject in solutionChanges.GetAddedProjects())
{
await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedProject in solutionChanges.GetRemovedProjects())
{
await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges)
{
await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false);
foreach (var addedDocumentId in projectChanges.GetAddedDocuments())
await EnqueueWorkItemAsync(projectChanges.NewProject, addedDocumentId, document: null, InvocationReasons.DocumentAdded).ConfigureAwait(false);
foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetRequiredDocument(changedDocumentId), projectChanges.NewProject.GetRequiredDocument(changedDocumentId))
.ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedDocumentId in projectChanges.GetRemovedDocuments())
await EnqueueWorkItemAsync(projectChanges.OldProject, removedDocumentId, document: null, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges)
{
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
// TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document?
var projectConfigurationChange = InvocationReasons.Empty;
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged);
}
if (projectChanges.GetAddedMetadataReferences().Any() ||
projectChanges.GetAddedProjectReferences().Any() ||
projectChanges.GetAddedAnalyzerReferences().Any() ||
projectChanges.GetRemovedMetadataReferences().Any() ||
projectChanges.GetRemovedProjectReferences().Any() ||
projectChanges.GetRemovedAnalyzerReferences().Any() ||
!object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) ||
!object.Equals(oldProject.AssemblyName, newProject.AssemblyName) ||
!object.Equals(oldProject.Name, newProject.Name) ||
!object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions) ||
!object.Equals(oldProject.DefaultNamespace, newProject.DefaultNamespace) ||
!object.Equals(oldProject.OutputFilePath, newProject.OutputFilePath) ||
!object.Equals(oldProject.OutputRefFilePath, newProject.OutputRefFilePath) ||
!oldProject.CompilationOutputInfo.Equals(newProject.CompilationOutputInfo) ||
oldProject.State.RunAnalyzers != newProject.State.RunAnalyzers)
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged);
}
if (!projectConfigurationChange.IsEmpty)
{
await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument)
{
var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>();
if (differenceService == null)
{
// For languages that don't use a Roslyn syntax tree, they don't export a document difference service.
// The whole document should be considered as changed in that case.
await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, InvocationReasons.DocumentChanged).ConfigureAwait(false);
}
else
{
var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false);
if (differenceResult != null)
await EnqueueWorkItemAsync(newDocument.Project, newDocument.Id, newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false);
}
}
private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons)
{
var project = solution.GetRequiredProject(documentId.ProjectId);
return EnqueueWorkItemAsync(project, documentId, document: null, invocationReasons);
}
private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons)
{
var project = solution.GetRequiredProject(projectId);
return EnqueueWorkItemAsync(project, invocationReasons);
}
private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons)
{
foreach (var projectId in solution.ProjectIds)
{
await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId)
{
var oldProject = oldSolution.GetRequiredProject(projectId);
var newProject = newSolution.GetRequiredProject(projectId);
await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false);
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId)
{
var oldProject = oldSolution.GetRequiredProject(documentId.ProjectId);
var newProject = newSolution.GetRequiredProject(documentId.ProjectId);
await EnqueueWorkItemAsync(oldProject.GetRequiredDocument(documentId), newProject.GetRequiredDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false);
}
internal TestAccessor GetTestAccessor()
{
return new TestAccessor(this);
}
internal readonly struct TestAccessor
{
private readonly WorkCoordinator _workCoordinator;
internal TestAccessor(WorkCoordinator workCoordinator)
{
_workCoordinator = workCoordinator;
}
internal void WaitUntilCompletion(ImmutableArray<IIncrementalAnalyzer> workers)
{
var solution = _workCoordinator._registration.GetSolutionToAnalyze();
var list = new List<WorkItem>();
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, isLowPriority: false, activeMember: null, EmptyAsyncToken.Instance));
}
}
_workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion(workers, list);
}
internal void WaitUntilCompletion()
=> _workCoordinator._documentAndProjectWorkerProcessor.GetTestAccessor().WaitUntilCompletion();
}
}
internal readonly struct ReanalyzeScope
{
private readonly SolutionId? _solutionId;
private readonly ISet<object>? _projectOrDocumentIds;
public ReanalyzeScope(SolutionId solutionId)
{
_solutionId = solutionId;
_projectOrDocumentIds = null;
}
public ReanalyzeScope(IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null)
{
projectIds ??= SpecializedCollections.EmptyEnumerable<ProjectId>();
documentIds ??= SpecializedCollections.EmptyEnumerable<DocumentId>();
_solutionId = null;
_projectOrDocumentIds = new HashSet<object>(projectIds);
foreach (var documentId in documentIds)
{
if (_projectOrDocumentIds.Contains(documentId.ProjectId))
{
continue;
}
_projectOrDocumentIds.Add(documentId);
}
}
public bool HasMultipleDocuments => _solutionId != null || _projectOrDocumentIds?.Count > 1;
public string GetLanguagesStringForTelemetry(Solution solution)
{
if (_solutionId != null && solution.Id != _solutionId)
{
// return empty if given solution is not
// same as solution this scope is created for
return string.Empty;
}
using var pool = SharedPools.Default<HashSet<string>>().GetPooledObject();
if (_solutionId != null)
{
pool.Object.UnionWith(solution.State.ProjectStates.Select(kv => kv.Value.Language));
return string.Join(",", pool.Object);
}
Contract.ThrowIfNull(_projectOrDocumentIds);
foreach (var projectOrDocumentId in _projectOrDocumentIds)
{
switch (projectOrDocumentId)
{
case ProjectId projectId:
var project = solution.GetProject(projectId);
if (project != null)
{
pool.Object.Add(project.Language);
}
break;
case DocumentId documentId:
var document = solution.GetDocument(documentId);
if (document != null)
{
pool.Object.Add(document.Project.Language);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId);
}
}
return string.Join(",", pool.Object);
}
public int GetDocumentCount(Solution solution)
{
if (_solutionId != null && solution.Id != _solutionId)
{
return 0;
}
var count = 0;
if (_solutionId != null)
{
foreach (var projectState in solution.State.ProjectStates)
{
count += projectState.Value.DocumentStates.Count;
}
return count;
}
Contract.ThrowIfNull(_projectOrDocumentIds);
foreach (var projectOrDocumentId in _projectOrDocumentIds)
{
switch (projectOrDocumentId)
{
case ProjectId projectId:
var project = solution.GetProject(projectId);
if (project != null)
{
count += project.DocumentIds.Count;
}
break;
case DocumentId documentId:
count++;
break;
default:
throw ExceptionUtilities.UnexpectedValue(projectOrDocumentId);
}
}
return count;
}
public IEnumerable<(Project project, DocumentId documentId)> GetDocumentIds(Solution solution)
{
if (_solutionId != null && solution.Id != _solutionId)
{
yield break;
}
if (_solutionId != null)
{
foreach (var project in solution.Projects)
{
foreach (var documentId in project.DocumentIds)
yield return (project, documentId);
}
yield break;
}
Contract.ThrowIfNull(_projectOrDocumentIds);
foreach (var projectOrDocumentId in _projectOrDocumentIds)
{
switch (projectOrDocumentId)
{
case ProjectId projectId:
{
var project = solution.GetProject(projectId);
if (project != null)
{
foreach (var documentId in project.DocumentIds)
yield return (project, documentId);
}
break;
}
case DocumentId documentId:
{
var project = solution.GetProject(documentId.ProjectId);
if (project != null)
yield return (project, documentId);
break;
}
}
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Core/Implementation/InlineRename/Taggers/ClassificationTypeDefinitions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal sealed class ClassificationTypeDefinitions
{
// Only used for theming, does not need localized
public const string InlineRenameField = "Inline Rename Field Text";
[Export]
[Name(InlineRenameField)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition? InlineRenameFieldTypeDefinition;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal sealed class ClassificationTypeDefinitions
{
// Only used for theming, does not need localized
public const string InlineRenameField = "Inline Rename Field Text";
[Export]
[Name(InlineRenameField)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition? InlineRenameFieldTypeDefinition;
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Binder/ExpressionVariableBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class ExpressionVariableBinder : LocalScopeBinder
{
internal override SyntaxNode ScopeDesignator { get; }
internal ExpressionVariableBinder(SyntaxNode scopeDesignator, Binder next) : base(next)
{
this.ScopeDesignator = scopeDesignator;
}
protected override ImmutableArray<LocalSymbol> BuildLocals()
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
ExpressionVariableFinder.FindExpressionVariables(this, builder, (CSharpSyntaxNode)ScopeDesignator,
GetBinder((CSharpSyntaxNode)ScopeDesignator));
return builder.ToImmutableAndFree();
}
internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator)
{
if (ScopeDesignator == scopeDesignator)
{
return this.Locals;
}
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class ExpressionVariableBinder : LocalScopeBinder
{
internal override SyntaxNode ScopeDesignator { get; }
internal ExpressionVariableBinder(SyntaxNode scopeDesignator, Binder next) : base(next)
{
this.ScopeDesignator = scopeDesignator;
}
protected override ImmutableArray<LocalSymbol> BuildLocals()
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
ExpressionVariableFinder.FindExpressionVariables(this, builder, (CSharpSyntaxNode)ScopeDesignator,
GetBinder((CSharpSyntaxNode)ScopeDesignator));
return builder.ToImmutableAndFree();
}
internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator)
{
if (ScopeDesignator == scopeDesignator)
{
return this.Locals;
}
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Core/Portable/Text/ChangedText.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
internal sealed class ChangedText : SourceText
{
private readonly SourceText _newText;
private readonly ChangeInfo _info;
public ChangedText(SourceText oldText, SourceText newText, ImmutableArray<TextChangeRange> changeRanges)
: base(checksumAlgorithm: oldText.ChecksumAlgorithm)
{
RoslynDebug.Assert(newText != null);
Debug.Assert(newText is CompositeText || newText is SubText || newText is StringText || newText is LargeText);
RoslynDebug.Assert(oldText != null);
Debug.Assert(oldText != newText);
Debug.Assert(!changeRanges.IsDefault);
RequiresChangeRangesAreValid(oldText, newText, changeRanges);
_newText = newText;
_info = new ChangeInfo(changeRanges, new WeakReference<SourceText>(oldText), (oldText as ChangedText)?._info);
}
private static void RequiresChangeRangesAreValid(
SourceText oldText, SourceText newText, ImmutableArray<TextChangeRange> changeRanges)
{
var deltaLength = 0;
foreach (var change in changeRanges)
deltaLength += change.NewLength - change.Span.Length;
if (oldText.Length + deltaLength != newText.Length)
throw new InvalidOperationException("Delta length difference of change ranges didn't match before/after text length.");
var position = 0;
foreach (var change in changeRanges)
{
if (change.Span.Start < position)
throw new InvalidOperationException("Change preceded current position in oldText");
if (change.Span.Start > oldText.Length)
throw new InvalidOperationException("Change start was after the end of oldText");
if (change.Span.End > oldText.Length)
throw new InvalidOperationException("Change end was after the end of oldText");
position = change.Span.End;
}
}
private class ChangeInfo
{
public ImmutableArray<TextChangeRange> ChangeRanges { get; }
// store old text weakly so we don't form unwanted chains of old texts (especially chains of ChangedTexts)
// used to identify the changes in GetChangeRanges.
public WeakReference<SourceText> WeakOldText { get; }
public ChangeInfo? Previous { get; private set; }
public ChangeInfo(ImmutableArray<TextChangeRange> changeRanges, WeakReference<SourceText> weakOldText, ChangeInfo? previous)
{
this.ChangeRanges = changeRanges;
this.WeakOldText = weakOldText;
this.Previous = previous;
Clean();
}
// clean up
private void Clean()
{
// look for last info in the chain that still has reference to old text
ChangeInfo? lastInfo = this;
for (ChangeInfo? info = this; info != null; info = info.Previous)
{
SourceText? tmp;
if (info.WeakOldText.TryGetTarget(out tmp))
{
lastInfo = info;
}
}
// break chain for any info's beyond that so they get GC'd
ChangeInfo? prev;
while (lastInfo != null)
{
prev = lastInfo.Previous;
lastInfo.Previous = null;
lastInfo = prev;
}
}
}
public override Encoding? Encoding
{
get { return _newText.Encoding; }
}
public IEnumerable<TextChangeRange> Changes
{
get { return _info.ChangeRanges; }
}
public override int Length
{
get { return _newText.Length; }
}
internal override int StorageSize
{
get { return _newText.StorageSize; }
}
internal override ImmutableArray<SourceText> Segments
{
get { return _newText.Segments; }
}
internal override SourceText StorageKey
{
get { return _newText.StorageKey; }
}
public override char this[int position]
{
get { return _newText[position]; }
}
public override string ToString(TextSpan span)
{
return _newText.ToString(span);
}
public override SourceText GetSubText(TextSpan span)
{
return _newText.GetSubText(span);
}
public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
_newText.CopyTo(sourceIndex, destination, destinationIndex, count);
}
public override SourceText WithChanges(IEnumerable<TextChange> changes)
{
// compute changes against newText to avoid capturing strong references to this ChangedText instance.
// _newText will only ever be one of CompositeText, SubText, StringText or LargeText, so calling WithChanges on it
// will either produce a ChangeText instance or the original instance in case of a empty change.
var changed = _newText.WithChanges(changes) as ChangedText;
if (changed != null)
{
return new ChangedText(this, changed._newText, changed._info.ChangeRanges);
}
else
{
// change was empty, so just return this same instance
return this;
}
}
public override IReadOnlyList<TextChangeRange> GetChangeRanges(SourceText oldText)
{
if (oldText == null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (this == oldText)
{
return TextChangeRange.NoChanges;
}
// try this quick check first
SourceText? actualOldText;
if (_info.WeakOldText.TryGetTarget(out actualOldText) && actualOldText == oldText)
{
// the supplied old text is the one we directly reference, so the changes must be the ones we have.
return _info.ChangeRanges;
}
// otherwise look to see if there are a series of changes from the old text to this text and merge them.
if (IsChangedFrom(oldText))
{
var changes = GetChangesBetween(oldText, this);
if (changes.Count > 1)
{
return Merge(changes);
}
}
// the SourceText subtype for editor snapshots knows when two snapshots from the same buffer have the same contents
if (actualOldText != null && actualOldText.GetChangeRanges(oldText).Count == 0)
{
// the texts are different instances, but the contents are considered to be the same.
return _info.ChangeRanges;
}
return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), _newText.Length));
}
private bool IsChangedFrom(SourceText oldText)
{
for (ChangeInfo? info = _info; info != null; info = info.Previous)
{
SourceText? text;
if (info.WeakOldText.TryGetTarget(out text) && text == oldText)
{
return true;
}
}
return false;
}
private static IReadOnlyList<ImmutableArray<TextChangeRange>> GetChangesBetween(SourceText oldText, ChangedText newText)
{
var list = new List<ImmutableArray<TextChangeRange>>();
ChangeInfo? change = newText._info;
list.Add(change.ChangeRanges);
while (change != null)
{
SourceText? actualOldText;
change.WeakOldText.TryGetTarget(out actualOldText);
if (actualOldText == oldText)
{
return list;
}
change = change.Previous;
if (change != null)
{
list.Insert(0, change.ChangeRanges);
}
}
// did not find old text, so not connected?
list.Clear();
return list;
}
private static ImmutableArray<TextChangeRange> Merge(IReadOnlyList<ImmutableArray<TextChangeRange>> changeSets)
{
Debug.Assert(changeSets.Count > 1);
var merged = changeSets[0];
for (int i = 1; i < changeSets.Count; i++)
{
merged = TextChangeRangeExtensions.Merge(merged, changeSets[i]);
}
return merged;
}
/// <summary>
/// Computes line starts faster given already computed line starts from text before the change.
/// </summary>
protected override TextLineCollection GetLinesCore()
{
SourceText? oldText;
TextLineCollection? oldLineInfo;
if (!_info.WeakOldText.TryGetTarget(out oldText) || !oldText.TryGetLines(out oldLineInfo))
{
// no old line starts? do it the hard way.
return base.GetLinesCore();
}
// compute line starts given changes and line starts already computed from previous text
var lineStarts = ArrayBuilder<int>.GetInstance();
lineStarts.Add(0);
// position in the original document
var position = 0;
// delta generated by already processed changes (position in the new document = position + delta)
var delta = 0;
// true if last segment ends with CR and we need to check for CR+LF code below assumes that both CR and LF are also line breaks alone
var endsWithCR = false;
foreach (var change in _info.ChangeRanges)
{
// include existing line starts that occur before this change
if (change.Span.Start > position)
{
if (endsWithCR && _newText[position + delta] == '\n')
{
// remove last added line start (it was due to previous CR)
// a new line start including the LF will be added next
lineStarts.RemoveLast();
}
var lps = oldLineInfo.GetLinePositionSpan(TextSpan.FromBounds(position, change.Span.Start));
for (int i = lps.Start.Line + 1; i <= lps.End.Line; i++)
{
lineStarts.Add(oldLineInfo[i].Start + delta);
}
endsWithCR = oldText[change.Span.Start - 1] == '\r';
// in case change is inserted between CR+LF we treat CR as line break alone,
// but this line break might be retracted and replaced with new one in case LF is inserted
if (endsWithCR && change.Span.Start < oldText.Length && oldText[change.Span.Start] == '\n')
{
lineStarts.Add(change.Span.Start + delta);
}
}
// include line starts that occur within newly inserted text
if (change.NewLength > 0)
{
var changeStart = change.Span.Start + delta;
var text = GetSubText(new TextSpan(changeStart, change.NewLength));
if (endsWithCR && text[0] == '\n')
{
// remove last added line start (it was due to previous CR)
// a new line start including the LF will be added next
lineStarts.RemoveLast();
}
// Skip first line (it is always at offset 0 and corresponds to the previous line)
for (int i = 1; i < text.Lines.Count; i++)
{
lineStarts.Add(changeStart + text.Lines[i].Start);
}
endsWithCR = text[change.NewLength - 1] == '\r';
}
position = change.Span.End;
delta += (change.NewLength - change.Span.Length);
}
// include existing line starts that occur after all changes
if (position < oldText.Length)
{
if (endsWithCR && _newText[position + delta] == '\n')
{
// remove last added line start (it was due to previous CR)
// a new line start including the LF will be added next
lineStarts.RemoveLast();
}
var lps = oldLineInfo.GetLinePositionSpan(TextSpan.FromBounds(position, oldText.Length));
for (int i = lps.Start.Line + 1; i <= lps.End.Line; i++)
{
lineStarts.Add(oldLineInfo[i].Start + delta);
}
}
return new LineInfo(this, lineStarts.ToArrayAndFree());
}
internal static class TestAccessor
{
public static ImmutableArray<TextChangeRange> Merge(ImmutableArray<TextChangeRange> oldChanges, ImmutableArray<TextChangeRange> newChanges)
=> TextChangeRangeExtensions.Merge(oldChanges, newChanges);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Text
{
internal sealed class ChangedText : SourceText
{
private readonly SourceText _newText;
private readonly ChangeInfo _info;
public ChangedText(SourceText oldText, SourceText newText, ImmutableArray<TextChangeRange> changeRanges)
: base(checksumAlgorithm: oldText.ChecksumAlgorithm)
{
RoslynDebug.Assert(newText != null);
Debug.Assert(newText is CompositeText || newText is SubText || newText is StringText || newText is LargeText);
RoslynDebug.Assert(oldText != null);
Debug.Assert(oldText != newText);
Debug.Assert(!changeRanges.IsDefault);
RequiresChangeRangesAreValid(oldText, newText, changeRanges);
_newText = newText;
_info = new ChangeInfo(changeRanges, new WeakReference<SourceText>(oldText), (oldText as ChangedText)?._info);
}
private static void RequiresChangeRangesAreValid(
SourceText oldText, SourceText newText, ImmutableArray<TextChangeRange> changeRanges)
{
var deltaLength = 0;
foreach (var change in changeRanges)
deltaLength += change.NewLength - change.Span.Length;
if (oldText.Length + deltaLength != newText.Length)
throw new InvalidOperationException("Delta length difference of change ranges didn't match before/after text length.");
var position = 0;
foreach (var change in changeRanges)
{
if (change.Span.Start < position)
throw new InvalidOperationException("Change preceded current position in oldText");
if (change.Span.Start > oldText.Length)
throw new InvalidOperationException("Change start was after the end of oldText");
if (change.Span.End > oldText.Length)
throw new InvalidOperationException("Change end was after the end of oldText");
position = change.Span.End;
}
}
private class ChangeInfo
{
public ImmutableArray<TextChangeRange> ChangeRanges { get; }
// store old text weakly so we don't form unwanted chains of old texts (especially chains of ChangedTexts)
// used to identify the changes in GetChangeRanges.
public WeakReference<SourceText> WeakOldText { get; }
public ChangeInfo? Previous { get; private set; }
public ChangeInfo(ImmutableArray<TextChangeRange> changeRanges, WeakReference<SourceText> weakOldText, ChangeInfo? previous)
{
this.ChangeRanges = changeRanges;
this.WeakOldText = weakOldText;
this.Previous = previous;
Clean();
}
// clean up
private void Clean()
{
// look for last info in the chain that still has reference to old text
ChangeInfo? lastInfo = this;
for (ChangeInfo? info = this; info != null; info = info.Previous)
{
SourceText? tmp;
if (info.WeakOldText.TryGetTarget(out tmp))
{
lastInfo = info;
}
}
// break chain for any info's beyond that so they get GC'd
ChangeInfo? prev;
while (lastInfo != null)
{
prev = lastInfo.Previous;
lastInfo.Previous = null;
lastInfo = prev;
}
}
}
public override Encoding? Encoding
{
get { return _newText.Encoding; }
}
public IEnumerable<TextChangeRange> Changes
{
get { return _info.ChangeRanges; }
}
public override int Length
{
get { return _newText.Length; }
}
internal override int StorageSize
{
get { return _newText.StorageSize; }
}
internal override ImmutableArray<SourceText> Segments
{
get { return _newText.Segments; }
}
internal override SourceText StorageKey
{
get { return _newText.StorageKey; }
}
public override char this[int position]
{
get { return _newText[position]; }
}
public override string ToString(TextSpan span)
{
return _newText.ToString(span);
}
public override SourceText GetSubText(TextSpan span)
{
return _newText.GetSubText(span);
}
public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
_newText.CopyTo(sourceIndex, destination, destinationIndex, count);
}
public override SourceText WithChanges(IEnumerable<TextChange> changes)
{
// compute changes against newText to avoid capturing strong references to this ChangedText instance.
// _newText will only ever be one of CompositeText, SubText, StringText or LargeText, so calling WithChanges on it
// will either produce a ChangeText instance or the original instance in case of a empty change.
var changed = _newText.WithChanges(changes) as ChangedText;
if (changed != null)
{
return new ChangedText(this, changed._newText, changed._info.ChangeRanges);
}
else
{
// change was empty, so just return this same instance
return this;
}
}
public override IReadOnlyList<TextChangeRange> GetChangeRanges(SourceText oldText)
{
if (oldText == null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (this == oldText)
{
return TextChangeRange.NoChanges;
}
// try this quick check first
SourceText? actualOldText;
if (_info.WeakOldText.TryGetTarget(out actualOldText) && actualOldText == oldText)
{
// the supplied old text is the one we directly reference, so the changes must be the ones we have.
return _info.ChangeRanges;
}
// otherwise look to see if there are a series of changes from the old text to this text and merge them.
if (IsChangedFrom(oldText))
{
var changes = GetChangesBetween(oldText, this);
if (changes.Count > 1)
{
return Merge(changes);
}
}
// the SourceText subtype for editor snapshots knows when two snapshots from the same buffer have the same contents
if (actualOldText != null && actualOldText.GetChangeRanges(oldText).Count == 0)
{
// the texts are different instances, but the contents are considered to be the same.
return _info.ChangeRanges;
}
return ImmutableArray.Create(new TextChangeRange(new TextSpan(0, oldText.Length), _newText.Length));
}
private bool IsChangedFrom(SourceText oldText)
{
for (ChangeInfo? info = _info; info != null; info = info.Previous)
{
SourceText? text;
if (info.WeakOldText.TryGetTarget(out text) && text == oldText)
{
return true;
}
}
return false;
}
private static IReadOnlyList<ImmutableArray<TextChangeRange>> GetChangesBetween(SourceText oldText, ChangedText newText)
{
var list = new List<ImmutableArray<TextChangeRange>>();
ChangeInfo? change = newText._info;
list.Add(change.ChangeRanges);
while (change != null)
{
SourceText? actualOldText;
change.WeakOldText.TryGetTarget(out actualOldText);
if (actualOldText == oldText)
{
return list;
}
change = change.Previous;
if (change != null)
{
list.Insert(0, change.ChangeRanges);
}
}
// did not find old text, so not connected?
list.Clear();
return list;
}
private static ImmutableArray<TextChangeRange> Merge(IReadOnlyList<ImmutableArray<TextChangeRange>> changeSets)
{
Debug.Assert(changeSets.Count > 1);
var merged = changeSets[0];
for (int i = 1; i < changeSets.Count; i++)
{
merged = TextChangeRangeExtensions.Merge(merged, changeSets[i]);
}
return merged;
}
/// <summary>
/// Computes line starts faster given already computed line starts from text before the change.
/// </summary>
protected override TextLineCollection GetLinesCore()
{
SourceText? oldText;
TextLineCollection? oldLineInfo;
if (!_info.WeakOldText.TryGetTarget(out oldText) || !oldText.TryGetLines(out oldLineInfo))
{
// no old line starts? do it the hard way.
return base.GetLinesCore();
}
// compute line starts given changes and line starts already computed from previous text
var lineStarts = ArrayBuilder<int>.GetInstance();
lineStarts.Add(0);
// position in the original document
var position = 0;
// delta generated by already processed changes (position in the new document = position + delta)
var delta = 0;
// true if last segment ends with CR and we need to check for CR+LF code below assumes that both CR and LF are also line breaks alone
var endsWithCR = false;
foreach (var change in _info.ChangeRanges)
{
// include existing line starts that occur before this change
if (change.Span.Start > position)
{
if (endsWithCR && _newText[position + delta] == '\n')
{
// remove last added line start (it was due to previous CR)
// a new line start including the LF will be added next
lineStarts.RemoveLast();
}
var lps = oldLineInfo.GetLinePositionSpan(TextSpan.FromBounds(position, change.Span.Start));
for (int i = lps.Start.Line + 1; i <= lps.End.Line; i++)
{
lineStarts.Add(oldLineInfo[i].Start + delta);
}
endsWithCR = oldText[change.Span.Start - 1] == '\r';
// in case change is inserted between CR+LF we treat CR as line break alone,
// but this line break might be retracted and replaced with new one in case LF is inserted
if (endsWithCR && change.Span.Start < oldText.Length && oldText[change.Span.Start] == '\n')
{
lineStarts.Add(change.Span.Start + delta);
}
}
// include line starts that occur within newly inserted text
if (change.NewLength > 0)
{
var changeStart = change.Span.Start + delta;
var text = GetSubText(new TextSpan(changeStart, change.NewLength));
if (endsWithCR && text[0] == '\n')
{
// remove last added line start (it was due to previous CR)
// a new line start including the LF will be added next
lineStarts.RemoveLast();
}
// Skip first line (it is always at offset 0 and corresponds to the previous line)
for (int i = 1; i < text.Lines.Count; i++)
{
lineStarts.Add(changeStart + text.Lines[i].Start);
}
endsWithCR = text[change.NewLength - 1] == '\r';
}
position = change.Span.End;
delta += (change.NewLength - change.Span.Length);
}
// include existing line starts that occur after all changes
if (position < oldText.Length)
{
if (endsWithCR && _newText[position + delta] == '\n')
{
// remove last added line start (it was due to previous CR)
// a new line start including the LF will be added next
lineStarts.RemoveLast();
}
var lps = oldLineInfo.GetLinePositionSpan(TextSpan.FromBounds(position, oldText.Length));
for (int i = lps.Start.Line + 1; i <= lps.End.Line; i++)
{
lineStarts.Add(oldLineInfo[i].Start + delta);
}
}
return new LineInfo(this, lineStarts.ToArrayAndFree());
}
internal static class TestAccessor
{
public static ImmutableArray<TextChangeRange> Merge(ImmutableArray<TextChangeRange> oldChanges, ImmutableArray<TextChangeRange> newChanges)
=> TextChangeRangeExtensions.Merge(oldChanges, newChanges);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/CrossRefBuild.bat | REM Licensed to the .NET Foundation under one or more agreements.
REM The .NET Foundation licenses this file to you under the MIT license.
REM See the LICENSE file in the project root for more information.
vbc CrossRefModule1.vb /target:module /vbruntime-
vbc CrossRefModule2.vb /target:module /vbruntime- /addmodule:CrossRefModule1.netmodule
vbc CrossRefLib.vb /target:library /vbruntime- /addmodule:CrossRefModule1.netmodule,CrossRefModule2.netmodule
| REM Licensed to the .NET Foundation under one or more agreements.
REM The .NET Foundation licenses this file to you under the MIT license.
REM See the LICENSE file in the project root for more information.
vbc CrossRefModule1.vb /target:module /vbruntime-
vbc CrossRefModule2.vb /target:module /vbruntime- /addmodule:CrossRefModule1.netmodule
vbc CrossRefLib.vb /target:library /vbruntime- /addmodule:CrossRefModule1.netmodule,CrossRefModule2.netmodule
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/Core/Portable/Intents/IIntentProviderMetadata.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Features.Intents
{
internal interface IIntentProviderMetadata
{
public string IntentName { get; }
public string LanguageName { 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.
namespace Microsoft.CodeAnalysis.Features.Intents
{
internal interface IIntentProviderMetadata
{
public string IntentName { get; }
public string LanguageName { get; }
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if DEBUG
using Microsoft.CodeAnalysis.Shared.Extensions;
#endif
namespace Microsoft.CodeAnalysis.Simplification
{
internal abstract class AbstractSimplificationService<TExpressionSyntax, TStatementSyntax, TCrefSyntax> : ISimplificationService
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TCrefSyntax : SyntaxNode
{
private ImmutableArray<AbstractReducer> _reducers;
protected AbstractSimplificationService(ImmutableArray<AbstractReducer> reducers)
=> _reducers = reducers;
protected abstract ImmutableArray<NodeOrTokenToReduce> GetNodesAndTokensToReduce(SyntaxNode root, Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpans);
protected abstract SemanticModel GetSpeculativeSemanticModel(ref SyntaxNode nodeToSpeculate, SemanticModel originalSemanticModel, SyntaxNode originalNode);
protected abstract bool CanNodeBeSimplifiedWithoutSpeculation(SyntaxNode node);
protected virtual SyntaxNode TransformReducedNode(SyntaxNode reducedNode, SyntaxNode originalNode)
=> reducedNode;
public abstract SyntaxNode Expand(SyntaxNode node, SemanticModel semanticModel, SyntaxAnnotation annotationForReplacedAliasIdentifier, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken);
public abstract SyntaxToken Expand(SyntaxToken token, SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, CancellationToken cancellationToken);
public async Task<Document> ReduceAsync(
Document document,
ImmutableArray<TextSpan> spans,
OptionSet optionSet = null,
ImmutableArray<AbstractReducer> reducers = default,
CancellationToken cancellationToken = default)
{
using (Logger.LogBlock(FunctionId.Simplifier_ReduceAsync, cancellationToken))
{
var spanList = spans.NullToEmpty();
// we have no span
if (!spanList.Any())
{
return document;
}
optionSet ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Chaining of the Speculative SemanticModel (i.e. Generating a speculative SemanticModel from an existing Speculative SemanticModel) is not supported
// Hence make sure we always start working off of the actual SemanticModel instead of a speculative SemanticModel.
Debug.Assert(!semanticModel.IsSpeculativeSemanticModel);
var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
#if DEBUG
var originalDocHasErrors = await document.HasAnyErrorsAsync(cancellationToken).ConfigureAwait(false);
#endif
var reduced = await this.ReduceCoreAsync(document, spanList, optionSet, reducers, cancellationToken).ConfigureAwait(false);
if (reduced != document)
{
#if DEBUG
if (!originalDocHasErrors)
{
await reduced.VerifyNoErrorsAsync("Error introduced by Simplification Service", cancellationToken).ConfigureAwait(false);
}
#endif
}
return reduced;
}
}
private async Task<Document> ReduceCoreAsync(
Document document,
ImmutableArray<TextSpan> spans,
OptionSet optionSet,
ImmutableArray<AbstractReducer> reducers,
CancellationToken cancellationToken)
{
// Create a simple interval tree for simplification spans.
var spansTree = new SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>(new TextSpanIntervalIntrospector(), spans);
bool isNodeOrTokenOutsideSimplifySpans(SyntaxNodeOrToken nodeOrToken) =>
!spansTree.HasIntervalThatOverlapsWith(nodeOrToken.FullSpan.Start, nodeOrToken.FullSpan.Length);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
// prep namespace imports marked for simplification
var removeIfUnusedAnnotation = new SyntaxAnnotation();
var originalRoot = root;
root = PrepareNamespaceImportsForRemovalIfUnused(document, root, removeIfUnusedAnnotation, isNodeOrTokenOutsideSimplifySpans);
var hasImportsToSimplify = root != originalRoot;
if (hasImportsToSimplify)
{
document = document.WithSyntaxRoot(root);
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
}
// Get the list of syntax nodes and tokens that need to be reduced.
var nodesAndTokensToReduce = this.GetNodesAndTokensToReduce(root, isNodeOrTokenOutsideSimplifySpans);
if (nodesAndTokensToReduce.Any())
{
if (reducers.IsDefault)
{
reducers = _reducers;
}
// Take out any reducers that don't even apply with the current
// set of users options. i.e. no point running 'reduce to var'
// if the user doesn't have the 'var' preference set.
reducers = reducers.WhereAsArray(r => r.IsApplicable(optionSet));
var reducedNodesMap = new ConcurrentDictionary<SyntaxNode, SyntaxNode>();
var reducedTokensMap = new ConcurrentDictionary<SyntaxToken, SyntaxToken>();
// Reduce all the nodesAndTokensToReduce using the given reducers/rewriters and
// store the reduced nodes and/or tokens in the reduced nodes/tokens maps.
// Note that this method doesn't update the original syntax tree.
await this.ReduceAsync(document, root, nodesAndTokensToReduce, reducers, optionSet, semanticModel, reducedNodesMap, reducedTokensMap, cancellationToken).ConfigureAwait(false);
if (reducedNodesMap.Any() || reducedTokensMap.Any())
{
// Update the syntax tree with reduced nodes/tokens.
root = root.ReplaceSyntax(
nodes: reducedNodesMap.Keys,
computeReplacementNode: (o, n) => TransformReducedNode(reducedNodesMap[o], n),
tokens: reducedTokensMap.Keys,
computeReplacementToken: (o, n) => reducedTokensMap[o],
trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(),
computeReplacementTrivia: null);
document = document.WithSyntaxRoot(root);
}
}
if (hasImportsToSimplify)
{
// remove any unused namespace imports that were marked for simplification
document = await this.RemoveUnusedNamespaceImportsAsync(document, removeIfUnusedAnnotation, cancellationToken).ConfigureAwait(false);
}
return document;
}
private Task ReduceAsync(
Document document,
SyntaxNode root,
ImmutableArray<NodeOrTokenToReduce> nodesAndTokensToReduce,
ImmutableArray<AbstractReducer> reducers,
OptionSet optionSet,
SemanticModel semanticModel,
ConcurrentDictionary<SyntaxNode, SyntaxNode> reducedNodesMap,
ConcurrentDictionary<SyntaxToken, SyntaxToken> reducedTokensMap,
CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(nodesAndTokensToReduce.Any());
// Reduce each node or token in the given list by running it through each reducer.
var simplifyTasks = new Task[nodesAndTokensToReduce.Length];
for (var i = 0; i < nodesAndTokensToReduce.Length; i++)
{
var nodeOrTokenToReduce = nodesAndTokensToReduce[i];
simplifyTasks[i] = Task.Run(async () =>
{
var nodeOrToken = nodeOrTokenToReduce.OriginalNodeOrToken;
var simplifyAllDescendants = nodeOrTokenToReduce.SimplifyAllDescendants;
var semanticModelForReduce = semanticModel;
var currentNodeOrToken = nodeOrTokenToReduce.NodeOrToken;
var isNode = nodeOrToken.IsNode;
foreach (var reducer in reducers)
{
cancellationToken.ThrowIfCancellationRequested();
using var rewriter = reducer.GetOrCreateRewriter();
rewriter.Initialize(document.Project.ParseOptions, optionSet, cancellationToken);
do
{
if (currentNodeOrToken.SyntaxTree != semanticModelForReduce.SyntaxTree)
{
// currentNodeOrToken was simplified either by a previous reducer or
// a previous iteration of the current reducer.
// Create a speculative semantic model for the simplified node for semantic queries.
// Certain node kinds (expressions/statements) require non-null parent nodes during simplification.
// However, the reduced nodes haven't been parented yet, so do the required parenting using the original node's parent.
if (currentNodeOrToken.Parent == null &&
nodeOrToken.Parent != null &&
(currentNodeOrToken.IsToken ||
currentNodeOrToken.AsNode() is TExpressionSyntax ||
currentNodeOrToken.AsNode() is TStatementSyntax ||
currentNodeOrToken.AsNode() is TCrefSyntax))
{
var annotation = new SyntaxAnnotation();
currentNodeOrToken = currentNodeOrToken.WithAdditionalAnnotations(annotation);
var replacedParent = isNode ?
nodeOrToken.Parent.ReplaceNode(nodeOrToken.AsNode(), currentNodeOrToken.AsNode()) :
nodeOrToken.Parent.ReplaceToken(nodeOrToken.AsToken(), currentNodeOrToken.AsToken());
currentNodeOrToken = replacedParent
.ChildNodesAndTokens()
.Single(c => c.HasAnnotation(annotation));
}
if (isNode)
{
var currentNode = currentNodeOrToken.AsNode();
if (this.CanNodeBeSimplifiedWithoutSpeculation(nodeOrToken.AsNode()))
{
// Since this node cannot be speculated, we are replacing the Document with the changes and get a new SemanticModel
var marker = new SyntaxAnnotation();
var newRoot = root.ReplaceNode(nodeOrToken.AsNode(), currentNode.WithAdditionalAnnotations(marker));
var newDocument = document.WithSyntaxRoot(newRoot);
semanticModelForReduce = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
newRoot = await semanticModelForReduce.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
currentNodeOrToken = newRoot.DescendantNodes().Single(c => c.HasAnnotation(marker));
}
else
{
// Create speculative semantic model for simplified node.
semanticModelForReduce = GetSpeculativeSemanticModel(ref currentNode, semanticModel, nodeOrToken.AsNode());
currentNodeOrToken = currentNode;
}
}
}
// Reduce the current node or token.
currentNodeOrToken = rewriter.VisitNodeOrToken(currentNodeOrToken, semanticModelForReduce, simplifyAllDescendants);
}
while (rewriter.HasMoreWork);
}
// If nodeOrToken was simplified, add it to the appropriate dictionary of replaced nodes/tokens.
if (currentNodeOrToken != nodeOrToken)
{
if (isNode)
{
reducedNodesMap[nodeOrToken.AsNode()] = currentNodeOrToken.AsNode();
}
else
{
reducedTokensMap[nodeOrToken.AsToken()] = currentNodeOrToken.AsToken();
}
}
}, cancellationToken);
}
return Task.WhenAll(simplifyTasks);
}
// find any namespace imports / using directives marked for simplification in the specified spans
// and add removeIfUnused annotation
private static SyntaxNode PrepareNamespaceImportsForRemovalIfUnused(
Document document,
SyntaxNode root,
SyntaxAnnotation removeIfUnusedAnnotation,
Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpan)
{
var gen = SyntaxGenerator.GetGenerator(document);
var importsToSimplify = root.DescendantNodes().Where(n =>
!isNodeOrTokenOutsideSimplifySpan(n)
&& gen.GetDeclarationKind(n) == DeclarationKind.NamespaceImport
&& n.HasAnnotation(Simplifier.Annotation));
return root.ReplaceNodes(importsToSimplify, (o, r) => r.WithAdditionalAnnotations(removeIfUnusedAnnotation));
}
private async Task<Document> RemoveUnusedNamespaceImportsAsync(
Document document,
SyntaxAnnotation removeIfUnusedAnnotation,
CancellationToken cancellationToken)
{
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var addedImports = root.GetAnnotatedNodes(removeIfUnusedAnnotation);
var unusedImports = new HashSet<SyntaxNode>();
this.GetUnusedNamespaceImports(model, unusedImports, cancellationToken);
// only remove the unused imports that we added
unusedImports.IntersectWith(addedImports);
if (unusedImports.Count > 0)
{
var gen = SyntaxGenerator.GetGenerator(document);
var newRoot = gen.RemoveNodes(root, unusedImports);
return document.WithSyntaxRoot(newRoot);
}
else
{
return document;
}
}
protected abstract void GetUnusedNamespaceImports(SemanticModel model, HashSet<SyntaxNode> namespaceImports, CancellationToken cancellationToken);
}
internal struct NodeOrTokenToReduce
{
public readonly SyntaxNodeOrToken NodeOrToken;
public readonly bool SimplifyAllDescendants;
public readonly SyntaxNodeOrToken OriginalNodeOrToken;
public readonly bool CanBeSpeculated;
public NodeOrTokenToReduce(SyntaxNodeOrToken nodeOrToken, bool simplifyAllDescendants, SyntaxNodeOrToken originalNodeOrToken, bool canBeSpeculated = true)
{
this.NodeOrToken = nodeOrToken;
this.SimplifyAllDescendants = simplifyAllDescendants;
this.OriginalNodeOrToken = originalNodeOrToken;
this.CanBeSpeculated = canBeSpeculated;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
#if DEBUG
using Microsoft.CodeAnalysis.Shared.Extensions;
#endif
namespace Microsoft.CodeAnalysis.Simplification
{
internal abstract class AbstractSimplificationService<TExpressionSyntax, TStatementSyntax, TCrefSyntax> : ISimplificationService
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TCrefSyntax : SyntaxNode
{
private ImmutableArray<AbstractReducer> _reducers;
protected AbstractSimplificationService(ImmutableArray<AbstractReducer> reducers)
=> _reducers = reducers;
protected abstract ImmutableArray<NodeOrTokenToReduce> GetNodesAndTokensToReduce(SyntaxNode root, Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpans);
protected abstract SemanticModel GetSpeculativeSemanticModel(ref SyntaxNode nodeToSpeculate, SemanticModel originalSemanticModel, SyntaxNode originalNode);
protected abstract bool CanNodeBeSimplifiedWithoutSpeculation(SyntaxNode node);
protected virtual SyntaxNode TransformReducedNode(SyntaxNode reducedNode, SyntaxNode originalNode)
=> reducedNode;
public abstract SyntaxNode Expand(SyntaxNode node, SemanticModel semanticModel, SyntaxAnnotation annotationForReplacedAliasIdentifier, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken);
public abstract SyntaxToken Expand(SyntaxToken token, SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, CancellationToken cancellationToken);
public async Task<Document> ReduceAsync(
Document document,
ImmutableArray<TextSpan> spans,
OptionSet optionSet = null,
ImmutableArray<AbstractReducer> reducers = default,
CancellationToken cancellationToken = default)
{
using (Logger.LogBlock(FunctionId.Simplifier_ReduceAsync, cancellationToken))
{
var spanList = spans.NullToEmpty();
// we have no span
if (!spanList.Any())
{
return document;
}
optionSet ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Chaining of the Speculative SemanticModel (i.e. Generating a speculative SemanticModel from an existing Speculative SemanticModel) is not supported
// Hence make sure we always start working off of the actual SemanticModel instead of a speculative SemanticModel.
Debug.Assert(!semanticModel.IsSpeculativeSemanticModel);
var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
#if DEBUG
var originalDocHasErrors = await document.HasAnyErrorsAsync(cancellationToken).ConfigureAwait(false);
#endif
var reduced = await this.ReduceCoreAsync(document, spanList, optionSet, reducers, cancellationToken).ConfigureAwait(false);
if (reduced != document)
{
#if DEBUG
if (!originalDocHasErrors)
{
await reduced.VerifyNoErrorsAsync("Error introduced by Simplification Service", cancellationToken).ConfigureAwait(false);
}
#endif
}
return reduced;
}
}
private async Task<Document> ReduceCoreAsync(
Document document,
ImmutableArray<TextSpan> spans,
OptionSet optionSet,
ImmutableArray<AbstractReducer> reducers,
CancellationToken cancellationToken)
{
// Create a simple interval tree for simplification spans.
var spansTree = new SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>(new TextSpanIntervalIntrospector(), spans);
bool isNodeOrTokenOutsideSimplifySpans(SyntaxNodeOrToken nodeOrToken) =>
!spansTree.HasIntervalThatOverlapsWith(nodeOrToken.FullSpan.Start, nodeOrToken.FullSpan.Length);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
// prep namespace imports marked for simplification
var removeIfUnusedAnnotation = new SyntaxAnnotation();
var originalRoot = root;
root = PrepareNamespaceImportsForRemovalIfUnused(document, root, removeIfUnusedAnnotation, isNodeOrTokenOutsideSimplifySpans);
var hasImportsToSimplify = root != originalRoot;
if (hasImportsToSimplify)
{
document = document.WithSyntaxRoot(root);
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
}
// Get the list of syntax nodes and tokens that need to be reduced.
var nodesAndTokensToReduce = this.GetNodesAndTokensToReduce(root, isNodeOrTokenOutsideSimplifySpans);
if (nodesAndTokensToReduce.Any())
{
if (reducers.IsDefault)
{
reducers = _reducers;
}
// Take out any reducers that don't even apply with the current
// set of users options. i.e. no point running 'reduce to var'
// if the user doesn't have the 'var' preference set.
reducers = reducers.WhereAsArray(r => r.IsApplicable(optionSet));
var reducedNodesMap = new ConcurrentDictionary<SyntaxNode, SyntaxNode>();
var reducedTokensMap = new ConcurrentDictionary<SyntaxToken, SyntaxToken>();
// Reduce all the nodesAndTokensToReduce using the given reducers/rewriters and
// store the reduced nodes and/or tokens in the reduced nodes/tokens maps.
// Note that this method doesn't update the original syntax tree.
await this.ReduceAsync(document, root, nodesAndTokensToReduce, reducers, optionSet, semanticModel, reducedNodesMap, reducedTokensMap, cancellationToken).ConfigureAwait(false);
if (reducedNodesMap.Any() || reducedTokensMap.Any())
{
// Update the syntax tree with reduced nodes/tokens.
root = root.ReplaceSyntax(
nodes: reducedNodesMap.Keys,
computeReplacementNode: (o, n) => TransformReducedNode(reducedNodesMap[o], n),
tokens: reducedTokensMap.Keys,
computeReplacementToken: (o, n) => reducedTokensMap[o],
trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(),
computeReplacementTrivia: null);
document = document.WithSyntaxRoot(root);
}
}
if (hasImportsToSimplify)
{
// remove any unused namespace imports that were marked for simplification
document = await this.RemoveUnusedNamespaceImportsAsync(document, removeIfUnusedAnnotation, cancellationToken).ConfigureAwait(false);
}
return document;
}
private Task ReduceAsync(
Document document,
SyntaxNode root,
ImmutableArray<NodeOrTokenToReduce> nodesAndTokensToReduce,
ImmutableArray<AbstractReducer> reducers,
OptionSet optionSet,
SemanticModel semanticModel,
ConcurrentDictionary<SyntaxNode, SyntaxNode> reducedNodesMap,
ConcurrentDictionary<SyntaxToken, SyntaxToken> reducedTokensMap,
CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(nodesAndTokensToReduce.Any());
// Reduce each node or token in the given list by running it through each reducer.
var simplifyTasks = new Task[nodesAndTokensToReduce.Length];
for (var i = 0; i < nodesAndTokensToReduce.Length; i++)
{
var nodeOrTokenToReduce = nodesAndTokensToReduce[i];
simplifyTasks[i] = Task.Run(async () =>
{
var nodeOrToken = nodeOrTokenToReduce.OriginalNodeOrToken;
var simplifyAllDescendants = nodeOrTokenToReduce.SimplifyAllDescendants;
var semanticModelForReduce = semanticModel;
var currentNodeOrToken = nodeOrTokenToReduce.NodeOrToken;
var isNode = nodeOrToken.IsNode;
foreach (var reducer in reducers)
{
cancellationToken.ThrowIfCancellationRequested();
using var rewriter = reducer.GetOrCreateRewriter();
rewriter.Initialize(document.Project.ParseOptions, optionSet, cancellationToken);
do
{
if (currentNodeOrToken.SyntaxTree != semanticModelForReduce.SyntaxTree)
{
// currentNodeOrToken was simplified either by a previous reducer or
// a previous iteration of the current reducer.
// Create a speculative semantic model for the simplified node for semantic queries.
// Certain node kinds (expressions/statements) require non-null parent nodes during simplification.
// However, the reduced nodes haven't been parented yet, so do the required parenting using the original node's parent.
if (currentNodeOrToken.Parent == null &&
nodeOrToken.Parent != null &&
(currentNodeOrToken.IsToken ||
currentNodeOrToken.AsNode() is TExpressionSyntax ||
currentNodeOrToken.AsNode() is TStatementSyntax ||
currentNodeOrToken.AsNode() is TCrefSyntax))
{
var annotation = new SyntaxAnnotation();
currentNodeOrToken = currentNodeOrToken.WithAdditionalAnnotations(annotation);
var replacedParent = isNode ?
nodeOrToken.Parent.ReplaceNode(nodeOrToken.AsNode(), currentNodeOrToken.AsNode()) :
nodeOrToken.Parent.ReplaceToken(nodeOrToken.AsToken(), currentNodeOrToken.AsToken());
currentNodeOrToken = replacedParent
.ChildNodesAndTokens()
.Single(c => c.HasAnnotation(annotation));
}
if (isNode)
{
var currentNode = currentNodeOrToken.AsNode();
if (this.CanNodeBeSimplifiedWithoutSpeculation(nodeOrToken.AsNode()))
{
// Since this node cannot be speculated, we are replacing the Document with the changes and get a new SemanticModel
var marker = new SyntaxAnnotation();
var newRoot = root.ReplaceNode(nodeOrToken.AsNode(), currentNode.WithAdditionalAnnotations(marker));
var newDocument = document.WithSyntaxRoot(newRoot);
semanticModelForReduce = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
newRoot = await semanticModelForReduce.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
currentNodeOrToken = newRoot.DescendantNodes().Single(c => c.HasAnnotation(marker));
}
else
{
// Create speculative semantic model for simplified node.
semanticModelForReduce = GetSpeculativeSemanticModel(ref currentNode, semanticModel, nodeOrToken.AsNode());
currentNodeOrToken = currentNode;
}
}
}
// Reduce the current node or token.
currentNodeOrToken = rewriter.VisitNodeOrToken(currentNodeOrToken, semanticModelForReduce, simplifyAllDescendants);
}
while (rewriter.HasMoreWork);
}
// If nodeOrToken was simplified, add it to the appropriate dictionary of replaced nodes/tokens.
if (currentNodeOrToken != nodeOrToken)
{
if (isNode)
{
reducedNodesMap[nodeOrToken.AsNode()] = currentNodeOrToken.AsNode();
}
else
{
reducedTokensMap[nodeOrToken.AsToken()] = currentNodeOrToken.AsToken();
}
}
}, cancellationToken);
}
return Task.WhenAll(simplifyTasks);
}
// find any namespace imports / using directives marked for simplification in the specified spans
// and add removeIfUnused annotation
private static SyntaxNode PrepareNamespaceImportsForRemovalIfUnused(
Document document,
SyntaxNode root,
SyntaxAnnotation removeIfUnusedAnnotation,
Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpan)
{
var gen = SyntaxGenerator.GetGenerator(document);
var importsToSimplify = root.DescendantNodes().Where(n =>
!isNodeOrTokenOutsideSimplifySpan(n)
&& gen.GetDeclarationKind(n) == DeclarationKind.NamespaceImport
&& n.HasAnnotation(Simplifier.Annotation));
return root.ReplaceNodes(importsToSimplify, (o, r) => r.WithAdditionalAnnotations(removeIfUnusedAnnotation));
}
private async Task<Document> RemoveUnusedNamespaceImportsAsync(
Document document,
SyntaxAnnotation removeIfUnusedAnnotation,
CancellationToken cancellationToken)
{
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var addedImports = root.GetAnnotatedNodes(removeIfUnusedAnnotation);
var unusedImports = new HashSet<SyntaxNode>();
this.GetUnusedNamespaceImports(model, unusedImports, cancellationToken);
// only remove the unused imports that we added
unusedImports.IntersectWith(addedImports);
if (unusedImports.Count > 0)
{
var gen = SyntaxGenerator.GetGenerator(document);
var newRoot = gen.RemoveNodes(root, unusedImports);
return document.WithSyntaxRoot(newRoot);
}
else
{
return document;
}
}
protected abstract void GetUnusedNamespaceImports(SemanticModel model, HashSet<SyntaxNode> namespaceImports, CancellationToken cancellationToken);
}
internal struct NodeOrTokenToReduce
{
public readonly SyntaxNodeOrToken NodeOrToken;
public readonly bool SimplifyAllDescendants;
public readonly SyntaxNodeOrToken OriginalNodeOrToken;
public readonly bool CanBeSpeculated;
public NodeOrTokenToReduce(SyntaxNodeOrToken nodeOrToken, bool simplifyAllDescendants, SyntaxNodeOrToken originalNodeOrToken, bool canBeSpeculated = true)
{
this.NodeOrToken = nodeOrToken;
this.SimplifyAllDescendants = simplifyAllDescendants;
this.OriginalNodeOrToken = originalNodeOrToken;
this.CanBeSpeculated = canBeSpeculated;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundInterpolatedStringExpression.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundInterpolatedStringExpression
Public ReadOnly Property HasInterpolations As Boolean
Get
' $""
' $"TEXT"
' $"TEXT{INTERPOLATION}..."
' $"{INTERPOLATION}"
' $"{INTERPOLATION}TEXT..."
' The parser will never produce two adjacent text elements so in for non-synthetic trees this should only need
' to examine the first two elements at most.
For Each item In Contents
If item.Kind = BoundKind.Interpolation Then Return True
Next
Return False
End Get
End Property
Public ReadOnly Property IsEmpty() As Boolean
Get
Return Contents.Length = 0
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(Type.SpecialType = SpecialType.System_String)
Debug.Assert(Not Contents.Where(Function(content) content.Kind <> BoundKind.Interpolation AndAlso content.Kind <> BoundKind.Literal).Any())
End Sub
#End If
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundInterpolatedStringExpression
Public ReadOnly Property HasInterpolations As Boolean
Get
' $""
' $"TEXT"
' $"TEXT{INTERPOLATION}..."
' $"{INTERPOLATION}"
' $"{INTERPOLATION}TEXT..."
' The parser will never produce two adjacent text elements so in for non-synthetic trees this should only need
' to examine the first two elements at most.
For Each item In Contents
If item.Kind = BoundKind.Interpolation Then Return True
Next
Return False
End Get
End Property
Public ReadOnly Property IsEmpty() As Boolean
Get
Return Contents.Length = 0
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(Type.SpecialType = SpecialType.System_String)
Debug.Assert(Not Contents.Where(Function(content) content.Kind <> BoundKind.Interpolation AndAlso content.Kind <> BoundKind.Literal).Any())
End Sub
#End If
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/Symbols/Attributes/AttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Reflection;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents an attribute applied to a Symbol.
/// </summary>
internal abstract partial class CSharpAttributeData : AttributeData
{
private ThreeState _lazyIsSecurityAttribute = ThreeState.Unknown;
/// <summary>
/// Gets the attribute class being applied.
/// </summary>
public new abstract NamedTypeSymbol? AttributeClass { get; }
/// <summary>
/// Gets the constructor used in this application of the attribute.
/// </summary>
public new abstract MethodSymbol? AttributeConstructor { get; }
/// <summary>
/// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols.
/// </summary>
public new abstract SyntaxReference? ApplicationSyntaxReference { get; }
// Overridden to be able to apply MemberNotNull to the new members
[MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))]
internal override bool HasErrors
{
get
{
var hasErrors = base.HasErrors;
if (!hasErrors)
{
Debug.Assert(AttributeClass is not null);
Debug.Assert(AttributeConstructor is not null);
}
return hasErrors;
}
}
/// <summary>
/// Gets the list of constructor arguments specified by this application of the attribute. This list contains both positional arguments
/// and named arguments that are formal parameters to the constructor.
/// </summary>
public new IEnumerable<TypedConstant> ConstructorArguments
{
get { return this.CommonConstructorArguments; }
}
/// <summary>
/// Gets the list of named field or property value arguments specified by this application of the attribute.
/// </summary>
public new IEnumerable<KeyValuePair<string, TypedConstant>> NamedArguments
{
get { return this.CommonNamedArguments; }
}
/// <summary>
/// Compares the namespace and type name with the attribute's namespace and type name.
/// Returns true if they are the same.
/// </summary>
internal virtual bool IsTargetAttribute(string namespaceName, string typeName)
{
Debug.Assert(this.AttributeClass is object);
if (!this.AttributeClass.Name.Equals(typeName))
{
return false;
}
if (this.AttributeClass.IsErrorType() && !(this.AttributeClass is MissingMetadataTypeSymbol))
{
// Can't guarantee complete name information.
return false;
}
return this.AttributeClass.HasNameQualifier(namespaceName);
}
internal bool IsTargetAttribute(Symbol targetSymbol, AttributeDescription description)
{
return GetTargetAttributeSignatureIndex(targetSymbol, description) != -1;
}
internal abstract int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description);
/// <summary>
/// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description
/// and the attribute description has a signature with parameter count equal to the given attribute syntax's argument list count.
/// NOTE: We don't allow early decoded attributes to have optional parameters.
/// </summary>
internal static bool IsTargetEarlyAttribute(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax, AttributeDescription description)
{
Debug.Assert(!attributeType.IsErrorType());
int argumentCount = (attributeSyntax.ArgumentList != null) ?
attributeSyntax.ArgumentList.Arguments.Count<AttributeArgumentSyntax>((arg) => arg.NameEquals == null) :
0;
return AttributeData.IsTargetEarlyAttribute(attributeType, argumentCount, description);
}
// Security attributes, i.e. attributes derived from well-known SecurityAttribute, are matched by type, not constructor signature.
internal bool IsSecurityAttribute(CSharpCompilation compilation)
{
if (_lazyIsSecurityAttribute == ThreeState.Unknown)
{
Debug.Assert(!this.HasErrors);
// CLI spec (Partition II Metadata), section 21.11 "DeclSecurity : 0x0E" states:
// SPEC: If the attribute's type is derived (directly or indirectly) from System.Security.Permissions.SecurityAttribute then
// SPEC: it is a security custom attribute and requires special treatment.
// NOTE: The native C# compiler violates the above and considers only those attributes whose type derives from
// NOTE: System.Security.Permissions.CodeAccessSecurityAttribute as security custom attributes.
// NOTE: We will follow the specification.
// NOTE: See Devdiv Bug #13762 "Custom security attributes deriving from SecurityAttribute are not treated as security attributes" for details.
// Well-known type SecurityAttribute is optional.
// Native compiler doesn't generate a use-site error if it is not found, we do the same.
var wellKnownType = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAttribute);
Debug.Assert(AttributeClass is object);
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
_lazyIsSecurityAttribute = AttributeClass.IsDerivedFrom(wellKnownType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo).ToThreeState();
}
return _lazyIsSecurityAttribute.Value();
}
// for testing and debugging only
/// <summary>
/// Returns the <see cref="System.String"/> that represents the current AttributeData.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current AttributeData.</returns>
public override string? ToString()
{
if (this.AttributeClass is object)
{
string className = this.AttributeClass.ToDisplayString(SymbolDisplayFormat.TestFormat);
if (!this.CommonConstructorArguments.Any() & !this.CommonNamedArguments.Any())
{
return className;
}
var pooledStrbuilder = PooledStringBuilder.GetInstance();
StringBuilder stringBuilder = pooledStrbuilder.Builder;
stringBuilder.Append(className);
stringBuilder.Append("(");
bool first = true;
foreach (var constructorArgument in this.CommonConstructorArguments)
{
if (!first)
{
stringBuilder.Append(", ");
}
stringBuilder.Append(constructorArgument.ToCSharpString());
first = false;
}
foreach (var namedArgument in this.CommonNamedArguments)
{
if (!first)
{
stringBuilder.Append(", ");
}
stringBuilder.Append(namedArgument.Key);
stringBuilder.Append(" = ");
stringBuilder.Append(namedArgument.Value.ToCSharpString());
first = false;
}
stringBuilder.Append(")");
return pooledStrbuilder.ToStringAndFree();
}
return base.ToString();
}
#region AttributeData Implementation
/// <summary>
/// Gets the attribute class being applied as an <see cref="INamedTypeSymbol"/>
/// </summary>
protected override INamedTypeSymbol? CommonAttributeClass
{
get { return this.AttributeClass.GetPublicSymbol(); }
}
/// <summary>
/// Gets the constructor used in this application of the attribute as an <see cref="IMethodSymbol"/>.
/// </summary>
protected override IMethodSymbol? CommonAttributeConstructor
{
get { return this.AttributeConstructor.GetPublicSymbol(); }
}
/// <summary>
/// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols.
/// </summary>
protected override SyntaxReference? CommonApplicationSyntaxReference
{
get { return this.ApplicationSyntaxReference; }
}
#endregion
#region Attribute Decoding
internal void DecodeSecurityAttribute<T>(Symbol targetSymbol, CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, ISecurityAttributeTarget, new()
{
Debug.Assert(!this.HasErrors);
Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag);
bool hasErrors;
DeclarativeSecurityAction action = DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, out hasErrors, (BindingDiagnosticBag)arguments.Diagnostics);
if (!hasErrors)
{
T data = arguments.GetOrCreateData<T>();
SecurityWellKnownAttributeData securityData = data.GetOrCreateData();
securityData.SetSecurityAttribute(arguments.Index, action, arguments.AttributesCount);
if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute))
{
string? resolvedPathForFixup = DecodePermissionSetAttribute(compilation, arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics);
if (resolvedPathForFixup != null)
{
securityData.SetPathForPermissionSetAttributeFixup(arguments.Index, resolvedPathForFixup, arguments.AttributesCount);
}
}
}
}
internal static void DecodeSkipLocalsInitAttribute<T>(CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, ISkipLocalsInitAttributeTarget, new()
{
arguments.GetOrCreateData<T>().HasSkipLocalsInitAttribute = true;
if (!compilation.Options.AllowUnsafe)
{
Debug.Assert(arguments.AttributeSyntaxOpt is object);
((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_IllegalUnsafe, arguments.AttributeSyntaxOpt.Location);
}
}
internal static void DecodeMemberNotNullAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new()
{
var value = arguments.Attribute.CommonConstructorArguments[0];
if (value.IsNull)
{
return;
}
if (value.Kind != TypedConstantKind.Array)
{
string? memberName = value.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
arguments.GetOrCreateData<T>().AddNotNullMember(memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
else
{
var builder = ArrayBuilder<string>.GetInstance();
foreach (var member in value.Values)
{
var memberName = member.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
builder.Add(memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
arguments.GetOrCreateData<T>().AddNotNullMember(builder);
builder.Free();
}
}
private static void ReportBadNotNullMemberIfNeeded(TypeSymbol type, DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, string memberName)
{
foreach (Symbol foundMember in type.GetMembers(memberName))
{
if (foundMember.Kind == SymbolKind.Field || foundMember.Kind == SymbolKind.Property)
{
return;
}
}
Debug.Assert(arguments.AttributeSyntaxOpt is object);
((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.WRN_MemberNotNullBadMember, arguments.AttributeSyntaxOpt.Location, memberName);
}
internal static void DecodeMemberNotNullWhenAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new()
{
var value = arguments.Attribute.CommonConstructorArguments[1];
if (value.IsNull)
{
return;
}
var sense = arguments.Attribute.CommonConstructorArguments[0].DecodeValue<bool>(SpecialType.System_Boolean);
if (value.Kind != TypedConstantKind.Array)
{
var memberName = value.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
else
{
var builder = ArrayBuilder<string>.GetInstance();
foreach (var member in value.Values)
{
var memberName = member.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
builder.Add(memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, builder);
builder.Free();
}
}
private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax? nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)targetSymbol != null);
Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method);
Debug.Assert(this.IsSecurityAttribute(compilation));
var ctorArgs = this.CommonConstructorArguments;
if (!ctorArgs.Any())
{
// NOTE: Security custom attributes must have a valid SecurityAction as its first argument, we have none here.
// NOTE: Ideally, we should always generate 'CS7048: First argument to a security attribute must be a valid SecurityAction' for this case.
// NOTE: However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses
// NOTE: SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case.
// BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments,
// it doesn't quite do this correctly
// The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first
// attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute.
// We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior.
if (this.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute))
{
hasErrors = false;
return DeclarativeSecurityAction.LinkDemand;
}
}
else
{
TypedConstant firstArg = ctorArgs.First();
var firstArgType = (TypeSymbol?)firstArg.TypeInternal;
if (firstArgType is object && firstArgType.Equals(compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction)))
{
return DecodeSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, out hasErrors);
}
}
// CS7048: First argument to a security attribute must be a valid SecurityAction
diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, nodeOpt != null ? nodeOpt.Name.Location : NoLocation.Singleton);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
private DeclarativeSecurityAction DecodeSecurityAction(TypedConstant typedValue, Symbol targetSymbol, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics, out bool hasErrors)
{
Debug.Assert((object)targetSymbol != null);
Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method);
Debug.Assert(typedValue.ValueInternal is object);
int securityAction = (int)typedValue.ValueInternal;
bool isPermissionRequestAction;
switch (securityAction)
{
case (int)DeclarativeSecurityAction.InheritanceDemand:
case (int)DeclarativeSecurityAction.LinkDemand:
if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute))
{
// CS7052: SecurityAction value '{0}' is invalid for PrincipalPermission attribute
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_PrincipalPermissionInvalidAction, syntaxLocation, displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
isPermissionRequestAction = false;
break;
case 1:
// Native compiler allows security action value 1 for security attributes on types/methods, even though there is no corresponding field in System.Security.Permissions.SecurityAction enum.
// We will maintain compatibility.
case (int)DeclarativeSecurityAction.Assert:
case (int)DeclarativeSecurityAction.Demand:
case (int)DeclarativeSecurityAction.PermitOnly:
case (int)DeclarativeSecurityAction.Deny:
isPermissionRequestAction = false;
break;
case (int)DeclarativeSecurityAction.RequestMinimum:
case (int)DeclarativeSecurityAction.RequestOptional:
case (int)DeclarativeSecurityAction.RequestRefuse:
isPermissionRequestAction = true;
break;
default:
{
// CS7049: Security attribute '{0}' has an invalid SecurityAction value '{1}'
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidAction, syntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "", displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
}
// Validate security action for symbol kind
if (isPermissionRequestAction)
{
if (targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method)
{
// Types and methods cannot take permission requests.
// CS7051: SecurityAction value '{0}' is invalid for security attributes applied to a type or a method
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, syntaxLocation, displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
}
else
{
if (targetSymbol.Kind == SymbolKind.Assembly)
{
// Assemblies cannot take declarative security.
// CS7050: SecurityAction value '{0}' is invalid for security attributes applied to an assembly
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, syntaxLocation, displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
}
hasErrors = false;
return (DeclarativeSecurityAction)securityAction;
}
private static Location GetSecurityAttributeActionSyntaxLocation(AttributeSyntax? nodeOpt, TypedConstant typedValue, out object displayString)
{
if (nodeOpt == null)
{
displayString = "";
return NoLocation.Singleton;
}
var argList = nodeOpt.ArgumentList;
if (argList == null || argList.Arguments.IsEmpty())
{
// Optional SecurityAction parameter with default value.
displayString = (FormattableString)$"{typedValue.ValueInternal}";
return nodeOpt.Location;
}
AttributeArgumentSyntax argSyntax = argList.Arguments[0];
displayString = argSyntax.ToString();
return argSyntax.Location;
}
/// <summary>
/// Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen.
/// </summary>
/// <remarks>
/// PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument.
/// Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute.
/// It involves following steps:
/// 1) Verifying that the specified file name resolves to a valid path.
/// 2) Reading the contents of the file into a byte array.
/// 3) Convert each byte in the file content into two bytes containing hexadecimal characters.
/// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above.
///
/// Step 1) is performed in this method, i.e. during binding.
/// Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass.
/// See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps.
/// </remarks>
/// <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns>
private string? DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
string? resolvedFilePath = null;
var namedArgs = this.CommonNamedArguments;
if (namedArgs.Length == 1)
{
var namedArg = namedArgs[0];
Debug.Assert(AttributeClass is object);
NamedTypeSymbol attrType = this.AttributeClass;
string filePropName = PermissionSetAttributeWithFileReference.FilePropertyName;
string hexPropName = PermissionSetAttributeWithFileReference.HexPropertyName;
if (namedArg.Key == filePropName &&
PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName))
{
// resolve file prop path
var fileName = (string?)namedArg.Value.ValueInternal;
var resolver = compilation.Options.XmlReferenceResolver;
resolvedFilePath = (resolver != null && fileName != null) ? resolver.ResolveReference(fileName, baseFilePath: null) : null;
if (resolvedFilePath == null)
{
// CS7053: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute
Location argSyntaxLocation = nodeOpt?.GetNamedArgumentSyntax(filePropName)?.Location ?? NoLocation.Singleton;
diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, fileName ?? "<null>", filePropName);
}
else if (!PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName))
{
// PermissionSetAttribute was defined in user source, but doesn't have the required Hex property.
// Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception.
// We instead skip the fixup and emit the file property.
// CONSIDER: We may want to consider taking a breaking change and generating an error here.
return null;
}
}
}
return resolvedFilePath;
}
// This method checks if the given PermissionSetAttribute type has a property member with the given propName which is writable, non-generic, public and of string type.
private static bool PermissionSetAttributeTypeHasRequiredProperty(NamedTypeSymbol permissionSetType, string propName)
{
var members = permissionSetType.GetMembers(propName);
if (members.Length == 1 && members[0].Kind == SymbolKind.Property)
{
var property = (PropertySymbol)members[0];
if (property.TypeWithAnnotations.HasType && property.Type.SpecialType == SpecialType.System_String &&
property.DeclaredAccessibility == Accessibility.Public && property.GetMemberArity() == 0 &&
(object)property.SetMethod != null && property.SetMethod.DeclaredAccessibility == Accessibility.Public)
{
return true;
}
}
return false;
}
internal void DecodeClassInterfaceAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
TypedConstant ctorArgument = this.CommonConstructorArguments[0];
Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive);
ClassInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ?
ctorArgument.DecodeValue<ClassInterfaceType>(SpecialType.System_Enum) :
(ClassInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16);
switch (interfaceType)
{
case ClassInterfaceType.None:
case Cci.Constants.ClassInterfaceType_AutoDispatch:
case Cci.Constants.ClassInterfaceType_AutoDual:
break;
default:
// CS0591: Invalid value for argument to '{0}' attribute
Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "");
break;
}
}
internal void DecodeInterfaceTypeAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
TypedConstant ctorArgument = this.CommonConstructorArguments[0];
Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive);
ComInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ?
ctorArgument.DecodeValue<ComInterfaceType>(SpecialType.System_Enum) :
(ComInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16);
switch (interfaceType)
{
case Cci.Constants.ComInterfaceType_InterfaceIsDual:
case Cci.Constants.ComInterfaceType_InterfaceIsIDispatch:
case ComInterfaceType.InterfaceIsIInspectable:
case ComInterfaceType.InterfaceIsIUnknown:
break;
default:
// CS0591: Invalid value for argument to '{0}' attribute
CSharpSyntaxNode attributeArgumentSyntax = this.GetAttributeArgumentSyntax(0, node);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName());
break;
}
}
internal string DecodeGuidAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
var guidString = (string?)this.CommonConstructorArguments[0].ValueInternal;
// Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens)
Guid guid;
if (!Guid.TryParseExact(guidString, "D", out guid))
{
// CS0591: Invalid value for argument to '{0}' attribute
Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "");
guidString = String.Empty;
}
return guidString!;
}
private protected sealed override bool IsStringProperty(string memberName)
{
if (AttributeClass is object)
{
foreach (var member in AttributeClass.GetMembers(memberName))
{
if (member is PropertySymbol { Type: { SpecialType: SpecialType.System_String } })
{
return true;
}
}
}
return false;
}
#endregion
/// <summary>
/// This method determines if an applied attribute must be emitted.
/// Some attributes appear in symbol model to reflect the source code,
/// but should not be emitted.
/// </summary>
internal bool ShouldEmitAttribute(Symbol target, bool isReturnType, bool emittingAssemblyAttributesInNetModule)
{
Debug.Assert(target is SourceAssemblySymbol || target.ContainingAssembly is SourceAssemblySymbol);
if (HasErrors)
{
throw ExceptionUtilities.Unreachable;
}
// Attribute type is conditionally omitted if both the following are true:
// (a) It has at least one applied/inherited conditional attribute AND
// (b) None of conditional symbols are defined in the source file where the given attribute was defined.
if (this.IsConditionallyOmitted)
{
return false;
}
switch (target.Kind)
{
case SymbolKind.Assembly:
if ((!emittingAssemblyAttributesInNetModule &&
(IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) ||
IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) ||
IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) ||
IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) ||
IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) ||
IsSecurityAttribute(target.DeclaringCompilation))
{
return false;
}
break;
case SymbolKind.Event:
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute))
{
return false;
}
break;
case SymbolKind.Field:
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) ||
IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) ||
IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute))
{
return false;
}
break;
case SymbolKind.Method:
if (isReturnType)
{
if (IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute))
{
return false;
}
}
else
{
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) ||
IsTargetAttribute(target, AttributeDescription.DllImportAttribute) ||
IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) ||
IsTargetAttribute(target, AttributeDescription.DynamicSecurityMethodAttribute) ||
IsSecurityAttribute(target.DeclaringCompilation))
{
return false;
}
}
break;
case SymbolKind.NetModule:
// Note that DefaultCharSetAttribute is emitted to metadata, although it's also decoded and used when emitting P/Invoke
break;
case SymbolKind.NamedType:
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.ComImportAttribute) ||
IsTargetAttribute(target, AttributeDescription.SerializableAttribute) ||
IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) ||
IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) ||
IsSecurityAttribute(target.DeclaringCompilation))
{
return false;
}
break;
case SymbolKind.Parameter:
if (IsTargetAttribute(target, AttributeDescription.OptionalAttribute) ||
IsTargetAttribute(target, AttributeDescription.DefaultParameterValueAttribute) ||
IsTargetAttribute(target, AttributeDescription.InAttribute) ||
IsTargetAttribute(target, AttributeDescription.OutAttribute) ||
IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute))
{
return false;
}
break;
case SymbolKind.Property:
if (IsTargetAttribute(target, AttributeDescription.IndexerNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.DisallowNullAttribute) ||
IsTargetAttribute(target, AttributeDescription.AllowNullAttribute) ||
IsTargetAttribute(target, AttributeDescription.MaybeNullAttribute) ||
IsTargetAttribute(target, AttributeDescription.NotNullAttribute))
{
return false;
}
break;
}
return true;
}
}
internal static class AttributeDataExtensions
{
internal static int IndexOfAttribute(this ImmutableArray<CSharpAttributeData> attributes, Symbol targetSymbol, AttributeDescription description)
{
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i].IsTargetAttribute(targetSymbol, description))
{
return i;
}
}
return -1;
}
internal static CSharpSyntaxNode GetAttributeArgumentSyntax(this AttributeData attribute, int parameterIndex, AttributeSyntax attributeSyntax)
{
Debug.Assert(attribute is SourceAttributeData);
return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntax);
}
internal static string? DecodeNotNullIfNotNullAttribute(this CSharpAttributeData attribute)
{
var arguments = attribute.CommonConstructorArguments;
return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_String, out string? value) ? value : null;
}
internal static Location GetAttributeArgumentSyntaxLocation(this AttributeData attribute, int parameterIndex, AttributeSyntax? attributeSyntaxOpt)
{
if (attributeSyntaxOpt == null)
{
return NoLocation.Singleton;
}
Debug.Assert(attribute is SourceAttributeData);
return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntaxOpt).Location;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Reflection;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents an attribute applied to a Symbol.
/// </summary>
internal abstract partial class CSharpAttributeData : AttributeData
{
private ThreeState _lazyIsSecurityAttribute = ThreeState.Unknown;
/// <summary>
/// Gets the attribute class being applied.
/// </summary>
public new abstract NamedTypeSymbol? AttributeClass { get; }
/// <summary>
/// Gets the constructor used in this application of the attribute.
/// </summary>
public new abstract MethodSymbol? AttributeConstructor { get; }
/// <summary>
/// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols.
/// </summary>
public new abstract SyntaxReference? ApplicationSyntaxReference { get; }
// Overridden to be able to apply MemberNotNull to the new members
[MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))]
internal override bool HasErrors
{
get
{
var hasErrors = base.HasErrors;
if (!hasErrors)
{
Debug.Assert(AttributeClass is not null);
Debug.Assert(AttributeConstructor is not null);
}
return hasErrors;
}
}
/// <summary>
/// Gets the list of constructor arguments specified by this application of the attribute. This list contains both positional arguments
/// and named arguments that are formal parameters to the constructor.
/// </summary>
public new IEnumerable<TypedConstant> ConstructorArguments
{
get { return this.CommonConstructorArguments; }
}
/// <summary>
/// Gets the list of named field or property value arguments specified by this application of the attribute.
/// </summary>
public new IEnumerable<KeyValuePair<string, TypedConstant>> NamedArguments
{
get { return this.CommonNamedArguments; }
}
/// <summary>
/// Compares the namespace and type name with the attribute's namespace and type name.
/// Returns true if they are the same.
/// </summary>
internal virtual bool IsTargetAttribute(string namespaceName, string typeName)
{
Debug.Assert(this.AttributeClass is object);
if (!this.AttributeClass.Name.Equals(typeName))
{
return false;
}
if (this.AttributeClass.IsErrorType() && !(this.AttributeClass is MissingMetadataTypeSymbol))
{
// Can't guarantee complete name information.
return false;
}
return this.AttributeClass.HasNameQualifier(namespaceName);
}
internal bool IsTargetAttribute(Symbol targetSymbol, AttributeDescription description)
{
return GetTargetAttributeSignatureIndex(targetSymbol, description) != -1;
}
internal abstract int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description);
/// <summary>
/// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description
/// and the attribute description has a signature with parameter count equal to the given attribute syntax's argument list count.
/// NOTE: We don't allow early decoded attributes to have optional parameters.
/// </summary>
internal static bool IsTargetEarlyAttribute(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax, AttributeDescription description)
{
Debug.Assert(!attributeType.IsErrorType());
int argumentCount = (attributeSyntax.ArgumentList != null) ?
attributeSyntax.ArgumentList.Arguments.Count<AttributeArgumentSyntax>((arg) => arg.NameEquals == null) :
0;
return AttributeData.IsTargetEarlyAttribute(attributeType, argumentCount, description);
}
// Security attributes, i.e. attributes derived from well-known SecurityAttribute, are matched by type, not constructor signature.
internal bool IsSecurityAttribute(CSharpCompilation compilation)
{
if (_lazyIsSecurityAttribute == ThreeState.Unknown)
{
Debug.Assert(!this.HasErrors);
// CLI spec (Partition II Metadata), section 21.11 "DeclSecurity : 0x0E" states:
// SPEC: If the attribute's type is derived (directly or indirectly) from System.Security.Permissions.SecurityAttribute then
// SPEC: it is a security custom attribute and requires special treatment.
// NOTE: The native C# compiler violates the above and considers only those attributes whose type derives from
// NOTE: System.Security.Permissions.CodeAccessSecurityAttribute as security custom attributes.
// NOTE: We will follow the specification.
// NOTE: See Devdiv Bug #13762 "Custom security attributes deriving from SecurityAttribute are not treated as security attributes" for details.
// Well-known type SecurityAttribute is optional.
// Native compiler doesn't generate a use-site error if it is not found, we do the same.
var wellKnownType = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAttribute);
Debug.Assert(AttributeClass is object);
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
_lazyIsSecurityAttribute = AttributeClass.IsDerivedFrom(wellKnownType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo).ToThreeState();
}
return _lazyIsSecurityAttribute.Value();
}
// for testing and debugging only
/// <summary>
/// Returns the <see cref="System.String"/> that represents the current AttributeData.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current AttributeData.</returns>
public override string? ToString()
{
if (this.AttributeClass is object)
{
string className = this.AttributeClass.ToDisplayString(SymbolDisplayFormat.TestFormat);
if (!this.CommonConstructorArguments.Any() & !this.CommonNamedArguments.Any())
{
return className;
}
var pooledStrbuilder = PooledStringBuilder.GetInstance();
StringBuilder stringBuilder = pooledStrbuilder.Builder;
stringBuilder.Append(className);
stringBuilder.Append("(");
bool first = true;
foreach (var constructorArgument in this.CommonConstructorArguments)
{
if (!first)
{
stringBuilder.Append(", ");
}
stringBuilder.Append(constructorArgument.ToCSharpString());
first = false;
}
foreach (var namedArgument in this.CommonNamedArguments)
{
if (!first)
{
stringBuilder.Append(", ");
}
stringBuilder.Append(namedArgument.Key);
stringBuilder.Append(" = ");
stringBuilder.Append(namedArgument.Value.ToCSharpString());
first = false;
}
stringBuilder.Append(")");
return pooledStrbuilder.ToStringAndFree();
}
return base.ToString();
}
#region AttributeData Implementation
/// <summary>
/// Gets the attribute class being applied as an <see cref="INamedTypeSymbol"/>
/// </summary>
protected override INamedTypeSymbol? CommonAttributeClass
{
get { return this.AttributeClass.GetPublicSymbol(); }
}
/// <summary>
/// Gets the constructor used in this application of the attribute as an <see cref="IMethodSymbol"/>.
/// </summary>
protected override IMethodSymbol? CommonAttributeConstructor
{
get { return this.AttributeConstructor.GetPublicSymbol(); }
}
/// <summary>
/// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols.
/// </summary>
protected override SyntaxReference? CommonApplicationSyntaxReference
{
get { return this.ApplicationSyntaxReference; }
}
#endregion
#region Attribute Decoding
internal void DecodeSecurityAttribute<T>(Symbol targetSymbol, CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, ISecurityAttributeTarget, new()
{
Debug.Assert(!this.HasErrors);
Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag);
bool hasErrors;
DeclarativeSecurityAction action = DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, out hasErrors, (BindingDiagnosticBag)arguments.Diagnostics);
if (!hasErrors)
{
T data = arguments.GetOrCreateData<T>();
SecurityWellKnownAttributeData securityData = data.GetOrCreateData();
securityData.SetSecurityAttribute(arguments.Index, action, arguments.AttributesCount);
if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute))
{
string? resolvedPathForFixup = DecodePermissionSetAttribute(compilation, arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics);
if (resolvedPathForFixup != null)
{
securityData.SetPathForPermissionSetAttributeFixup(arguments.Index, resolvedPathForFixup, arguments.AttributesCount);
}
}
}
}
internal static void DecodeSkipLocalsInitAttribute<T>(CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, ISkipLocalsInitAttributeTarget, new()
{
arguments.GetOrCreateData<T>().HasSkipLocalsInitAttribute = true;
if (!compilation.Options.AllowUnsafe)
{
Debug.Assert(arguments.AttributeSyntaxOpt is object);
((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_IllegalUnsafe, arguments.AttributeSyntaxOpt.Location);
}
}
internal static void DecodeMemberNotNullAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new()
{
var value = arguments.Attribute.CommonConstructorArguments[0];
if (value.IsNull)
{
return;
}
if (value.Kind != TypedConstantKind.Array)
{
string? memberName = value.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
arguments.GetOrCreateData<T>().AddNotNullMember(memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
else
{
var builder = ArrayBuilder<string>.GetInstance();
foreach (var member in value.Values)
{
var memberName = member.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
builder.Add(memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
arguments.GetOrCreateData<T>().AddNotNullMember(builder);
builder.Free();
}
}
private static void ReportBadNotNullMemberIfNeeded(TypeSymbol type, DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, string memberName)
{
foreach (Symbol foundMember in type.GetMembers(memberName))
{
if (foundMember.Kind == SymbolKind.Field || foundMember.Kind == SymbolKind.Property)
{
return;
}
}
Debug.Assert(arguments.AttributeSyntaxOpt is object);
((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.WRN_MemberNotNullBadMember, arguments.AttributeSyntaxOpt.Location, memberName);
}
internal static void DecodeMemberNotNullWhenAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new()
{
var value = arguments.Attribute.CommonConstructorArguments[1];
if (value.IsNull)
{
return;
}
var sense = arguments.Attribute.CommonConstructorArguments[0].DecodeValue<bool>(SpecialType.System_Boolean);
if (value.Kind != TypedConstantKind.Array)
{
var memberName = value.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
else
{
var builder = ArrayBuilder<string>.GetInstance();
foreach (var member in value.Values)
{
var memberName = member.DecodeValue<string>(SpecialType.System_String);
if (memberName is object)
{
builder.Add(memberName);
ReportBadNotNullMemberIfNeeded(type, arguments, memberName);
}
}
arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, builder);
builder.Free();
}
}
private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax? nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics)
{
Debug.Assert((object)targetSymbol != null);
Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method);
Debug.Assert(this.IsSecurityAttribute(compilation));
var ctorArgs = this.CommonConstructorArguments;
if (!ctorArgs.Any())
{
// NOTE: Security custom attributes must have a valid SecurityAction as its first argument, we have none here.
// NOTE: Ideally, we should always generate 'CS7048: First argument to a security attribute must be a valid SecurityAction' for this case.
// NOTE: However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses
// NOTE: SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case.
// BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments,
// it doesn't quite do this correctly
// The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first
// attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute.
// We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior.
if (this.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute))
{
hasErrors = false;
return DeclarativeSecurityAction.LinkDemand;
}
}
else
{
TypedConstant firstArg = ctorArgs.First();
var firstArgType = (TypeSymbol?)firstArg.TypeInternal;
if (firstArgType is object && firstArgType.Equals(compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction)))
{
return DecodeSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, out hasErrors);
}
}
// CS7048: First argument to a security attribute must be a valid SecurityAction
diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, nodeOpt != null ? nodeOpt.Name.Location : NoLocation.Singleton);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
private DeclarativeSecurityAction DecodeSecurityAction(TypedConstant typedValue, Symbol targetSymbol, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics, out bool hasErrors)
{
Debug.Assert((object)targetSymbol != null);
Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method);
Debug.Assert(typedValue.ValueInternal is object);
int securityAction = (int)typedValue.ValueInternal;
bool isPermissionRequestAction;
switch (securityAction)
{
case (int)DeclarativeSecurityAction.InheritanceDemand:
case (int)DeclarativeSecurityAction.LinkDemand:
if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute))
{
// CS7052: SecurityAction value '{0}' is invalid for PrincipalPermission attribute
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_PrincipalPermissionInvalidAction, syntaxLocation, displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
isPermissionRequestAction = false;
break;
case 1:
// Native compiler allows security action value 1 for security attributes on types/methods, even though there is no corresponding field in System.Security.Permissions.SecurityAction enum.
// We will maintain compatibility.
case (int)DeclarativeSecurityAction.Assert:
case (int)DeclarativeSecurityAction.Demand:
case (int)DeclarativeSecurityAction.PermitOnly:
case (int)DeclarativeSecurityAction.Deny:
isPermissionRequestAction = false;
break;
case (int)DeclarativeSecurityAction.RequestMinimum:
case (int)DeclarativeSecurityAction.RequestOptional:
case (int)DeclarativeSecurityAction.RequestRefuse:
isPermissionRequestAction = true;
break;
default:
{
// CS7049: Security attribute '{0}' has an invalid SecurityAction value '{1}'
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidAction, syntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "", displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
}
// Validate security action for symbol kind
if (isPermissionRequestAction)
{
if (targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method)
{
// Types and methods cannot take permission requests.
// CS7051: SecurityAction value '{0}' is invalid for security attributes applied to a type or a method
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, syntaxLocation, displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
}
else
{
if (targetSymbol.Kind == SymbolKind.Assembly)
{
// Assemblies cannot take declarative security.
// CS7050: SecurityAction value '{0}' is invalid for security attributes applied to an assembly
object displayString;
Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString);
diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, syntaxLocation, displayString);
hasErrors = true;
return DeclarativeSecurityAction.None;
}
}
hasErrors = false;
return (DeclarativeSecurityAction)securityAction;
}
private static Location GetSecurityAttributeActionSyntaxLocation(AttributeSyntax? nodeOpt, TypedConstant typedValue, out object displayString)
{
if (nodeOpt == null)
{
displayString = "";
return NoLocation.Singleton;
}
var argList = nodeOpt.ArgumentList;
if (argList == null || argList.Arguments.IsEmpty())
{
// Optional SecurityAction parameter with default value.
displayString = (FormattableString)$"{typedValue.ValueInternal}";
return nodeOpt.Location;
}
AttributeArgumentSyntax argSyntax = argList.Arguments[0];
displayString = argSyntax.ToString();
return argSyntax.Location;
}
/// <summary>
/// Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen.
/// </summary>
/// <remarks>
/// PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument.
/// Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute.
/// It involves following steps:
/// 1) Verifying that the specified file name resolves to a valid path.
/// 2) Reading the contents of the file into a byte array.
/// 3) Convert each byte in the file content into two bytes containing hexadecimal characters.
/// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above.
///
/// Step 1) is performed in this method, i.e. during binding.
/// Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass.
/// See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps.
/// </remarks>
/// <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns>
private string? DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
string? resolvedFilePath = null;
var namedArgs = this.CommonNamedArguments;
if (namedArgs.Length == 1)
{
var namedArg = namedArgs[0];
Debug.Assert(AttributeClass is object);
NamedTypeSymbol attrType = this.AttributeClass;
string filePropName = PermissionSetAttributeWithFileReference.FilePropertyName;
string hexPropName = PermissionSetAttributeWithFileReference.HexPropertyName;
if (namedArg.Key == filePropName &&
PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName))
{
// resolve file prop path
var fileName = (string?)namedArg.Value.ValueInternal;
var resolver = compilation.Options.XmlReferenceResolver;
resolvedFilePath = (resolver != null && fileName != null) ? resolver.ResolveReference(fileName, baseFilePath: null) : null;
if (resolvedFilePath == null)
{
// CS7053: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute
Location argSyntaxLocation = nodeOpt?.GetNamedArgumentSyntax(filePropName)?.Location ?? NoLocation.Singleton;
diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, fileName ?? "<null>", filePropName);
}
else if (!PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName))
{
// PermissionSetAttribute was defined in user source, but doesn't have the required Hex property.
// Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception.
// We instead skip the fixup and emit the file property.
// CONSIDER: We may want to consider taking a breaking change and generating an error here.
return null;
}
}
}
return resolvedFilePath;
}
// This method checks if the given PermissionSetAttribute type has a property member with the given propName which is writable, non-generic, public and of string type.
private static bool PermissionSetAttributeTypeHasRequiredProperty(NamedTypeSymbol permissionSetType, string propName)
{
var members = permissionSetType.GetMembers(propName);
if (members.Length == 1 && members[0].Kind == SymbolKind.Property)
{
var property = (PropertySymbol)members[0];
if (property.TypeWithAnnotations.HasType && property.Type.SpecialType == SpecialType.System_String &&
property.DeclaredAccessibility == Accessibility.Public && property.GetMemberArity() == 0 &&
(object)property.SetMethod != null && property.SetMethod.DeclaredAccessibility == Accessibility.Public)
{
return true;
}
}
return false;
}
internal void DecodeClassInterfaceAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
TypedConstant ctorArgument = this.CommonConstructorArguments[0];
Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive);
ClassInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ?
ctorArgument.DecodeValue<ClassInterfaceType>(SpecialType.System_Enum) :
(ClassInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16);
switch (interfaceType)
{
case ClassInterfaceType.None:
case Cci.Constants.ClassInterfaceType_AutoDispatch:
case Cci.Constants.ClassInterfaceType_AutoDual:
break;
default:
// CS0591: Invalid value for argument to '{0}' attribute
Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "");
break;
}
}
internal void DecodeInterfaceTypeAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
TypedConstant ctorArgument = this.CommonConstructorArguments[0];
Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive);
ComInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ?
ctorArgument.DecodeValue<ComInterfaceType>(SpecialType.System_Enum) :
(ComInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16);
switch (interfaceType)
{
case Cci.Constants.ComInterfaceType_InterfaceIsDual:
case Cci.Constants.ComInterfaceType_InterfaceIsIDispatch:
case ComInterfaceType.InterfaceIsIInspectable:
case ComInterfaceType.InterfaceIsIUnknown:
break;
default:
// CS0591: Invalid value for argument to '{0}' attribute
CSharpSyntaxNode attributeArgumentSyntax = this.GetAttributeArgumentSyntax(0, node);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName());
break;
}
}
internal string DecodeGuidAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!this.HasErrors);
var guidString = (string?)this.CommonConstructorArguments[0].ValueInternal;
// Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens)
Guid guid;
if (!Guid.TryParseExact(guidString, "D", out guid))
{
// CS0591: Invalid value for argument to '{0}' attribute
Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt);
diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "");
guidString = String.Empty;
}
return guidString!;
}
private protected sealed override bool IsStringProperty(string memberName)
{
if (AttributeClass is object)
{
foreach (var member in AttributeClass.GetMembers(memberName))
{
if (member is PropertySymbol { Type: { SpecialType: SpecialType.System_String } })
{
return true;
}
}
}
return false;
}
#endregion
/// <summary>
/// This method determines if an applied attribute must be emitted.
/// Some attributes appear in symbol model to reflect the source code,
/// but should not be emitted.
/// </summary>
internal bool ShouldEmitAttribute(Symbol target, bool isReturnType, bool emittingAssemblyAttributesInNetModule)
{
Debug.Assert(target is SourceAssemblySymbol || target.ContainingAssembly is SourceAssemblySymbol);
if (HasErrors)
{
throw ExceptionUtilities.Unreachable;
}
// Attribute type is conditionally omitted if both the following are true:
// (a) It has at least one applied/inherited conditional attribute AND
// (b) None of conditional symbols are defined in the source file where the given attribute was defined.
if (this.IsConditionallyOmitted)
{
return false;
}
switch (target.Kind)
{
case SymbolKind.Assembly:
if ((!emittingAssemblyAttributesInNetModule &&
(IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) ||
IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) ||
IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) ||
IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) ||
IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) ||
IsSecurityAttribute(target.DeclaringCompilation))
{
return false;
}
break;
case SymbolKind.Event:
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute))
{
return false;
}
break;
case SymbolKind.Field:
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) ||
IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) ||
IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute))
{
return false;
}
break;
case SymbolKind.Method:
if (isReturnType)
{
if (IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute))
{
return false;
}
}
else
{
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) ||
IsTargetAttribute(target, AttributeDescription.DllImportAttribute) ||
IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) ||
IsTargetAttribute(target, AttributeDescription.DynamicSecurityMethodAttribute) ||
IsSecurityAttribute(target.DeclaringCompilation))
{
return false;
}
}
break;
case SymbolKind.NetModule:
// Note that DefaultCharSetAttribute is emitted to metadata, although it's also decoded and used when emitting P/Invoke
break;
case SymbolKind.NamedType:
if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.ComImportAttribute) ||
IsTargetAttribute(target, AttributeDescription.SerializableAttribute) ||
IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) ||
IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) ||
IsSecurityAttribute(target.DeclaringCompilation))
{
return false;
}
break;
case SymbolKind.Parameter:
if (IsTargetAttribute(target, AttributeDescription.OptionalAttribute) ||
IsTargetAttribute(target, AttributeDescription.DefaultParameterValueAttribute) ||
IsTargetAttribute(target, AttributeDescription.InAttribute) ||
IsTargetAttribute(target, AttributeDescription.OutAttribute) ||
IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute))
{
return false;
}
break;
case SymbolKind.Property:
if (IsTargetAttribute(target, AttributeDescription.IndexerNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) ||
IsTargetAttribute(target, AttributeDescription.DisallowNullAttribute) ||
IsTargetAttribute(target, AttributeDescription.AllowNullAttribute) ||
IsTargetAttribute(target, AttributeDescription.MaybeNullAttribute) ||
IsTargetAttribute(target, AttributeDescription.NotNullAttribute))
{
return false;
}
break;
}
return true;
}
}
internal static class AttributeDataExtensions
{
internal static int IndexOfAttribute(this ImmutableArray<CSharpAttributeData> attributes, Symbol targetSymbol, AttributeDescription description)
{
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i].IsTargetAttribute(targetSymbol, description))
{
return i;
}
}
return -1;
}
internal static CSharpSyntaxNode GetAttributeArgumentSyntax(this AttributeData attribute, int parameterIndex, AttributeSyntax attributeSyntax)
{
Debug.Assert(attribute is SourceAttributeData);
return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntax);
}
internal static string? DecodeNotNullIfNotNullAttribute(this CSharpAttributeData attribute)
{
var arguments = attribute.CommonConstructorArguments;
return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_String, out string? value) ? value : null;
}
internal static Location GetAttributeArgumentSyntaxLocation(this AttributeData attribute, int parameterIndex, AttributeSyntax? attributeSyntaxOpt)
{
if (attributeSyntaxOpt == null)
{
return NoLocation.Singleton;
}
Debug.Assert(attribute is SourceAttributeData);
return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntaxOpt).Location;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharpTest/CodeActions/ReplaceMethodWithProperty/ReplaceMethodWithPropertyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.ReplaceMethodWithProperty;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ReplaceMethodWithProperty
{
public class ReplaceMethodWithPropertyTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new ReplaceMethodWithPropertyCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithGetName()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithoutGetName()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]Goo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(6034, "https://github.com/dotnet/roslyn/issues/6034")]
public async Task TestMethodWithArrowBody()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo() => 0;
}",
@"class C
{
int Goo
{
get
{
return 0;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithoutBody()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo();
}",
@"class C
{
int Goo { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithModifiers()
{
await TestWithAllCodeStyleOff(
@"class C
{
public static int [||]GetGoo()
{
}
}",
@"class C
{
public static int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithAttributes()
{
await TestWithAllCodeStyleOff(
@"class C
{
[A]
int [||]GetGoo()
{
}
}",
@"class C
{
[A]
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrivia_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
}",
@"class C
{
// Goo
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrailingTrivia()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetP();
bool M()
{
return GetP() == 0;
}
}",
@"class C
{
int P { get; }
bool M()
{
return P == 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestDelegateWithTrailingTrivia()
{
await TestWithAllCodeStyleOff(
@"delegate int Mdelegate();
class C
{
int [||]GetP() => 0;
void M()
{
Mdelegate del = new Mdelegate(GetP );
}
}",
@"delegate int Mdelegate();
class C
{
int P
{
get
{
return 0;
}
}
void M()
{
Mdelegate del = new Mdelegate({|Conflict:P|} );
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIndentation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}",
@"class C
{
int Goo
{
get
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod1()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
int [||]GetGoo()
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
}
#endif
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod2()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
int [||]GetGoo()
{
}
void SetGoo(int val)
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
}
void SetGoo(int val)
{
}
#endif
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod3()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
int [||]GetGoo()
{
}
void SetGoo(int val)
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
set
{
}
}
#endif
}", index: 1);
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod4()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
void SetGoo(int val)
{
}
int [||]GetGoo()
{
}
#endif
}",
@"class C
{
#if true
void SetGoo(int val)
{
}
int Goo
{
get
{
}
}
#endif
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod5()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
void SetGoo(int val)
{
}
int [||]GetGoo()
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
set
{
}
}
#endif
}", index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrivia_2()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
// SetGoo
void SetGoo(int i)
{
}
}",
@"class C
{
// Goo
// SetGoo
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]I.GetGoo()
{
}
}",
@"class C
{
int I.Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_2()
{
await TestWithAllCodeStyleOff(
@"interface I
{
int GetGoo();
}
class C : I
{
int [||]I.GetGoo()
{
}
}",
@"interface I
{
int Goo { get; }
}
class C : I
{
int I.Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_3()
{
await TestWithAllCodeStyleOff(
@"interface I
{
int [||]GetGoo();
}
class C : I
{
int I.GetGoo()
{
}
}",
@"interface I
{
int Goo { get; }
}
class C : I
{
int I.Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestInAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[At[||]tr]
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestInMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int GetGoo()
{
[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVoidMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void [||]GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestAsyncMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
async Task [||]GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestGenericMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo<T>()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExtensionMethod()
{
await TestMissingInRegularAndScriptAsync(
@"static class C
{
int [||]GetGoo(this int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithParameters_1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithParameters_2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo(int i = 0)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestNotInSignature_1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[At[||]tr]
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestNotInSignature_2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int GetGoo()
{
[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceNotInMethod()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
var x = GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
var x = Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceSimpleInvocation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
var x = GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
var x = Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceMemberAccessInvocation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
var x = this.GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
var x = this.Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceBindingMemberInvocation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
C x;
var v = x?.GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
C x;
var v = x?.Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceInMethod()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
return GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
return Goo;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOverride()
{
await TestWithAllCodeStyleOff(
@"class C
{
public virtual int [||]GetGoo()
{
}
}
class D : C
{
public override int GetGoo()
{
}
}",
@"class C
{
public virtual int Goo
{
get
{
}
}
}
class D : C
{
public override int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReference_NonInvoked()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void Bar()
{
Action<int> i = GetGoo;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
}
void Bar()
{
Action<int> i = {|Conflict:Goo|};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReference_ImplicitReference()
{
await TestWithAllCodeStyleOff(
@"using System.Collections;
class C
{
public IEnumerator [||]GetEnumerator()
{
}
void Bar()
{
foreach (var x in this)
{
}
}
}",
@"using System.Collections;
class C
{
public IEnumerator Enumerator
{
get
{
}
}
void Bar()
{
{|Conflict:foreach (var x in this)
{
}|}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSetReference_NonInvoked()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
}
void Bar()
{
Action<int> i = SetGoo;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
void Bar()
{
Action<int> i = {|Conflict:Goo|};
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_SetterAccessibility()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
public int [||]GetGoo()
{
}
private void SetGoo(int i)
{
}
}",
@"using System;
class C
{
public int Goo
{
get
{
}
private set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_ExpressionBodies()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo() => 0;
void SetGoo(int i) => Bar();
}",
@"using System;
class C
{
int Goo
{
get
{
return 0;
}
set
{
Bar();
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_GetInSetReference()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
}
void Bar()
{
SetGoo(GetGoo() + 1);
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
void Bar()
{
Goo = Goo + 1;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_UpdateSetParameterName_1()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
v = i;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
v = value;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_UpdateSetParameterName_2()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int value)
{
v = value;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
v = value;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_SetReferenceInSetter()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
SetGoo(i - 1);
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
Goo = value - 1;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVirtualGetWithOverride_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
protected virtual int [||]GetGoo()
{
}
}
class D : C
{
protected override int GetGoo()
{
}
}",
@"class C
{
protected virtual int Goo
{
get
{
}
}
}
class D : C
{
protected override int Goo
{
get
{
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVirtualGetWithOverride_2()
{
await TestWithAllCodeStyleOff(
@"class C
{
protected virtual int [||]GetGoo()
{
}
}
class D : C
{
protected override int GetGoo()
{
base.GetGoo();
}
}",
@"class C
{
protected virtual int Goo
{
get
{
}
}
}
class D : C
{
protected override int Goo
{
get
{
base.Goo;
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestGetWithInterface()
{
await TestWithAllCodeStyleOff(
@"interface I
{
int [||]GetGoo();
}
class C : I
{
public int GetGoo()
{
}
}",
@"interface I
{
int Goo { get; }
}
class C : I
{
public int Goo
{
get
{
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestWithPartialClasses()
{
await TestWithAllCodeStyleOff(
@"partial class C
{
int [||]GetGoo()
{
}
}
partial class C
{
void SetGoo(int i)
{
}
}",
@"partial class C
{
int Goo
{
get
{
}
set
{
}
}
}
partial class C
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSetCaseInsensitive()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]getGoo()
{
}
void setGoo(int i)
{
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task Tuple()
{
await TestWithAllCodeStyleOff(
@"class C
{
(int, string) [||]GetGoo()
{
}
}",
@"class C
{
(int, string) Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task Tuple_GetAndSet()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
(int, string) [||]getGoo()
{
}
void setGoo((int, string) i)
{
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"using System;
class C
{
(int, string) Goo
{
get
{
}
set
{
}
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TupleWithNames_GetAndSet()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
(int a, string b) [||]getGoo()
{
}
void setGoo((int a, string b) i)
{
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"using System;
class C
{
(int a, string b) Goo
{
get
{
}
set
{
}
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TupleWithDifferentNames_GetAndSet()
{
// Cannot refactor tuples with different names together
await TestActionCountAsync(
@"using System;
class C
{
(int a, string b) [||]getGoo()
{
}
void setGoo((int c, string d) i)
{
}
}",
count: 1, new TestParameters(options: AllCodeStyleOff));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
// SetGoo
void SetGoo(out int i)
{
}
void Test()
{
SetGoo(out int i);
}
}",
@"class C
{
// Goo
int Goo
{
get
{
}
}
// SetGoo
void SetGoo(out int i)
{
}
void Test()
{
SetGoo(out int i);
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_2()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
// SetGoo
void SetGoo(int i)
{
}
void Test()
{
SetGoo(out int i);
}
}",
@"class C
{
// Goo
// SetGoo
int Goo
{
get
{
}
set
{
}
}
void Test()
{
{|Conflict:Goo|}(out int i);
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_3()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
// Goo
int GetGoo()
{
}
// SetGoo
void [||]SetGoo(out int i)
{
}
void Test()
{
SetGoo(out int i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_4()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
// Goo
int [||]GetGoo(out int i)
{
}
// SetGoo
void SetGoo(out int i, int j)
{
}
void Test()
{
var y = GetGoo(out int i);
}
}");
}
[WorkItem(14327, "https://github.com/dotnet/roslyn/issues/14327")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateChainedGet1()
{
await TestWithAllCodeStyleOff(
@"public class Goo
{
public Goo()
{
Goo value = GetValue().GetValue();
}
public Goo [||]GetValue()
{
return this;
}
}",
@"public class Goo
{
public Goo()
{
Goo value = Value.Value;
}
public Goo Value
{
get
{
return this;
}
}
}");
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
}",
@"class C
{
int Goo { get => 1; }
}", options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
}",
@"class C
{
int Goo => 1;
}", options: PreferExpressionBodiedProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
}",
@"class C
{
int Goo => 1;
}", options: PreferExpressionBodiedAccessorsAndProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
void SetGoo(int i)
{
_i = i;
}
}",
@"class C
{
int Goo { get => 1; set => _i = value; }
}",
index: 1,
options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle5()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
void SetGoo(int i)
{
_i = i;
}
}",
@"class C
{
int Goo
{
get
{
return 1;
}
set
{
_i = value;
}
}
}",
index: 1,
options: PreferExpressionBodiedProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle6()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
void SetGoo(int i)
{
_i = i;
}
}",
@"class C
{
int Goo { get => 1; set => _i = value; }
}",
index: 1,
options: PreferExpressionBodiedAccessorsAndProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle7()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() => 0;
}",
@"class C
{
int Goo => 0;
}", options: PreferExpressionBodiedProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle8()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() => 0;
}",
@"class C
{
int Goo { get => 0; }
}", options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle9()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() => throw e;
}",
@"class C
{
int Goo { get => throw e; }
}", options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle10()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() { throw e; }
}",
@"class C
{
int Goo => throw e;
}", options: PreferExpressionBodiedProperties);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsSingleLine()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() { throw e; }
}",
@"class C
{
int Goo => throw e;
}", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsNotSingleLine()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() { throw e +
e; }
}",
@"class C
{
int Goo
{
get
{
throw e +
e;
}
}
}", options: new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement },
});
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceImplementation()
{
await TestWithAllCodeStyleOff(
@"interface IGoo
{
int [||]GetGoo();
}
class C : IGoo
{
int IGoo.GetGoo()
{
throw new System.NotImplementedException();
}
}",
@"interface IGoo
{
int Goo { get; }
}
class C : IGoo
{
int IGoo.Goo
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(443523, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestSystemObjectMetadataOverride()
{
await TestMissingAsync(
@"class C
{
public override string [||]ToString()
{
}
}");
}
[WorkItem(443523, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMetadataOverride()
{
await TestWithAllCodeStyleOff(
@"class C : System.Type
{
public override int [||]GetArrayRank()
{
}
}",
@"class C : System.Type
{
public override int {|Warning:ArrayRank|}
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfTopLevelNullableIsDifferent_GetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private string? name;
public void SetName(string name)
{
this.name = name;
}
public string? [||]GetName()
{
return this.name;
}
}",
@"
#nullable enable
class C
{
private string? name;
public void SetName(string name)
{
this.name = name;
}
public string? Name => this.name;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfTopLevelNullableIsDifferent_SetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private string? name;
public void SetName(string? name)
{
this.name = name;
}
public string [||]GetName()
{
return this.name ?? """";
}
}",
@"
#nullable enable
class C
{
private string? name;
public void SetName(string? name)
{
this.name = name;
}
public string Name => this.name ?? """";
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfNestedNullableIsDifferent_GetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string> names)
{
this.names = names;
}
public IEnumerable<string?> [||]GetNames()
{
return this.names;
}
}",
@"
#nullable enable
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string> names)
{
this.names = names;
}
public IEnumerable<string?> Names => this.names;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfNestedNullableIsDifferent_SetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
using System.Linq;
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string?> names)
{
this.names = names;
}
public IEnumerable<string> [||]GetNames()
{
return this.names.Where(n => n is object);
}
}",
@"
#nullable enable
using System.Linq;
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string?> names)
{
this.names = names;
}
public IEnumerable<string> Names => this.names.Where(n => n is object);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task NullabilityOfFieldDifferentThanProperty()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private string name;
public string? [||]GetName()
{
return name;
}
}",
@"
#nullable enable
class C
{
private string name;
public string? Name => name;
}");
}
[WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUnsafeGetter()
{
await TestInRegularAndScriptAsync(
@"class C
{
public unsafe int [||]GetP()
{
return 0;
}
public void SetP(int value)
{ }
}",
@"class C
{
public unsafe int P
{
get => 0;
set
{ }
}
}", index: 1);
}
[WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUnsafeSetter()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]GetP()
{
return 0;
}
public unsafe void SetP(int value)
{ }
}",
@"class C
{
public unsafe int P
{
get => 0;
set
{ }
}
}", index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestAtStartOfMethod()
{
await TestWithAllCodeStyleOff(
@"class C
{
[||]int GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_OnSameLine()
{
await TestWithAllCodeStyleOff(
@"class C
{
[||] int GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_OnPreviousLine()
{
await TestWithAllCodeStyleOff(
@"class C
{
[||]
int GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotMultipleLinesPrior()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[||]
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotBeforeAttributes()
{
await TestInRegularAndScript1Async(
@"class C
{
[||][A]
int GetGoo()
{
}
}",
@"class C
{
[A]
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotBeforeComments()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[||] /// <summary/>
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotInComment()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
/// [||]<summary/>
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(42699, "https://github.com/dotnet/roslyn/issues/42699")]
public async Task TestSameNameMemberAsProperty()
{
await TestInRegularAndScript1Async(
@"class C
{
int Goo;
[||]int GetGoo()
{
}
}",
@"class C
{
int Goo;
int Goo1
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(42698, "https://github.com/dotnet/roslyn/issues/42698")]
public async Task TestMethodWithTrivia_3()
{
await TestInRegularAndScript1Async(
@"class C
{
[||]int Goo() //Vital Comment
{
return 1;
}
}",
@"class C
{
//Vital Comment
int Goo => 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(42698, "https://github.com/dotnet/roslyn/issues/42698")]
public async Task TestMethodWithTrivia_4()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo() // Goo
{
}
void SetGoo(int i) // SetGoo
{
}
}",
@"class C
{
// Goo
// SetGoo
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
private async Task TestWithAllCodeStyleOff(
string initialMarkup, string expectedMarkup,
ParseOptions? parseOptions = null, int index = 0)
{
await TestAsync(
initialMarkup, expectedMarkup, parseOptions,
index: index,
options: AllCodeStyleOff);
}
private OptionsCollection AllCodeStyleOff
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
private OptionsCollection PreferExpressionBodiedAccessors
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
private OptionsCollection PreferExpressionBodiedProperties
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
};
private OptionsCollection PreferExpressionBodiedAccessorsAndProperties
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.ReplaceMethodWithProperty;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ReplaceMethodWithProperty
{
public class ReplaceMethodWithPropertyTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new ReplaceMethodWithPropertyCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithGetName()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithoutGetName()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]Goo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(6034, "https://github.com/dotnet/roslyn/issues/6034")]
public async Task TestMethodWithArrowBody()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo() => 0;
}",
@"class C
{
int Goo
{
get
{
return 0;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithoutBody()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo();
}",
@"class C
{
int Goo { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithModifiers()
{
await TestWithAllCodeStyleOff(
@"class C
{
public static int [||]GetGoo()
{
}
}",
@"class C
{
public static int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithAttributes()
{
await TestWithAllCodeStyleOff(
@"class C
{
[A]
int [||]GetGoo()
{
}
}",
@"class C
{
[A]
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrivia_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
}",
@"class C
{
// Goo
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrailingTrivia()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetP();
bool M()
{
return GetP() == 0;
}
}",
@"class C
{
int P { get; }
bool M()
{
return P == 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestDelegateWithTrailingTrivia()
{
await TestWithAllCodeStyleOff(
@"delegate int Mdelegate();
class C
{
int [||]GetP() => 0;
void M()
{
Mdelegate del = new Mdelegate(GetP );
}
}",
@"delegate int Mdelegate();
class C
{
int P
{
get
{
return 0;
}
}
void M()
{
Mdelegate del = new Mdelegate({|Conflict:P|} );
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIndentation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}",
@"class C
{
int Goo
{
get
{
int count;
foreach (var x in y)
{
count += bar;
}
return count;
}
}
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod1()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
int [||]GetGoo()
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
}
#endif
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod2()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
int [||]GetGoo()
{
}
void SetGoo(int val)
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
}
void SetGoo(int val)
{
}
#endif
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod3()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
int [||]GetGoo()
{
}
void SetGoo(int val)
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
set
{
}
}
#endif
}", index: 1);
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod4()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
void SetGoo(int val)
{
}
int [||]GetGoo()
{
}
#endif
}",
@"class C
{
#if true
void SetGoo(int val)
{
}
int Goo
{
get
{
}
}
#endif
}");
}
[WorkItem(21460, "https://github.com/dotnet/roslyn/issues/21460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestIfDefMethod5()
{
await TestWithAllCodeStyleOff(
@"class C
{
#if true
void SetGoo(int val)
{
}
int [||]GetGoo()
{
}
#endif
}",
@"class C
{
#if true
int Goo
{
get
{
}
set
{
}
}
#endif
}", index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithTrivia_2()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
// SetGoo
void SetGoo(int i)
{
}
}",
@"class C
{
// Goo
// SetGoo
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]I.GetGoo()
{
}
}",
@"class C
{
int I.Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_2()
{
await TestWithAllCodeStyleOff(
@"interface I
{
int GetGoo();
}
class C : I
{
int [||]I.GetGoo()
{
}
}",
@"interface I
{
int Goo { get; }
}
class C : I
{
int I.Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceMethod_3()
{
await TestWithAllCodeStyleOff(
@"interface I
{
int [||]GetGoo();
}
class C : I
{
int I.GetGoo()
{
}
}",
@"interface I
{
int Goo { get; }
}
class C : I
{
int I.Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestInAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[At[||]tr]
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestInMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int GetGoo()
{
[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVoidMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void [||]GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestAsyncMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
async Task [||]GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestGenericMethod()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo<T>()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExtensionMethod()
{
await TestMissingInRegularAndScriptAsync(
@"static class C
{
int [||]GetGoo(this int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithParameters_1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMethodWithParameters_2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo(int i = 0)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestNotInSignature_1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[At[||]tr]
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestNotInSignature_2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int GetGoo()
{
[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceNotInMethod()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
var x = GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
var x = Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceSimpleInvocation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
var x = GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
var x = Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceMemberAccessInvocation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
var x = this.GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
var x = this.Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceBindingMemberInvocation()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
}
void Bar()
{
C x;
var v = x?.GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
}
}
void Bar()
{
C x;
var v = x?.Goo;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReferenceInMethod()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo()
{
return GetGoo();
}
}",
@"class C
{
int Goo
{
get
{
return Goo;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOverride()
{
await TestWithAllCodeStyleOff(
@"class C
{
public virtual int [||]GetGoo()
{
}
}
class D : C
{
public override int GetGoo()
{
}
}",
@"class C
{
public virtual int Goo
{
get
{
}
}
}
class D : C
{
public override int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReference_NonInvoked()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void Bar()
{
Action<int> i = GetGoo;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
}
void Bar()
{
Action<int> i = {|Conflict:Goo|};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetReference_ImplicitReference()
{
await TestWithAllCodeStyleOff(
@"using System.Collections;
class C
{
public IEnumerator [||]GetEnumerator()
{
}
void Bar()
{
foreach (var x in this)
{
}
}
}",
@"using System.Collections;
class C
{
public IEnumerator Enumerator
{
get
{
}
}
void Bar()
{
{|Conflict:foreach (var x in this)
{
}|}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSetReference_NonInvoked()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
}
void Bar()
{
Action<int> i = SetGoo;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
void Bar()
{
Action<int> i = {|Conflict:Goo|};
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_SetterAccessibility()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
public int [||]GetGoo()
{
}
private void SetGoo(int i)
{
}
}",
@"using System;
class C
{
public int Goo
{
get
{
}
private set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_ExpressionBodies()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo() => 0;
void SetGoo(int i) => Bar();
}",
@"using System;
class C
{
int Goo
{
get
{
return 0;
}
set
{
Bar();
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_GetInSetReference()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
}
void Bar()
{
SetGoo(GetGoo() + 1);
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
void Bar()
{
Goo = Goo + 1;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_UpdateSetParameterName_1()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
v = i;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
v = value;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_UpdateSetParameterName_2()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int value)
{
v = value;
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
v = value;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSet_SetReferenceInSetter()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]GetGoo()
{
}
void SetGoo(int i)
{
SetGoo(i - 1);
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
Goo = value - 1;
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVirtualGetWithOverride_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
protected virtual int [||]GetGoo()
{
}
}
class D : C
{
protected override int GetGoo()
{
}
}",
@"class C
{
protected virtual int Goo
{
get
{
}
}
}
class D : C
{
protected override int Goo
{
get
{
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestVirtualGetWithOverride_2()
{
await TestWithAllCodeStyleOff(
@"class C
{
protected virtual int [||]GetGoo()
{
}
}
class D : C
{
protected override int GetGoo()
{
base.GetGoo();
}
}",
@"class C
{
protected virtual int Goo
{
get
{
}
}
}
class D : C
{
protected override int Goo
{
get
{
base.Goo;
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestGetWithInterface()
{
await TestWithAllCodeStyleOff(
@"interface I
{
int [||]GetGoo();
}
class C : I
{
public int GetGoo()
{
}
}",
@"interface I
{
int Goo { get; }
}
class C : I
{
public int Goo
{
get
{
}
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestWithPartialClasses()
{
await TestWithAllCodeStyleOff(
@"partial class C
{
int [||]GetGoo()
{
}
}
partial class C
{
void SetGoo(int i)
{
}
}",
@"partial class C
{
int Goo
{
get
{
}
set
{
}
}
}
partial class C
{
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateGetSetCaseInsensitive()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
int [||]getGoo()
{
}
void setGoo(int i)
{
}
}",
@"using System;
class C
{
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task Tuple()
{
await TestWithAllCodeStyleOff(
@"class C
{
(int, string) [||]GetGoo()
{
}
}",
@"class C
{
(int, string) Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task Tuple_GetAndSet()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
(int, string) [||]getGoo()
{
}
void setGoo((int, string) i)
{
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"using System;
class C
{
(int, string) Goo
{
get
{
}
set
{
}
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TupleWithNames_GetAndSet()
{
await TestWithAllCodeStyleOff(
@"using System;
class C
{
(int a, string b) [||]getGoo()
{
}
void setGoo((int a, string b) i)
{
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"using System;
class C
{
(int a, string b) Goo
{
get
{
}
set
{
}
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs,
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TupleWithDifferentNames_GetAndSet()
{
// Cannot refactor tuples with different names together
await TestActionCountAsync(
@"using System;
class C
{
(int a, string b) [||]getGoo()
{
}
void setGoo((int c, string d) i)
{
}
}",
count: 1, new TestParameters(options: AllCodeStyleOff));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_1()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
// SetGoo
void SetGoo(out int i)
{
}
void Test()
{
SetGoo(out int i);
}
}",
@"class C
{
// Goo
int Goo
{
get
{
}
}
// SetGoo
void SetGoo(out int i)
{
}
void Test()
{
SetGoo(out int i);
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_2()
{
await TestWithAllCodeStyleOff(
@"class C
{
// Goo
int [||]GetGoo()
{
}
// SetGoo
void SetGoo(int i)
{
}
void Test()
{
SetGoo(out int i);
}
}",
@"class C
{
// Goo
// SetGoo
int Goo
{
get
{
}
set
{
}
}
void Test()
{
{|Conflict:Goo|}(out int i);
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_3()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
// Goo
int GetGoo()
{
}
// SetGoo
void [||]SetGoo(out int i)
{
}
void Test()
{
SetGoo(out int i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestOutVarDeclaration_4()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
// Goo
int [||]GetGoo(out int i)
{
}
// SetGoo
void SetGoo(out int i, int j)
{
}
void Test()
{
var y = GetGoo(out int i);
}
}");
}
[WorkItem(14327, "https://github.com/dotnet/roslyn/issues/14327")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUpdateChainedGet1()
{
await TestWithAllCodeStyleOff(
@"public class Goo
{
public Goo()
{
Goo value = GetValue().GetValue();
}
public Goo [||]GetValue()
{
return this;
}
}",
@"public class Goo
{
public Goo()
{
Goo value = Value.Value;
}
public Goo Value
{
get
{
return this;
}
}
}");
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle1()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
}",
@"class C
{
int Goo { get => 1; }
}", options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle2()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
}",
@"class C
{
int Goo => 1;
}", options: PreferExpressionBodiedProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle3()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
}",
@"class C
{
int Goo => 1;
}", options: PreferExpressionBodiedAccessorsAndProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle4()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
void SetGoo(int i)
{
_i = i;
}
}",
@"class C
{
int Goo { get => 1; set => _i = value; }
}",
index: 1,
options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle5()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
void SetGoo(int i)
{
_i = i;
}
}",
@"class C
{
int Goo
{
get
{
return 1;
}
set
{
_i = value;
}
}
}",
index: 1,
options: PreferExpressionBodiedProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle6()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo()
{
return 1;
}
void SetGoo(int i)
{
_i = i;
}
}",
@"class C
{
int Goo { get => 1; set => _i = value; }
}",
index: 1,
options: PreferExpressionBodiedAccessorsAndProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle7()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() => 0;
}",
@"class C
{
int Goo => 0;
}", options: PreferExpressionBodiedProperties);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle8()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() => 0;
}",
@"class C
{
int Goo { get => 0; }
}", options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle9()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() => throw e;
}",
@"class C
{
int Goo { get => throw e; }
}", options: PreferExpressionBodiedAccessors);
}
[WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestCodeStyle10()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() { throw e; }
}",
@"class C
{
int Goo => throw e;
}", options: PreferExpressionBodiedProperties);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsSingleLine()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() { throw e; }
}",
@"class C
{
int Goo => throw e;
}", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUseExpressionBodyWhenOnSingleLine_AndIsNotSingleLine()
{
await TestInRegularAndScriptAsync(
@"class C
{
int [||]GetGoo() { throw e +
e; }
}",
@"class C
{
int Goo
{
get
{
throw e +
e;
}
}
}", options: new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenOnSingleLineWithSilentEnforcement },
});
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestExplicitInterfaceImplementation()
{
await TestWithAllCodeStyleOff(
@"interface IGoo
{
int [||]GetGoo();
}
class C : IGoo
{
int IGoo.GetGoo()
{
throw new System.NotImplementedException();
}
}",
@"interface IGoo
{
int Goo { get; }
}
class C : IGoo
{
int IGoo.Goo
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(443523, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestSystemObjectMetadataOverride()
{
await TestMissingAsync(
@"class C
{
public override string [||]ToString()
{
}
}");
}
[WorkItem(443523, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=443523")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestMetadataOverride()
{
await TestWithAllCodeStyleOff(
@"class C : System.Type
{
public override int [||]GetArrayRank()
{
}
}",
@"class C : System.Type
{
public override int {|Warning:ArrayRank|}
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfTopLevelNullableIsDifferent_GetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private string? name;
public void SetName(string name)
{
this.name = name;
}
public string? [||]GetName()
{
return this.name;
}
}",
@"
#nullable enable
class C
{
private string? name;
public void SetName(string name)
{
this.name = name;
}
public string? Name => this.name;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfTopLevelNullableIsDifferent_SetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private string? name;
public void SetName(string? name)
{
this.name = name;
}
public string [||]GetName()
{
return this.name ?? """";
}
}",
@"
#nullable enable
class C
{
private string? name;
public void SetName(string? name)
{
this.name = name;
}
public string Name => this.name ?? """";
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfNestedNullableIsDifferent_GetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string> names)
{
this.names = names;
}
public IEnumerable<string?> [||]GetNames()
{
return this.names;
}
}",
@"
#nullable enable
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string> names)
{
this.names = names;
}
public IEnumerable<string?> Names => this.names;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task IgnoreIfNestedNullableIsDifferent_SetterNullable()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
using System.Linq;
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string?> names)
{
this.names = names;
}
public IEnumerable<string> [||]GetNames()
{
return this.names.Where(n => n is object);
}
}",
@"
#nullable enable
using System.Linq;
class C
{
private IEnumerable<string?> names;
public void SetNames(IEnumerable<string?> names)
{
this.names = names;
}
public IEnumerable<string> Names => this.names.Where(n => n is object);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task NullabilityOfFieldDifferentThanProperty()
{
await TestInRegularAndScriptAsync(
@"
#nullable enable
class C
{
private string name;
public string? [||]GetName()
{
return name;
}
}",
@"
#nullable enable
class C
{
private string name;
public string? Name => name;
}");
}
[WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUnsafeGetter()
{
await TestInRegularAndScriptAsync(
@"class C
{
public unsafe int [||]GetP()
{
return 0;
}
public void SetP(int value)
{ }
}",
@"class C
{
public unsafe int P
{
get => 0;
set
{ }
}
}", index: 1);
}
[WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestUnsafeSetter()
{
await TestInRegularAndScriptAsync(
@"class C
{
public int [||]GetP()
{
return 0;
}
public unsafe void SetP(int value)
{ }
}",
@"class C
{
public unsafe int P
{
get => 0;
set
{ }
}
}", index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestAtStartOfMethod()
{
await TestWithAllCodeStyleOff(
@"class C
{
[||]int GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_OnSameLine()
{
await TestWithAllCodeStyleOff(
@"class C
{
[||] int GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_OnPreviousLine()
{
await TestWithAllCodeStyleOff(
@"class C
{
[||]
int GetGoo()
{
}
}",
@"class C
{
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotMultipleLinesPrior()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[||]
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotBeforeAttributes()
{
await TestInRegularAndScript1Async(
@"class C
{
[||][A]
int GetGoo()
{
}
}",
@"class C
{
[A]
int Goo
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotBeforeComments()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[||] /// <summary/>
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
public async Task TestBeforeStartOfMethod_NotInComment()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
/// [||]<summary/>
int GetGoo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(42699, "https://github.com/dotnet/roslyn/issues/42699")]
public async Task TestSameNameMemberAsProperty()
{
await TestInRegularAndScript1Async(
@"class C
{
int Goo;
[||]int GetGoo()
{
}
}",
@"class C
{
int Goo;
int Goo1
{
get
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(42698, "https://github.com/dotnet/roslyn/issues/42698")]
public async Task TestMethodWithTrivia_3()
{
await TestInRegularAndScript1Async(
@"class C
{
[||]int Goo() //Vital Comment
{
return 1;
}
}",
@"class C
{
//Vital Comment
int Goo => 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)]
[WorkItem(42698, "https://github.com/dotnet/roslyn/issues/42698")]
public async Task TestMethodWithTrivia_4()
{
await TestWithAllCodeStyleOff(
@"class C
{
int [||]GetGoo() // Goo
{
}
void SetGoo(int i) // SetGoo
{
}
}",
@"class C
{
// Goo
// SetGoo
int Goo
{
get
{
}
set
{
}
}
}",
index: 1);
}
private async Task TestWithAllCodeStyleOff(
string initialMarkup, string expectedMarkup,
ParseOptions? parseOptions = null, int index = 0)
{
await TestAsync(
initialMarkup, expectedMarkup, parseOptions,
index: index,
options: AllCodeStyleOff);
}
private OptionsCollection AllCodeStyleOff
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
private OptionsCollection PreferExpressionBodiedAccessors
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
private OptionsCollection PreferExpressionBodiedProperties
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
};
private OptionsCollection PreferExpressionBodiedAccessorsAndProperties
=> new OptionsCollection(GetLanguage())
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement },
};
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/VisualBasic/Portable/SignatureHelp/GetTypeExpressionSignatureHelpProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
<ExportSignatureHelpProvider("GetTypeExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]>
Partial Friend Class GetTypeExpressionSignatureHelpProvider
Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of GetTypeExpressionSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As GetTypeExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))
Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New GetTypeExpressionDocumentation()})
End Function
Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean
Return token.IsChildToken(Of GetTypeExpressionSyntax)(Function(ce) ce.OpenParenToken)
End Function
Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean
Return ch = "("c
End Function
Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean
Return ch = ")"c
End Function
Protected Overrides Function IsArgumentListToken(node As GetTypeExpressionSyntax, token As SyntaxToken) As Boolean
Return node.GetTypeKeyword <> token AndAlso
node.CloseParenToken <> token
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.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
<ExportSignatureHelpProvider("GetTypeExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]>
Partial Friend Class GetTypeExpressionSignatureHelpProvider
Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of GetTypeExpressionSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As GetTypeExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))
Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New GetTypeExpressionDocumentation()})
End Function
Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean
Return token.IsChildToken(Of GetTypeExpressionSyntax)(Function(ce) ce.OpenParenToken)
End Function
Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean
Return ch = "("c
End Function
Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean
Return ch = ")"c
End Function
Protected Overrides Function IsArgumentListToken(node As GetTypeExpressionSyntax, token As SyntaxToken) As Boolean
Return node.GetTypeKeyword <> token AndAlso
node.CloseParenToken <> token
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Analyzers/CSharp/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues
{
public partial class RemoveUnusedValueExpressionStatementTests : RemoveUnusedValuesTestsBase
{
public RemoveUnusedValueExpressionStatementTests(ITestOutputHelper logger)
: base(logger)
{
}
private protected override OptionsCollection PreferNone =>
Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement,
new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.None));
private protected override OptionsCollection PreferDiscard =>
Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement,
new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.Silent));
private protected override OptionsCollection PreferUnusedLocal =>
Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement,
new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Suppressed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
int M2() => 0;
}", options: PreferNone);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_PreferDiscard_CSharp6()
{
// Discard not supported in C# 6.0, so we fallback to unused local variable.
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
int M2() => 0;
}",
@"class C
{
void M()
{
var unused = M2();
}
int M2() => 0;
}", options: PreferDiscard,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_VariableInitialization(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
int x = [|M2()|];
}
int M2() => 0;
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard), "_")]
[InlineData(nameof(PreferUnusedLocal), "var unused")]
public async Task ExpressionStatement_NonConstantPrimitiveTypeValue(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
int M2() => 0;
}",
$@"class C
{{
void M()
{{
{fix} = M2();
}}
int M2() => 0;
}}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard), "_")]
[InlineData(nameof(PreferUnusedLocal), "var unused")]
public async Task ExpressionStatement_UserDefinedType(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
C M2() => new C();
}",
$@"class C
{{
void M()
{{
{fix} = M2();
}}
C M2() => new C();
}}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_ConstantValue(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|1|];
}
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SyntaxError(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2(,)|];
}
int M2() => 0;
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
}", optionName);
}
[WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
UndefinedType M2() => null;
}", optionName);
}
[WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError_03(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class C
{
private async Task M()
{
// error CS0103: The name 'CancellationToken' does not exist in the current context
[|await Task.Delay(0, CancellationToken.None).ConfigureAwait(false)|];
}
}", optionName);
}
[WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError_04(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
private async Task M()
{
// error CS0103: The name 'Task' does not exist in the current context
// error CS0103: The name 'CancellationToken' does not exist in the current context
// error CS1983: The return type of an async method must be void, Task or Task<T>
[|await Task.Delay(0, CancellationToken.None).ConfigureAwait(false)|];
}
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_VoidReturningMethodCall(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
void M2() { }
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData("=")]
[InlineData("+=")]
public async Task ExpressionStatement_AssignmentExpression(string op)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
$@"class C
{{
void M(int x)
{{
x {op} [|M2()|];
}}
int M2() => 0;
}}");
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData("x++")]
[InlineData("x--")]
[InlineData("++x")]
[InlineData("--x")]
public async Task ExpressionStatement_IncrementOrDecrement(string incrementOrDecrement)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
$@"class C
{{
int M(int x)
{{
[|{incrementOrDecrement}|];
return x;
}}
}}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
var unused = M2();
[|M2()|];
}
int M2() => 0;
}",
@"class C
{
void M()
{
var unused = M2();
var unused1 = M2();
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_02()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
var unused = M2();
}
int M2() => 0;
}",
@"class C
{
void M()
{
var unused1 = M2();
var unused = M2();
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_03()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(int p)
{
[|M2()|];
if (p > 0)
{
var unused = M2();
}
}
int M2() => 0;
}",
@"class C
{
void M(int p)
{
var unused1 = M2();
if (p > 0)
{
var unused = M2();
}
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_04()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(int p)
{
if (p > 0)
{
[|M2()|];
}
else
{
var unused = M2();
}
}
int M2() => 0;
}",
@"class C
{
void M(int p)
{
if (p > 0)
{
var unused1 = M2();
}
else
{
var unused = M2();
}
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard), "_", "_", "_")]
[InlineData(nameof(PreferUnusedLocal), "var unused", "var unused", "var unused3")]
public async Task ExpressionStatement_FixAll(string optionName, string fix1, string fix2, string fix3)
{
await TestInRegularAndScriptAsync(
@"class C
{
public C()
{
M2(); // Separate code block
}
void M(int unused1, int unused2)
{
{|FixAllInDocument:M2()|};
M2(); // Another instance in same code block
_ = M2(); // Already fixed
var x = M2(); // Different unused value diagnostic
}
int M2() => 0;
}",
$@"class C
{{
public C()
{{
{fix1} = M2(); // Separate code block
}}
void M(int unused1, int unused2)
{{
{fix3} = M2();
{fix2} = M2(); // Another instance in same code block
_ = M2(); // Already fixed
var x = M2(); // Different unused value diagnostic
}}
int M2() => 0;
}}", optionName);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferDiscard_01()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// C1
[|M2()|]; // C2
// C3
}
int M2() => 0;
}",
@"class C
{
void M()
{
// C1
_ = M2(); // C2
// C3
}
int M2() => 0;
}", options: PreferDiscard);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferDiscard_02()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{/*C0*/
/*C1*/[|M2()|]/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}",
@"class C
{
void M()
{/*C0*/
/*C1*/
_ = M2()/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}", options: PreferDiscard);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferUnusedLocal_01()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// C1
[|M2()|]; // C2
// C3
}
int M2() => 0;
}",
@"class C
{
void M()
{
// C1
var unused = M2(); // C2
// C3
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferUnusedLocal_02()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{/*C0*/
/*C1*/[|M2()|]/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}",
@"class C
{
void M()
{/*C0*/
/*C1*/
var unused = M2()/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionBodiedMember_01(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M() => [|M2()|];
int M2() => 0;
}", optionName);
}
[WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionBodiedMember_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
System.Action a = () => [|M2()|];
}
int M2() => 0;
}", optionName);
}
[WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionBodiedMember_03(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
LocalFunction();
return;
void LocalFunction() => [|M2()|];
}
int M2() => 0;
}", optionName);
}
[WorkItem(43648, "https://github.com/dotnet/roslyn/issues/43648")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_Dynamic(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<dynamic> returnValue = new List<dynamic>();
dynamic dynamicValue = new object();
[|returnValue.Add(dynamicValue)|];
}
}", optionName);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues
{
public partial class RemoveUnusedValueExpressionStatementTests : RemoveUnusedValuesTestsBase
{
public RemoveUnusedValueExpressionStatementTests(ITestOutputHelper logger)
: base(logger)
{
}
private protected override OptionsCollection PreferNone =>
Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement,
new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.None));
private protected override OptionsCollection PreferDiscard =>
Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement,
new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption2.Silent));
private protected override OptionsCollection PreferUnusedLocal =>
Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement,
new CodeStyleOption2<UnusedValuePreference>(UnusedValuePreference.UnusedLocalVariable, NotificationOption2.Silent));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Suppressed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
int M2() => 0;
}", options: PreferNone);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_PreferDiscard_CSharp6()
{
// Discard not supported in C# 6.0, so we fallback to unused local variable.
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
int M2() => 0;
}",
@"class C
{
void M()
{
var unused = M2();
}
int M2() => 0;
}", options: PreferDiscard,
parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_VariableInitialization(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
int x = [|M2()|];
}
int M2() => 0;
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard), "_")]
[InlineData(nameof(PreferUnusedLocal), "var unused")]
public async Task ExpressionStatement_NonConstantPrimitiveTypeValue(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
int M2() => 0;
}",
$@"class C
{{
void M()
{{
{fix} = M2();
}}
int M2() => 0;
}}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard), "_")]
[InlineData(nameof(PreferUnusedLocal), "var unused")]
public async Task ExpressionStatement_UserDefinedType(string optionName, string fix)
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
C M2() => new C();
}",
$@"class C
{{
void M()
{{
{fix} = M2();
}}
C M2() => new C();
}}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_ConstantValue(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|1|];
}
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SyntaxError(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2(,)|];
}
int M2() => 0;
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
}", optionName);
}
[WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
UndefinedType M2() => null;
}", optionName);
}
[WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError_03(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"using System.Threading.Tasks;
class C
{
private async Task M()
{
// error CS0103: The name 'CancellationToken' does not exist in the current context
[|await Task.Delay(0, CancellationToken.None).ConfigureAwait(false)|];
}
}", optionName);
}
[WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_SemanticError_04(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
private async Task M()
{
// error CS0103: The name 'Task' does not exist in the current context
// error CS0103: The name 'CancellationToken' does not exist in the current context
// error CS1983: The return type of an async method must be void, Task or Task<T>
[|await Task.Delay(0, CancellationToken.None).ConfigureAwait(false)|];
}
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_VoidReturningMethodCall(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
}
void M2() { }
}", optionName);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData("=")]
[InlineData("+=")]
public async Task ExpressionStatement_AssignmentExpression(string op)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
$@"class C
{{
void M(int x)
{{
x {op} [|M2()|];
}}
int M2() => 0;
}}");
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData("x++")]
[InlineData("x--")]
[InlineData("++x")]
[InlineData("--x")]
public async Task ExpressionStatement_IncrementOrDecrement(string incrementOrDecrement)
{
await TestMissingInRegularAndScriptWithAllOptionsAsync(
$@"class C
{{
int M(int x)
{{
[|{incrementOrDecrement}|];
return x;
}}
}}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
var unused = M2();
[|M2()|];
}
int M2() => 0;
}",
@"class C
{
void M()
{
var unused = M2();
var unused1 = M2();
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_02()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
[|M2()|];
var unused = M2();
}
int M2() => 0;
}",
@"class C
{
void M()
{
var unused1 = M2();
var unused = M2();
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_03()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(int p)
{
[|M2()|];
if (p > 0)
{
var unused = M2();
}
}
int M2() => 0;
}",
@"class C
{
void M(int p)
{
var unused1 = M2();
if (p > 0)
{
var unused = M2();
}
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_04()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(int p)
{
if (p > 0)
{
[|M2()|];
}
else
{
var unused = M2();
}
}
int M2() => 0;
}",
@"class C
{
void M(int p)
{
if (p > 0)
{
var unused1 = M2();
}
else
{
var unused = M2();
}
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard), "_", "_", "_")]
[InlineData(nameof(PreferUnusedLocal), "var unused", "var unused", "var unused3")]
public async Task ExpressionStatement_FixAll(string optionName, string fix1, string fix2, string fix3)
{
await TestInRegularAndScriptAsync(
@"class C
{
public C()
{
M2(); // Separate code block
}
void M(int unused1, int unused2)
{
{|FixAllInDocument:M2()|};
M2(); // Another instance in same code block
_ = M2(); // Already fixed
var x = M2(); // Different unused value diagnostic
}
int M2() => 0;
}",
$@"class C
{{
public C()
{{
{fix1} = M2(); // Separate code block
}}
void M(int unused1, int unused2)
{{
{fix3} = M2();
{fix2} = M2(); // Another instance in same code block
_ = M2(); // Already fixed
var x = M2(); // Different unused value diagnostic
}}
int M2() => 0;
}}", optionName);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferDiscard_01()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// C1
[|M2()|]; // C2
// C3
}
int M2() => 0;
}",
@"class C
{
void M()
{
// C1
_ = M2(); // C2
// C3
}
int M2() => 0;
}", options: PreferDiscard);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferDiscard_02()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{/*C0*/
/*C1*/[|M2()|]/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}",
@"class C
{
void M()
{/*C0*/
/*C1*/
_ = M2()/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}", options: PreferDiscard);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferUnusedLocal_01()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{
// C1
[|M2()|]; // C2
// C3
}
int M2() => 0;
}",
@"class C
{
void M()
{
// C1
var unused = M2(); // C2
// C3
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
public async Task ExpressionStatement_Trivia_PreferUnusedLocal_02()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M()
{/*C0*/
/*C1*/[|M2()|]/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}",
@"class C
{
void M()
{/*C0*/
/*C1*/
var unused = M2()/*C2*/;/*C3*/
/*C4*/
}
int M2() => 0;
}", options: PreferUnusedLocal);
}
[WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionBodiedMember_01(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M() => [|M2()|];
int M2() => 0;
}", optionName);
}
[WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionBodiedMember_02(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
System.Action a = () => [|M2()|];
}
int M2() => 0;
}", optionName);
}
[WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionBodiedMember_03(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
LocalFunction();
return;
void LocalFunction() => [|M2()|];
}
int M2() => 0;
}", optionName);
}
[WorkItem(43648, "https://github.com/dotnet/roslyn/issues/43648")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)]
[InlineData(nameof(PreferDiscard))]
[InlineData(nameof(PreferUnusedLocal))]
public async Task ExpressionStatement_Dynamic(string optionName)
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class C
{
void M()
{
List<dynamic> returnValue = new List<dynamic>();
dynamic dynamicValue = new object();
[|returnValue.Add(dynamicValue)|];
}
}", optionName);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Portable/FlowAnalysis/AlwaysAssignedWalker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A region analysis walker that computes the set of variables that are always assigned a value
/// in the region. A variable is "always assigned" in a region if an analysis of the region that
/// starts with the variable unassigned ends with the variable assigned.
/// </summary>
internal class AlwaysAssignedWalker : AbstractRegionDataFlowPass
{
private LocalState _endOfRegionState;
private readonly HashSet<LabelSymbol> _labelsInside = new HashSet<LabelSymbol>();
private AlwaysAssignedWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
: base(compilation, member, node, firstInRegion, lastInRegion)
{
}
internal static IEnumerable<Symbol> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
{
var walker = new AlwaysAssignedWalker(compilation, member, node, firstInRegion, lastInRegion);
bool badRegion = false;
try
{
var result = walker.Analyze(ref badRegion);
return badRegion ? SpecializedCollections.EmptyEnumerable<Symbol>() : result;
}
finally
{
walker.Free();
}
}
private List<Symbol> Analyze(ref bool badRegion)
{
base.Analyze(ref badRegion, null);
List<Symbol> result = new List<Symbol>();
Debug.Assert(!IsInside);
if (_endOfRegionState.Reachable)
{
foreach (var i in _endOfRegionState.Assigned.TrueBits())
{
if (i >= variableBySlot.Count)
{
continue;
}
var v = base.variableBySlot[i];
if (v.Exists && !(v.Symbol is FieldSymbol))
{
result.Add(v.Symbol);
}
}
}
return result;
}
protected override void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method)
{
// ref parameter does not "always" assign.
if (refKind == RefKind.Out)
{
Assign(arg, value: null);
}
}
protected override void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged)
{
// branches into a region are considered entry points
if (IsInside && pending.Branch != null && !RegionContains(pending.Branch.Syntax.Span))
{
pending.State = pending.State.Reachable ? TopState() : UnreachableState();
}
base.ResolveBranch(pending, label, target, ref labelStateChanged);
}
public override BoundNode VisitLabel(BoundLabel node)
{
ResolveLabel(node, node.Label);
return base.VisitLabel(node);
}
public override BoundNode VisitLabeledStatement(BoundLabeledStatement node)
{
ResolveLabel(node, node.Label);
return base.VisitLabeledStatement(node);
}
private void ResolveLabel(BoundNode node, LabelSymbol label)
{
if (node.Syntax != null && RegionContains(node.Syntax.Span)) _labelsInside.Add(label);
}
protected override void EnterRegion()
{
this.State = TopState();
base.EnterRegion();
}
protected override void LeaveRegion()
{
if (this.IsConditionalState)
{
// If the region is in a condition, then the state will be split and state.Assigned will
// be null. Merge to get sensible results.
_endOfRegionState = StateWhenTrue.Clone();
Join(ref _endOfRegionState, ref StateWhenFalse);
}
else
{
_endOfRegionState = this.State.Clone();
}
foreach (var branch in base.PendingBranches)
{
if (branch.Branch != null && RegionContains(branch.Branch.Syntax.Span) && !_labelsInside.Contains(branch.Label))
{
Join(ref _endOfRegionState, ref branch.State);
}
}
base.LeaveRegion();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A region analysis walker that computes the set of variables that are always assigned a value
/// in the region. A variable is "always assigned" in a region if an analysis of the region that
/// starts with the variable unassigned ends with the variable assigned.
/// </summary>
internal class AlwaysAssignedWalker : AbstractRegionDataFlowPass
{
private LocalState _endOfRegionState;
private readonly HashSet<LabelSymbol> _labelsInside = new HashSet<LabelSymbol>();
private AlwaysAssignedWalker(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
: base(compilation, member, node, firstInRegion, lastInRegion)
{
}
internal static IEnumerable<Symbol> Analyze(CSharpCompilation compilation, Symbol member, BoundNode node, BoundNode firstInRegion, BoundNode lastInRegion)
{
var walker = new AlwaysAssignedWalker(compilation, member, node, firstInRegion, lastInRegion);
bool badRegion = false;
try
{
var result = walker.Analyze(ref badRegion);
return badRegion ? SpecializedCollections.EmptyEnumerable<Symbol>() : result;
}
finally
{
walker.Free();
}
}
private List<Symbol> Analyze(ref bool badRegion)
{
base.Analyze(ref badRegion, null);
List<Symbol> result = new List<Symbol>();
Debug.Assert(!IsInside);
if (_endOfRegionState.Reachable)
{
foreach (var i in _endOfRegionState.Assigned.TrueBits())
{
if (i >= variableBySlot.Count)
{
continue;
}
var v = base.variableBySlot[i];
if (v.Exists && !(v.Symbol is FieldSymbol))
{
result.Add(v.Symbol);
}
}
}
return result;
}
protected override void WriteArgument(BoundExpression arg, RefKind refKind, MethodSymbol method)
{
// ref parameter does not "always" assign.
if (refKind == RefKind.Out)
{
Assign(arg, value: null);
}
}
protected override void ResolveBranch(PendingBranch pending, LabelSymbol label, BoundStatement target, ref bool labelStateChanged)
{
// branches into a region are considered entry points
if (IsInside && pending.Branch != null && !RegionContains(pending.Branch.Syntax.Span))
{
pending.State = pending.State.Reachable ? TopState() : UnreachableState();
}
base.ResolveBranch(pending, label, target, ref labelStateChanged);
}
public override BoundNode VisitLabel(BoundLabel node)
{
ResolveLabel(node, node.Label);
return base.VisitLabel(node);
}
public override BoundNode VisitLabeledStatement(BoundLabeledStatement node)
{
ResolveLabel(node, node.Label);
return base.VisitLabeledStatement(node);
}
private void ResolveLabel(BoundNode node, LabelSymbol label)
{
if (node.Syntax != null && RegionContains(node.Syntax.Span)) _labelsInside.Add(label);
}
protected override void EnterRegion()
{
this.State = TopState();
base.EnterRegion();
}
protected override void LeaveRegion()
{
if (this.IsConditionalState)
{
// If the region is in a condition, then the state will be split and state.Assigned will
// be null. Merge to get sensible results.
_endOfRegionState = StateWhenTrue.Clone();
Join(ref _endOfRegionState, ref StateWhenFalse);
}
else
{
_endOfRegionState = this.State.Clone();
}
foreach (var branch in base.PendingBranches)
{
if (branch.Branch != null && RegionContains(branch.Branch.Syntax.Span) && !_labelsInside.Contains(branch.Label))
{
Join(ref _endOfRegionState, ref branch.State);
}
}
base.LeaveRegion();
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/VisualStudio/Core/Test/AbstractTextViewFilterTests.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.Editor
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Roslyn.Test.Utilities
Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests
<[UseExportProvider]>
Public Class AbstractTextViewFilterTests
<WpfFact, WorkItem(617826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617826"), Trait(Traits.Feature, Traits.Features.Venus), Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub MapPointsInProjectionCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
class C
{
static void M()
{
{|S1:foreach (var x in new int[] { 1, 2, 3 })
$${ |}
Console.Write({|S2:item|});
{|S3:[|}|]|}
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim projected = workspace.CreateProjectionBufferDocument(<text><![CDATA[
@{|S1:|}
<span>@{|S2:|}</span>
{|S3:|}
<h2>Default</h2>
]]></text>.Value.Replace(vbLf, vbCrLf), {doc})
Dim matchingSpan = projected.SelectedSpans.Single()
TestSpan(workspace, projected, projected.CursorPosition.Value, matchingSpan.End)
TestSpan(workspace, projected, matchingSpan.End, projected.CursorPosition.Value)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceNavigatesToOuterPositionOfMatchingBraceCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine[|$$(Increment(5))|];
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, doc.CursorPosition.Value, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End, doc.CursorPosition.Value, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceFromLeftAndRightOfOpenAndCloseBracesCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine(Increment[|$$(5)|]);
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, span.Start, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.Start + 1, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End - 1, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceExtFindsTheInnerPositionOfCloseBraceAndOuterPositionOfOpenBraceCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine[|(Increment(5)|])$$;
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, caretPosition:=span.Start, startPosition:=span.Start, endPosition:=span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=doc.CursorPosition.Value, startPosition:=span.End, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceExtFromLeftAndRightOfOpenAndCloseBracesCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine(Increment[|(5)|]);
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
' Test from left and right of Open parenthesis
TestSpan(workspace, doc, caretPosition:=span.Start, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.Start + 1, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
' Test from left and right of Close parenthesis
TestSpan(workspace, doc, caretPosition:=span.End, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.End - 1, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceFromLeftAndRightOfOpenAndCloseBracesBasic()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine(Increment[|$$(5)|])
End Sub
Private Function Increment(v As Integer) As Integer
Return v + 1
End Function
End Module
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, span.Start, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.Start + 1, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End - 1, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceExtFromLeftAndRightOfOpenAndCloseBracesBasic()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine(Increment[|$$(5)|])
End Sub
Private Function Increment(v As Integer) As Integer
Return v + 1
End Function
End Module
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
' Test from left and right of Open parenthesis
TestSpan(workspace, doc, caretPosition:=span.Start, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.Start + 1, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
' Test from left and right of Close parenthesis
TestSpan(workspace, doc, caretPosition:=span.End, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.End - 1, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
End Using
End Sub
Private Shared Sub TestSpan(workspace As TestWorkspace, document As TestHostDocument, startPosition As Integer, endPosition As Integer, Optional commandId As UInteger = Nothing)
Dim braceMatcher = workspace.ExportProvider.GetExportedValue(Of IBraceMatchingService)()
Dim initialLine = document.InitialTextSnapshot.GetLineFromPosition(startPosition)
Dim initialLineNumber = initialLine.LineNumber
Dim initialIndex = startPosition - initialLine.Start.Position
Dim spans() = {New VsTextSpan()}
Assert.Equal(0, AbstractVsTextViewFilter.GetPairExtentsWorker(
document.GetTextView(),
braceMatcher,
initialLineNumber,
initialIndex,
spans,
commandId = CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT),
CancellationToken.None))
' Note - we only set either the start OR the end to the result, the other gets set to the source.
Dim resultLine = document.InitialTextSnapshot.GetLineFromPosition(endPosition)
Dim resultIndex = endPosition - resultLine.Start.Position
AssertSpansMatch(startPosition, endPosition, initialLineNumber, initialIndex, spans, resultLine, resultIndex)
End Sub
Private Shared Sub TestSpan(workspace As TestWorkspace, document As TestHostDocument, caretPosition As Integer, startPosition As Integer, endPosition As Integer, Optional commandId As UInteger = Nothing)
Dim braceMatcher = workspace.ExportProvider.GetExportedValue(Of IBraceMatchingService)()
Dim initialLine = document.InitialTextSnapshot.GetLineFromPosition(caretPosition)
Dim initialLineNumber = initialLine.LineNumber
Dim initialIndex = caretPosition - initialLine.Start.Position
Dim spans() = {New VsTextSpan()}
Assert.Equal(0, AbstractVsTextViewFilter.GetPairExtentsWorker(
document.GetTextView(),
braceMatcher,
initialLineNumber,
initialIndex,
spans,
commandId = CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT),
CancellationToken.None))
'In extending selection (GotoBraceExt) scenarios we set both start AND end to the result.
Dim startIndex = startPosition - initialLine.Start.Position
Dim resultLine = document.InitialTextSnapshot.GetLineFromPosition(endPosition)
Dim resultIndex = endPosition - resultLine.Start.Position
AssertSpansMatch(startPosition, endPosition, initialLineNumber, startIndex, spans, resultLine, resultIndex)
End Sub
Private Shared Sub AssertSpansMatch(startPosition As Integer, endPosition As Integer, initialLineNumber As Integer, startIndex As Integer, spans() As VsTextSpan, resultLine As Text.ITextSnapshotLine, resultIndex As Integer)
If endPosition > startPosition Then
Assert.Equal(initialLineNumber, spans(0).iStartLine)
Assert.Equal(startIndex, spans(0).iStartIndex)
Assert.Equal(resultLine.LineNumber, spans(0).iEndLine)
Assert.Equal(resultIndex, spans(0).iEndIndex)
Else
Assert.Equal(resultLine.LineNumber, spans(0).iStartLine)
Assert.Equal(resultIndex, spans(0).iStartIndex)
Assert.Equal(initialLineNumber, spans(0).iEndLine)
Assert.Equal(startIndex, spans(0).iEndIndex)
End If
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Roslyn.Test.Utilities
Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests
<[UseExportProvider]>
Public Class AbstractTextViewFilterTests
<WpfFact, WorkItem(617826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617826"), Trait(Traits.Feature, Traits.Features.Venus), Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub MapPointsInProjectionCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
class C
{
static void M()
{
{|S1:foreach (var x in new int[] { 1, 2, 3 })
$${ |}
Console.Write({|S2:item|});
{|S3:[|}|]|}
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim projected = workspace.CreateProjectionBufferDocument(<text><![CDATA[
@{|S1:|}
<span>@{|S2:|}</span>
{|S3:|}
<h2>Default</h2>
]]></text>.Value.Replace(vbLf, vbCrLf), {doc})
Dim matchingSpan = projected.SelectedSpans.Single()
TestSpan(workspace, projected, projected.CursorPosition.Value, matchingSpan.End)
TestSpan(workspace, projected, matchingSpan.End, projected.CursorPosition.Value)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceNavigatesToOuterPositionOfMatchingBraceCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine[|$$(Increment(5))|];
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, doc.CursorPosition.Value, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End, doc.CursorPosition.Value, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceFromLeftAndRightOfOpenAndCloseBracesCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine(Increment[|$$(5)|]);
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, span.Start, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.Start + 1, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End - 1, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceExtFindsTheInnerPositionOfCloseBraceAndOuterPositionOfOpenBraceCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine[|(Increment(5)|])$$;
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, caretPosition:=span.Start, startPosition:=span.Start, endPosition:=span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=doc.CursorPosition.Value, startPosition:=span.End, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceExtFromLeftAndRightOfOpenAndCloseBracesCSharp()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document>
using System;
class C
{
static void M()
{
Console.WriteLine(Increment[|(5)|]);
}
static int Increment(int n)
{
return n+1;
}
}
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
' Test from left and right of Open parenthesis
TestSpan(workspace, doc, caretPosition:=span.Start, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.Start + 1, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
' Test from left and right of Close parenthesis
TestSpan(workspace, doc, caretPosition:=span.End, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.End - 1, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceFromLeftAndRightOfOpenAndCloseBracesBasic()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine(Increment[|$$(5)|])
End Sub
Private Function Increment(v As Integer) As Integer
Return v + 1
End Function
End Module
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
TestSpan(workspace, doc, span.Start, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.Start + 1, span.End, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
TestSpan(workspace, doc, span.End - 1, span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE))
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Sub GotoBraceExtFromLeftAndRightOfOpenAndCloseBracesBasic()
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.VisualBasic %> CommonReferences="true">
<Document>
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine(Increment[|$$(5)|])
End Sub
Private Function Increment(v As Integer) As Integer
Return v + 1
End Function
End Module
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceXml, composition:=VisualStudioTestCompositions.LanguageServices)
Dim doc = workspace.Documents.Single()
Dim span = doc.SelectedSpans.Single()
' Test from left and right of Open parenthesis
TestSpan(workspace, doc, caretPosition:=span.Start, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.Start + 1, startPosition:=span.Start, endPosition:=span.End - 1, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
' Test from left and right of Close parenthesis
TestSpan(workspace, doc, caretPosition:=span.End, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
TestSpan(workspace, doc, caretPosition:=span.End - 1, startPosition:=span.End - 1, endPosition:=span.Start, commandId:=CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT))
End Using
End Sub
Private Shared Sub TestSpan(workspace As TestWorkspace, document As TestHostDocument, startPosition As Integer, endPosition As Integer, Optional commandId As UInteger = Nothing)
Dim braceMatcher = workspace.ExportProvider.GetExportedValue(Of IBraceMatchingService)()
Dim initialLine = document.InitialTextSnapshot.GetLineFromPosition(startPosition)
Dim initialLineNumber = initialLine.LineNumber
Dim initialIndex = startPosition - initialLine.Start.Position
Dim spans() = {New VsTextSpan()}
Assert.Equal(0, AbstractVsTextViewFilter.GetPairExtentsWorker(
document.GetTextView(),
braceMatcher,
initialLineNumber,
initialIndex,
spans,
commandId = CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT),
CancellationToken.None))
' Note - we only set either the start OR the end to the result, the other gets set to the source.
Dim resultLine = document.InitialTextSnapshot.GetLineFromPosition(endPosition)
Dim resultIndex = endPosition - resultLine.Start.Position
AssertSpansMatch(startPosition, endPosition, initialLineNumber, initialIndex, spans, resultLine, resultIndex)
End Sub
Private Shared Sub TestSpan(workspace As TestWorkspace, document As TestHostDocument, caretPosition As Integer, startPosition As Integer, endPosition As Integer, Optional commandId As UInteger = Nothing)
Dim braceMatcher = workspace.ExportProvider.GetExportedValue(Of IBraceMatchingService)()
Dim initialLine = document.InitialTextSnapshot.GetLineFromPosition(caretPosition)
Dim initialLineNumber = initialLine.LineNumber
Dim initialIndex = caretPosition - initialLine.Start.Position
Dim spans() = {New VsTextSpan()}
Assert.Equal(0, AbstractVsTextViewFilter.GetPairExtentsWorker(
document.GetTextView(),
braceMatcher,
initialLineNumber,
initialIndex,
spans,
commandId = CUInt(VSConstants.VSStd2KCmdID.GOTOBRACE_EXT),
CancellationToken.None))
'In extending selection (GotoBraceExt) scenarios we set both start AND end to the result.
Dim startIndex = startPosition - initialLine.Start.Position
Dim resultLine = document.InitialTextSnapshot.GetLineFromPosition(endPosition)
Dim resultIndex = endPosition - resultLine.Start.Position
AssertSpansMatch(startPosition, endPosition, initialLineNumber, startIndex, spans, resultLine, resultIndex)
End Sub
Private Shared Sub AssertSpansMatch(startPosition As Integer, endPosition As Integer, initialLineNumber As Integer, startIndex As Integer, spans() As VsTextSpan, resultLine As Text.ITextSnapshotLine, resultIndex As Integer)
If endPosition > startPosition Then
Assert.Equal(initialLineNumber, spans(0).iStartLine)
Assert.Equal(startIndex, spans(0).iStartIndex)
Assert.Equal(resultLine.LineNumber, spans(0).iEndLine)
Assert.Equal(resultIndex, spans(0).iEndIndex)
Else
Assert.Equal(resultLine.LineNumber, spans(0).iStartLine)
Assert.Equal(resultIndex, spans(0).iStartIndex)
Assert.Equal(initialLineNumber, spans(0).iEndLine)
Assert.Equal(startIndex, spans(0).iEndIndex)
End If
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/Portable/CodeCleanup/Providers/ICodeCleanupProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeCleanup.Providers
{
/// <summary>
/// A code cleaner that requires semantic information to do its job.
/// </summary>
internal interface ICodeCleanupProvider
{
/// <summary>
/// Returns the name of this provider.
/// </summary>
string Name { get; }
/// <summary>
/// This should apply its code clean up logic to the spans of the document.
/// </summary>
Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken = default);
/// <summary>
/// This will run all provided code cleaners in an order that is given to the method.
///
/// This will do cleanups that don't require any semantic information
/// </summary>
Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken = default);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeCleanup.Providers
{
/// <summary>
/// A code cleaner that requires semantic information to do its job.
/// </summary>
internal interface ICodeCleanupProvider
{
/// <summary>
/// Returns the name of this provider.
/// </summary>
string Name { get; }
/// <summary>
/// This should apply its code clean up logic to the spans of the document.
/// </summary>
Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken = default);
/// <summary>
/// This will run all provided code cleaners in an order that is given to the method.
///
/// This will do cleanups that don't require any semantic information
/// </summary>
Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken = default);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
internal static class CastSimplifier
{
public static bool IsUnnecessaryCast(ExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast is CastExpressionSyntax castExpression ? IsUnnecessaryCast(castExpression, semanticModel, cancellationToken) :
cast is BinaryExpressionSyntax binaryExpression ? IsUnnecessaryAsCast(binaryExpression, semanticModel, cancellationToken) : false;
public static bool IsUnnecessaryCast(CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> IsCastSafeToRemove(cast, cast.Expression, semanticModel, cancellationToken);
public static bool IsUnnecessaryAsCast(BinaryExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast.Kind() == SyntaxKind.AsExpression &&
IsCastSafeToRemove(cast, cast.Left, semanticModel, cancellationToken);
private static bool IsCastSafeToRemove(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(castNode,
castedExpressionNode, semanticModel, cancellationToken,
skipVerificationForReplacedNode: true, failOnOverloadResolutionFailuresInOriginalCode: true);
// First, check to see if the node ultimately parenting this cast has any
// syntax errors. If so, we bail.
if (speculationAnalyzer.SemanticRootOfOriginalExpression.ContainsDiagnostics)
return false;
// Now perform basic checks looking for a few things:
//
// 1. casts that must stay because removal will produce actually illegal code.
// 2. casts that must stay because they have runtime impact (i.e. could cause exceptions to be thrown).
// 3. casts that *seem* unnecessary because they don't violate the above, and the cast seems like it has no
// effect at runtime (i.e. casting a `string` to `object`). Note: just because the cast seems like it
// will have not runtime impact doesn't mean we can remove it. It still may be necessary to preserve the
// meaning of the code (for example for overload resolution). That check will occur after this.
//
// This is the fundamental separation between CastHasNoRuntimeImpact and
// speculationAnalyzer.ReplacementChangesSemantics. The former is simple and is only asking if the cast
// seems like it would have no impact *at runtime*. The latter ensures that the static meaning of the code
// is preserved.
//
// When adding/updating checks keep the above in mind to determine where the check should go.
var castHasRuntimeImpact = CastHasRuntimeImpact(
speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
if (castHasRuntimeImpact)
return false;
// Cast has no runtime effect. But it may change static semantics. Only allow removal if static semantics
// don't change.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
return true;
}
private static bool CastHasRuntimeImpact(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Look for simple patterns we know will never cause any runtime changes.
if (CastDefinitelyHasNoRuntimeImpact(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// Call into our legacy codepath that tries to make the same determination.
return !CastHasNoRuntimeImpact_Legacy(speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
}
private static bool CastDefinitelyHasNoRuntimeImpact(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// NOTE: Keep this method simple. Each type of runtime impact check should just be a new check added
// independently from the rest. We want to make it very clear exactly which cases each check is covering.
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
// $"x {(object)y} z" It's always safe to remove this `(object)` cast as this cast happens automatically.
if (IsObjectCastInInterpolation(castNode, castType))
return true;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`
if (IsEnumToNumericCastThatCanDefinitelyBeRemoved(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
return false;
}
private static bool CastHasNoRuntimeImpact_Legacy(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Note: Legacy codepaths for determining if a cast is removable. As much as possible we should attempt to
// extract simple and clearly defined checks from here and move to CastDefinitelyHasNoRuntimeImpact.
// Then look for patterns for cases where we never want to remove casts.
if (CastMustBePreserved(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// If this changes static semantics (i.e. causes a different overload to be called), then we can't remove it.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
var castTypeInfo = semanticModel.GetTypeInfo(castNode, cancellationToken);
var castType = castTypeInfo.Type;
RoslynDebug.AssertNotNull(castType);
var expressionTypeInfo = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken);
var expressionType = expressionTypeInfo.Type;
var expressionToCastType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
var outerType = GetOuterCastType(castNode, semanticModel, out var parentIsOrAsExpression) ?? castTypeInfo.ConvertedType;
// Clearest case. We know we haven't changed static semantic, and we have an Identity (i.e. no-impact,
// representation-preserving) cast. This is always safe to remove.
//
// Note: while these casts are always safe to remove, there is a case where we still keep them.
// Specifically, if the compiler would warn that the code is no longer clear, then we will keep the cast
// around. These warning checks should go into CastMustBePreserved above.
if (expressionToCastType.IsIdentity)
return true;
// Is this a cast inside a conditional expression? Because of target typing we already sorted that out
// in ReplacementChangesSemantics()
if (IsBranchOfConditionalExpression(castNode))
{
return true;
}
// We already bailed out of we had an explicit/none conversions back in CastMustBePreserved
// (except for implicit user defined conversions).
Debug.Assert(!expressionToCastType.IsExplicit || expressionToCastType.IsUserDefined);
// At this point, the only type of conversion left are implicit or user-defined conversions. These may be
// conversions we can remove, but need further analysis.
Debug.Assert(expressionToCastType.IsImplicit || expressionToCastType.IsUserDefined);
if (expressionToCastType.IsInterpolatedString)
{
// interpolation casts are necessary to preserve semantics if our destination type is not itself
// FormattableString or some interface of FormattableString.
return castType.Equals(castTypeInfo.ConvertedType) ||
ImmutableArray<ITypeSymbol?>.CastUp(castType.AllInterfaces).Contains(castTypeInfo.ConvertedType);
}
if (castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression) &&
!castType.Equals(outerType) &&
outerType.IsNullable())
{
// We have a cast like `(T?)(X)default`. We can't remove the inner cast as it effects what value
// 'default' means in this context.
return false;
}
if (parentIsOrAsExpression)
{
// Note: speculationAnalyzer.ReplacementChangesSemantics() ensures that the parenting is or as expression are not broken.
// Here we just need to ensure that the original cast expression doesn't invoke a user defined operator.
return !expressionToCastType.IsUserDefined;
}
if (outerType != null)
{
var castToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castNode, outerType);
var expressionToOuterType = GetSpeculatedExpressionToOuterTypeConversion(speculationAnalyzer.ReplacedExpression, speculationAnalyzer, cancellationToken);
// if the conversion to the outer type doesn't exist, then we shouldn't offer, except for anonymous functions which can't be reasoned about the same way (see below)
if (!expressionToOuterType.Exists && !expressionToOuterType.IsAnonymousFunction)
{
return false;
}
// CONSIDER: Anonymous function conversions cannot be compared from different semantic models as lambda symbol comparison requires syntax tree equality. Should this be a compiler bug?
// For now, just revert back to computing expressionToOuterType using the original semantic model.
if (expressionToOuterType.IsAnonymousFunction)
{
expressionToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, outerType);
}
// If there is an user-defined conversion from the expression to the cast type or the cast
// to the outer type, we need to make sure that the same user-defined conversion will be
// called if the cast is removed.
if (castToOuterType.IsUserDefined || expressionToCastType.IsUserDefined)
{
return !expressionToOuterType.IsExplicit &&
(HaveSameUserDefinedConversion(expressionToCastType, expressionToOuterType) ||
HaveSameUserDefinedConversion(castToOuterType, expressionToOuterType)) &&
UserDefinedConversionIsAllowed(castNode);
}
else if (expressionToOuterType.IsUserDefined)
{
return false;
}
if (expressionToCastType.IsExplicit &&
expressionToOuterType.IsExplicit)
{
return false;
}
// If the conversion from the expression to the cast type is implicit numeric or constant
// and the conversion from the expression to the outer type is identity, we'll go ahead
// and remove the cast.
if (expressionToOuterType.IsIdentity &&
expressionToCastType.IsImplicit &&
(expressionToCastType.IsNumeric || expressionToCastType.IsConstantExpression))
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
if (!castToOuterType.IsBoxing &&
castToOuterType == expressionToOuterType)
{
if (castToOuterType.IsNullable)
{
// Even though both the nullable conversions (castToOuterType and expressionToOuterType) are equal, we can guarantee no data loss only if there is an
// implicit conversion from expression type to cast type and expression type is non-nullable. For example, consider the cast removal "(float?)" for below:
// Console.WriteLine((int)(float?)(int?)2147483647); // Prints -2147483648
// castToOuterType: ExplicitNullable
// expressionToOuterType: ExplicitNullable
// expressionToCastType: ImplicitNullable
// We should not remove the cast to "float?".
// However, cast to "int?" is unnecessary and should be removable.
return expressionToCastType.IsImplicit && !expressionType.IsNullable();
}
else if (expressionToCastType.IsImplicit && expressionToCastType.IsNumeric && !castToOuterType.IsIdentity)
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
return true;
}
if (castToOuterType.IsIdentity &&
!expressionToCastType.IsUnboxing &&
expressionToCastType == expressionToOuterType)
{
return true;
}
// Special case: It's possible to have useless casts inside delegate creation expressions.
// For example: new Func<string, bool>((Predicate<object>)(y => true)).
if (IsInDelegateCreationExpression(castNode, semanticModel))
{
if (expressionToCastType.IsAnonymousFunction && expressionToOuterType.IsAnonymousFunction)
{
return !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
if (expressionToCastType.IsMethodGroup && expressionToOuterType.IsMethodGroup)
{
return true;
}
}
// Case :
// 1. IList<object> y = (IList<dynamic>)new List<object>()
if (expressionToCastType.IsExplicit && castToOuterType.IsExplicit && expressionToOuterType.IsImplicit)
{
// If both expressionToCastType and castToOuterType are numeric, then this is a required cast as one of the conversions leads to loss of precision.
// Cast removal can change program behavior.
return !(expressionToCastType.IsNumeric && castToOuterType.IsNumeric);
}
// Case :
// 2. object y = (ValueType)1;
if (expressionToCastType.IsBoxing && expressionToOuterType.IsBoxing && castToOuterType.IsImplicit)
{
return true;
}
// Case :
// 3. object y = (NullableValueType)null;
if ((!castToOuterType.IsBoxing || expressionToCastType.IsNullLiteral) &&
castToOuterType.IsImplicit &&
expressionToCastType.IsImplicit &&
expressionToOuterType.IsImplicit)
{
if (expressionToOuterType.IsAnonymousFunction)
{
return expressionToCastType.IsAnonymousFunction &&
!speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
return true;
}
}
return false;
}
private static bool IsObjectCastInInterpolation(ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType)
{
// A casts to object can always be removed from an expression inside of an interpolation, since it'll be converted to object
// in order to call string.Format(...) anyway.
return castType?.SpecialType == SpecialType.System_Object &&
castNode.WalkUpParentheses().IsParentKind(SyntaxKind.Interpolation);
}
private static bool IsEnumToNumericCastThatCanDefinitelyBeRemoved(
ExpressionSyntax castNode,
[NotNullWhen(true)] ITypeSymbol? castType,
[NotNullWhen(true)] ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (!castedExpressionType.IsEnumType(out var castedEnumType))
return false;
if (!Equals(castType, castedEnumType.EnumUnderlyingType))
return false;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`.
castNode = castNode.WalkUpParentheses();
if (castNode.IsParentKind(SyntaxKind.BitwiseNotExpression, out PrefixUnaryExpressionSyntax? prefixUnary))
{
if (!prefixUnary.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax? parentCast))
return false;
// `(int)` in `(E?)~(int)e` is also redundant.
var parentCastType = semanticModel.GetTypeInfo(parentCast.Type, cancellationToken).Type;
if (parentCastType.IsNullable(out var underlyingType))
parentCastType = underlyingType;
return castedEnumType.Equals(parentCastType);
}
// if we have `(int)e == 0` then the cast can be removed. Note: this is only for the exact cast of
// comparing to the constant 0. All other comparisons are not allowed.
if (castNode.Parent is BinaryExpressionSyntax binaryExpression)
{
if (binaryExpression.IsKind(SyntaxKind.EqualsExpression) || binaryExpression.IsKind(SyntaxKind.NotEqualsExpression))
{
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
var otherSideType = semanticModel.GetTypeInfo(otherSide, cancellationToken).Type;
if (Equals(otherSideType, castedEnumType.EnumUnderlyingType))
{
var constantValue = semanticModel.GetConstantValue(otherSide, cancellationToken);
if (constantValue.HasValue &&
IntegerUtilities.IsIntegral(constantValue.Value) &&
IntegerUtilities.ToInt64(constantValue.Value) == 0)
{
return true;
}
}
}
}
return false;
}
private static bool CastMustBePreserved(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// If we don't understand the type, we must keep it.
if (castType == null)
return true;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
var conversion = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
// If we've got an error for some reason, then we don't want to touch this at all.
if (castType.IsErrorType())
return true;
// Almost all explicit conversions can cause an exception or data loss, hence can never be removed.
if (IsExplicitCastThatMustBePreserved(castNode, conversion))
return true;
// If this conversion doesn't even exist, then this code is in error, and we don't want to touch it.
if (!conversion.Exists)
return true;
// `dynamic` changes the semantics of everything and is rarely safe to remove. We could consider removing
// absolutely safe casts (i.e. `(dynamic)(dynamic)a`), but it's likely not worth the effort, so we just
// disallow touching them entirely.
if (InvolvesDynamic(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If removing the cast would cause the compiler to issue a specific warning, then we have to preserve it.
if (CastRemovalWouldCauseSignExtensionWarning(castNode, semanticModel, cancellationToken))
return true;
// *(T*)null. Can't remove this case.
if (IsDereferenceOfNullPointerCast(castNode, castedExpressionNode))
return true;
if (ParamsArgumentCastMustBePreserved(castNode, castType, semanticModel, cancellationToken))
return true;
// `... ? (int?)1 : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
//
// TODO(cyrusn): This should move into SpeculationAnalyzer as it's a static-semantics change.
if (CastMustBePreservedInConditionalBranch(castNode, conversion))
return true;
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
if (CastIsRequiredToPreventUnintendedComparisonWarning(castNode, castedExpressionNode, castType, semanticModel, cancellationToken))
return true;
// Identity fp-casts can actually change the runtime value of the fp number. This can happen because the
// runtime is allowed to perform the operations with wider precision than the actual specified fp-precision.
// i.e. 64-bit doubles can actually be 80 bits at runtime. Even though the language considers this to be an
// identity cast, we don't want to remove these because the user may be depending on that truncation.
RoslynDebug.Assert(!conversion.IsIdentity || castedExpressionType is not null);
if (IdentityFloatingPointCastMustBePreserved(castNode, castedExpressionNode, castType, castedExpressionType!, semanticModel, conversion, cancellationToken))
return true;
if (PointerOrIntPtrCastMustBePreserved(conversion))
return true;
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
if (IsTypeLessExpressionNotInTargetTypedLocation(castNode, castedExpressionType))
return true;
// If we have something like `(nuint)(nint)x` where x is an IntPtr then the nint cast cannot be removed
// as IntPtr to nuint is invalid.
if (IsIntPtrToNativeIntegerNestedCast(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If we have `~(ulong)uintVal` then we have to preserve the `(ulong)` cast. Otherwise, the `~` will
// operate on the shorter-bit value, before being extended out to the full length, rather than operating on
// the full length.
if (IsBitwiseNotOfExtendedUnsignedValue(castNode, conversion, castType, castedExpressionType))
return true;
return false;
}
private static bool IsBitwiseNotOfExtendedUnsignedValue(ExpressionSyntax castNode, Conversion conversion, ITypeSymbol castType, ITypeSymbol castedExressionType)
{
if (castNode.WalkUpParentheses().IsParentKind(SyntaxKind.BitwiseNotExpression) &&
conversion.IsImplicit &&
conversion.IsNumeric)
{
return IsUnsigned(castType) || IsUnsigned(castedExressionType);
}
return false;
}
private static bool IsUnsigned(ITypeSymbol type)
=> type.SpecialType.IsUnsignedIntegralType() || IsNuint(type);
private static bool IsNuint(ITypeSymbol type)
=> type.SpecialType == SpecialType.System_UIntPtr && type.IsNativeIntegerType;
private static bool IsIntPtrToNativeIntegerNestedCast(ExpressionSyntax castNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castedExpressionType == null)
{
return false;
}
if (castType.SpecialType is not (SpecialType.System_IntPtr or SpecialType.System_UIntPtr))
{
return false;
}
if (castNode.WalkUpParentheses().Parent is CastExpressionSyntax castExpression)
{
var parentCastType = semanticModel.GetTypeInfo(castExpression, cancellationToken).Type;
if (parentCastType == null)
{
return false;
}
// Given (nuint)(nint)myIntPtr we would normally suggest removing the (nint) cast as being identity
// but it is required as a means to get from IntPtr to nuint, and vice versa from UIntPtr to nint,
// so we check for an identity cast from [U]IntPtr to n[u]int and then to a number type.
if (castedExpressionType.SpecialType == castType.SpecialType &&
!castedExpressionType.IsNativeIntegerType &&
castType.IsNativeIntegerType &&
parentCastType.IsNumericType())
{
return true;
}
}
return false;
}
private static bool IsTypeLessExpressionNotInTargetTypedLocation(ExpressionSyntax castNode, [NotNullWhen(false)] ITypeSymbol? castedExpressionType)
{
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
// checked if the expression being casted is typeless.
if (castedExpressionType != null)
return false;
if (IsInTargetTypingLocation(castNode))
return false;
// we don't have our own type, and we're not in a location where a type can be inferred. don't remove this
// cast.
return true;
}
private static bool IsInTargetTypingLocation(ExpressionSyntax node)
{
node = node.WalkUpParentheses();
var parent = node.Parent;
// note: the list below is not intended to be exhaustive. For example there are places we can target type,
// but which we don't want to bother doing all the work to validate. For example, technically you can
// target type `throw (Exception)null`, so we could allow `(Exception)` to be removed. But it's such a corner
// case that we don't care about supporting, versus all the hugely valuable cases users will actually run into.
// also: the list doesn't have to be firmly accurate:
// 1. If we have a false positive and we say something is a target typing location, then that means we
// simply try to remove the cast, but then catch the break later.
// 2. If we have a false negative and we say something is not a target typing location, then we simply
// don't try to remove the cast and the user has no impact on their code.
// `null op e2`. Either side can target type the other.
if (parent is BinaryExpressionSyntax)
return true;
// `Goo(null)`. The type of the arg is target typed by the Goo method being called.
//
// This also helps Tuples fall out as they're built of arguments. i.e. `(string s, string y) = (null, null)`.
if (parent is ArgumentSyntax)
return true;
// same as above
if (parent is AttributeArgumentSyntax)
return true;
// `new SomeType[] { null }` or `new [] { null, expr }`.
// Type of the element can be target typed by the array type, or the sibling expression types.
if (parent is InitializerExpressionSyntax)
return true;
// `return null;`. target typed by whatever method this is in.
if (parent is ReturnStatementSyntax)
return true;
// `yield return null;` same as above.
if (parent is YieldStatementSyntax)
return true;
// `x = null`. target typed by the other side.
if (parent is AssignmentExpressionSyntax)
return true;
// ... = null
//
// handles: parameters, variable declarations and the like.
if (parent is EqualsValueClauseSyntax)
return true;
// `(SomeType)null`. Definitely can target type this type-less expression.
if (parent is CastExpressionSyntax)
return true;
// `... ? null : ...`. Either side can target type the other.
if (parent is ConditionalExpressionSyntax)
return true;
// case null:
if (parent is CaseSwitchLabelSyntax)
return true;
return false;
}
private static bool IsExplicitCastThatMustBePreserved(ExpressionSyntax castNode, Conversion conversion)
{
if (conversion.IsExplicit)
{
// Consider the explicit cast in a line like:
//
// string? s = conditional ? (string?)"hello" : null;
//
// That string? cast is an explicit conversion that not IsUserDefined, but it may be removable if we support
// target-typed conditionals; in that case we'll return false here and force the full algorithm to be ran rather
// than this fast-path.
if (IsBranchOfConditionalExpression(castNode) &&
!CastMustBePreservedInConditionalBranch(castNode, conversion))
{
return false;
}
// if it's not a user defined conversion, we must preserve it as it has runtime impact that we don't want to change.
if (!conversion.IsUserDefined)
return true;
// Casts that involve implicit conversions are still represented as explicit casts. Because they're
// implicit though, we may be able to remove it. i.e. if we have `(C)0 + (C)1` we can remove one of the
// casts because it will be inferred from the binary context.
var userMethod = conversion.MethodSymbol;
if (userMethod?.Name != WellKnownMemberNames.ImplicitConversionName)
return true;
}
return false;
}
private static bool PointerOrIntPtrCastMustBePreserved(Conversion conversion)
{
if (!conversion.IsIdentity)
return false;
// if we have a non-identity cast to an int* or IntPtr just do not touch this.
// https://github.com/dotnet/roslyn/issues/2987 tracks improving on this conservative approach.
//
// NOTE(cyrusn): This code should not be necessary. However there is additional code that deals with
// `*(x*)expr` ends up masking that this change should not be safe. That code is suspect and should be
// changed. Until then though we disable this.
return conversion.IsPointer || conversion.IsIntPtr;
}
private static bool InvolvesDynamic(
ExpressionSyntax castNode,
ITypeSymbol? castType,
ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// We do not remove any cast on
// 1. Dynamic Expressions
// 2. If there is any other argument which is dynamic
// 3. Dynamic Invocation
// 4. Assignment to dynamic
if (castType?.Kind == SymbolKind.DynamicType || castedExpressionType?.Kind == SymbolKind.DynamicType)
return true;
return IsDynamicInvocation(castNode, semanticModel, cancellationToken) ||
IsDynamicAssignment(castNode, semanticModel, cancellationToken);
}
private static bool IsDereferenceOfNullPointerCast(ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode)
{
return castNode.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) &&
castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression);
}
private static bool IsBranchOfConditionalExpression(ExpressionSyntax expression)
{
return expression.Parent is ConditionalExpressionSyntax conditionalExpression &&
expression != conditionalExpression.Condition;
}
private static bool CastMustBePreservedInConditionalBranch(
ExpressionSyntax castNode, Conversion conversion)
{
// `... ? (int?)i : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
// It's safe to remove the cast when it's an identity. for example:
// `... ? (int)1 : default`.
if (!conversion.IsIdentity)
{
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is ConditionalExpressionSyntax conditionalExpression)
{
if (conditionalExpression.WhenTrue == castNode ||
conditionalExpression.WhenFalse == castNode)
{
var otherSide = conditionalExpression.WhenTrue == castNode
? conditionalExpression.WhenFalse
: conditionalExpression.WhenTrue;
otherSide = otherSide.WalkDownParentheses();
// In C# 9 we can potentially remove the cast if the other side is null, since the cast was previously required to
// resolve a situation like:
//
// var x = condition ? (int?)i : null
//
// but it isn't with target-typed conditionals. We do have to keep the cast if it's default, as:
//
// var x = condition ? (int?)i : default
//
// is inferred by the compiler to mean 'default(int?)', whereas removing the cast would mean default(int).
var languageVersion = ((CSharpParseOptions)castNode.SyntaxTree.Options).LanguageVersion;
return (otherSide.IsKind(SyntaxKind.NullLiteralExpression) && languageVersion < LanguageVersion.CSharp9) ||
otherSide.IsKind(SyntaxKind.DefaultLiteralExpression);
}
}
}
return false;
}
private static bool CastRemovalWouldCauseSignExtensionWarning(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Logic copied from DiagnosticsPass_Warnings.CheckForBitwiseOrSignExtend. Including comments.
if (!(expression is CastExpressionSyntax castExpression))
return false;
var castRoot = castExpression.WalkUpParentheses();
// Check both binary-or, and assignment-or
//
// x | (...)y
// x |= (...)y
ExpressionSyntax leftOperand, rightOperand;
if (castRoot.Parent is BinaryExpressionSyntax parentBinary)
{
if (!parentBinary.IsKind(SyntaxKind.BitwiseOrExpression))
return false;
(leftOperand, rightOperand) = (parentBinary.Left, parentBinary.Right);
}
else if (castRoot.Parent is AssignmentExpressionSyntax parentAssignment)
{
if (!parentAssignment.IsKind(SyntaxKind.OrAssignmentExpression))
return false;
(leftOperand, rightOperand) = (parentAssignment.Left, parentAssignment.Right);
}
else
{
return false;
}
// The native compiler skips this warning if both sides of the operator are constants.
//
// CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short
// when they are non-constants, or when one is a constant, that we would similarly warn
// when both are constants.
var constantValue = semanticModel.GetConstantValue(castRoot.Parent, cancellationToken);
if (constantValue.HasValue && constantValue.Value != null)
return false;
// Start by determining *which bits on each side are going to be unexpectedly turned on*.
var leftOperation = semanticModel.GetOperation(leftOperand.WalkDownParentheses(), cancellationToken);
var rightOperation = semanticModel.GetOperation(rightOperand.WalkDownParentheses(), cancellationToken);
if (leftOperation == null || rightOperation == null)
return false;
// Note: we are asking the question about if there would be a problem removing the cast. So we have to act
// as if an explicit cast becomes an implicit one. We do this by ignoring the appropriate cast and not
// treating it as explicit when we encounter it.
var left = FindSurprisingSignExtensionBits(leftOperation, leftOperand == castRoot);
var right = FindSurprisingSignExtensionBits(rightOperation, rightOperand == castRoot);
// If they are all the same then there's no warning to give.
if (left == right)
return false;
// Suppress the warning if one side is a constant, and either all the unexpected
// bits are already off, or all the unexpected bits are already on.
var constVal = GetConstantValueForBitwiseOrCheck(leftOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & right) == right || (~val & right) == right)
return false;
}
constVal = GetConstantValueForBitwiseOrCheck(rightOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & left) == left || (~val & left) == left)
return false;
}
// This would produce a warning. Don't offer to remove the cast.
return true;
}
private static ulong? GetConstantValueForBitwiseOrCheck(IOperation operation)
{
// We might have a nullable conversion on top of an integer constant. But only dig out
// one level.
if (operation is IConversionOperation conversion &&
conversion.Conversion.IsImplicit &&
conversion.Conversion.IsNullable)
{
operation = conversion.Operand;
}
var constantValue = operation.ConstantValue;
if (!constantValue.HasValue || constantValue.Value == null)
return null;
RoslynDebug.Assert(operation.Type is not null);
if (!operation.Type.SpecialType.IsIntegralType())
return null;
return IntegerUtilities.ToUInt64(constantValue.Value);
}
// A "surprising" sign extension is:
//
// * a conversion with no cast in source code that goes from a smaller
// signed type to a larger signed or unsigned type.
//
// * an conversion (with or without a cast) from a smaller
// signed type to a larger unsigned type.
private static ulong FindSurprisingSignExtensionBits(IOperation? operation, bool treatExplicitCastAsImplicit)
{
if (!(operation is IConversionOperation conversion))
return 0;
var from = conversion.Operand.Type;
var to = conversion.Type;
if (from is null || to is null)
return 0;
if (from.IsNullable(out var fromUnderlying))
from = fromUnderlying;
if (to.IsNullable(out var toUnderlying))
to = toUnderlying;
var fromSpecialType = from.SpecialType;
var toSpecialType = to.SpecialType;
if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType())
return 0;
var fromSize = fromSpecialType.SizeInBytes();
var toSize = toSpecialType.SizeInBytes();
if (fromSize == 0 || toSize == 0)
return 0;
// The operand might itself be a conversion, and might be contributing
// surprising bits. We might have more, fewer or the same surprising bits
// as the operand.
var recursive = FindSurprisingSignExtensionBits(conversion.Operand, treatExplicitCastAsImplicit: false);
if (fromSize == toSize)
{
// No change.
return recursive;
}
if (toSize < fromSize)
{
// We are casting from a larger type to a smaller type, and are therefore
// losing surprising bits.
switch (toSize)
{
case 1: return unchecked((ulong)(byte)recursive);
case 2: return unchecked((ulong)(ushort)recursive);
case 4: return unchecked((ulong)(uint)recursive);
}
Debug.Assert(false, "How did we get here?");
return recursive;
}
// We are converting from a smaller type to a larger type, and therefore might
// be adding surprising bits. First of all, the smaller type has got to be signed
// for there to be sign extension.
var fromSigned = fromSpecialType.IsSignedIntegralType();
if (!fromSigned)
return recursive;
// OK, we know that the "from" type is a signed integer that is smaller than the
// "to" type, so we are going to have sign extension. Is it surprising? The only
// time that sign extension is *not* surprising is when we have a cast operator
// to a *signed* type. That is, (int)myShort is not a surprising sign extension.
var explicitInCode = !conversion.IsImplicit;
if (!treatExplicitCastAsImplicit &&
explicitInCode &&
toSpecialType.IsSignedIntegralType())
{
return recursive;
}
// Note that we *could* be somewhat more clever here. Consider the following edge case:
//
// (ulong)(int)(uint)(ushort)mySbyte
//
// We could reason that the sbyte-to-ushort conversion is going to add one byte of
// unexpected sign extension. The conversion from ushort to uint adds no more bytes.
// The conversion from uint to int adds no more bytes. Does the conversion from int
// to ulong add any more bytes of unexpected sign extension? Well, no, because we
// know that the previous conversion from ushort to uint will ensure that the top bit
// of the uint is off!
//
// But we are not going to try to be that clever. In the extremely unlikely event that
// someone does this, we will record that the unexpectedly turned-on bits are
// 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00
// are the unexpected bits.
var result = recursive;
for (var i = fromSize; i < toSize; ++i)
result |= (0xFFUL) << (i * 8);
return result;
}
private static bool IdentityFloatingPointCastMustBePreserved(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
ITypeSymbol castType, ITypeSymbol castedExpressionType,
SemanticModel semanticModel, Conversion conversion, CancellationToken cancellationToken)
{
if (!conversion.IsIdentity)
return false;
// Floating point casts can have subtle runtime behavior, even between the same fp types. For example, a
// cast from float-to-float can still change behavior because it may take a higher precision computation and
// truncate it to 32bits.
//
// Because of this we keep floating point conversions unless we can prove that it's safe. The only safe
// times are when we're loading or storing into a location we know has the same size as the cast size
// (i.e. reading/writing into a field).
if (castedExpressionType.SpecialType != SpecialType.System_Double &&
castedExpressionType.SpecialType != SpecialType.System_Single &&
castType.SpecialType != SpecialType.System_Double &&
castType.SpecialType != SpecialType.System_Single)
{
// wasn't a floating point conversion.
return false;
}
// Identity fp conversion is safe if this is a read from a fp field/array
if (IsFieldOrArrayElement(semanticModel, castedExpressionNode, cancellationToken))
return false;
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is AssignmentExpressionSyntax assignmentExpression &&
assignmentExpression.Right == castNode)
{
// Identity fp conversion is safe if this is a write to a fp field/array
if (IsFieldOrArrayElement(semanticModel, assignmentExpression.Left, cancellationToken))
return false;
}
else if (castNode.Parent.IsKind(SyntaxKind.ArrayInitializerExpression, out InitializerExpressionSyntax? arrayInitializer))
{
// Identity fp conversion is safe if this is in an array initializer.
var typeInfo = semanticModel.GetTypeInfo(arrayInitializer, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.ArrayType;
}
else if (castNode.Parent is EqualsValueClauseSyntax equalsValue &&
equalsValue.Value == castNode &&
equalsValue.Parent is VariableDeclaratorSyntax variableDeclarator)
{
// Identity fp conversion is safe if this is in a field initializer.
var symbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
if (symbol?.Kind == SymbolKind.Field)
return false;
}
// We have to preserve this cast.
return true;
}
private static bool IsFieldOrArrayElement(
SemanticModel semanticModel, ExpressionSyntax expr, CancellationToken cancellationToken)
{
expr = expr.WalkDownParentheses();
var castedExpresionSymbol = semanticModel.GetSymbolInfo(expr, cancellationToken).Symbol;
// we're reading from a field of the same size. it's safe to remove this case.
if (castedExpresionSymbol?.Kind == SymbolKind.Field)
return true;
if (expr is ElementAccessExpressionSyntax elementAccess)
{
var locationType = semanticModel.GetTypeInfo(elementAccess.Expression, cancellationToken);
return locationType.Type?.Kind == SymbolKind.ArrayType;
}
return false;
}
private static bool HaveSameUserDefinedConversion(Conversion conversion1, Conversion conversion2)
{
return conversion1.IsUserDefined
&& conversion2.IsUserDefined
&& Equals(conversion1.MethodSymbol, conversion2.MethodSymbol);
}
private static bool IsInDelegateCreationExpression(
ExpressionSyntax castNode, SemanticModel semanticModel)
{
if (!(castNode.WalkUpParentheses().Parent is ArgumentSyntax argument))
{
return false;
}
if (!(argument.Parent is ArgumentListSyntax argumentList))
{
return false;
}
if (!(argumentList.Parent is ObjectCreationExpressionSyntax objectCreation))
{
return false;
}
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type).Symbol;
return typeSymbol != null
&& typeSymbol.IsDelegateType();
}
private static bool IsDynamicInvocation(
ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castExpression.WalkUpParentheses().IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) &&
argument.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList) &&
argument.Parent.Parent.IsKind(SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression))
{
var typeInfo = semanticModel.GetTypeInfo(argument.Parent.Parent, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsDynamicAssignment(ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
castExpression = castExpression.WalkUpParentheses();
if (castExpression.IsRightSideOfAnyAssignExpression())
{
var assignmentExpression = (AssignmentExpressionSyntax)castExpression.Parent!;
var assignmentType = semanticModel.GetTypeInfo(assignmentExpression.Left, cancellationToken).Type;
return assignmentType?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsRequiredImplicitNumericConversion(ITypeSymbol sourceType, ITypeSymbol destinationType)
{
// C# Language Specification: Section 6.1.2 Implicit numeric conversions
// Conversions from int, uint, long, or ulong to float and from long or ulong to double may cause a loss of precision,
// but will never cause a loss of magnitude. The other implicit numeric conversions never lose any information.
switch (destinationType.SpecialType)
{
case SpecialType.System_Single:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
case SpecialType.System_Double:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
default:
return false;
}
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Based on the check in DiagnosticPass.CheckRelationals.
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
// compiler: if (node.Left.Type.SpecialType == SpecialType.System_Object
if (castType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual
castNode = castNode.WalkUpParentheses();
var parent = castNode.Parent;
if (!(parent is BinaryExpressionSyntax binaryExpression))
return false;
if (!binaryExpression.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression))
return false;
var binaryMethod = semanticModel.GetSymbolInfo(binaryExpression, cancellationToken).Symbol as IMethodSymbol;
if (binaryMethod == null)
return false;
if (binaryMethod.ContainingType?.SpecialType != SpecialType.System_Object)
return false;
var operatorName = binaryMethod.Name;
if (operatorName != WellKnownMemberNames.EqualityOperatorName && operatorName != WellKnownMemberNames.InequalityOperatorName)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
otherSide = otherSide.WalkDownParentheses();
return CastIsRequiredToPreventUnintendedComparisonWarning(castedExpressionNode, otherSide, operatorName, semanticModel, cancellationToken) ||
CastIsRequiredToPreventUnintendedComparisonWarning(otherSide, castedExpressionNode, operatorName, semanticModel, cancellationToken);
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax left, ExpressionSyntax right, string operatorName,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// compiler: node.Left.Type.SpecialType == SpecialType.System_Object
var leftType = semanticModel.GetTypeInfo(left, cancellationToken).Type;
if (leftType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: && !IsExplicitCast(node.Left)
if (left.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull)
var constantValue = semanticModel.GetConstantValue(left, cancellationToken);
if (constantValue.HasValue && constantValue.Value is null)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
// Code for: ConvertedHasEqual
// compiler: if (conv.ExplicitCastInCode) return false;
if (right.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol;
// if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface)
var otherSideType = semanticModel.GetTypeInfo(right, cancellationToken).Type as INamedTypeSymbol;
if (otherSideType == null)
return false;
if (!otherSideType.IsReferenceType || otherSideType.TypeKind == TypeKind.Interface)
return false;
// compiler: for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics)
for (var currentType = otherSideType; currentType != null; currentType = currentType.BaseType)
{
// compiler: foreach (var sym in t.GetMembers(opName))
foreach (var opMember in currentType.GetMembers(operatorName))
{
// compiler: MethodSymbol op = sym as MethodSymbol;
var opMethod = opMember as IMethodSymbol;
// compiler: if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue;
if (opMethod == null || opMethod.MethodKind != MethodKind.UserDefinedOperator)
continue;
// compiler: var parameters = op.GetParameters();
// if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2))
// return true
var parameters = opMethod.Parameters;
if (parameters.Length == 2 && Equals(parameters[0].Type, currentType) && Equals(parameters[1].Type, currentType))
return true;
}
}
return false;
}
private static Conversion GetSpeculatedExpressionToOuterTypeConversion(ExpressionSyntax speculatedExpression, SpeculationAnalyzer speculationAnalyzer, CancellationToken cancellationToken)
{
var typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(speculatedExpression, cancellationToken);
var conversion = speculationAnalyzer.SpeculativeSemanticModel.GetConversion(speculatedExpression, cancellationToken);
if (!conversion.IsIdentity)
{
return conversion;
}
var speculatedExpressionOuterType = GetOuterCastType(speculatedExpression, speculationAnalyzer.SpeculativeSemanticModel, out _) ?? typeInfo.ConvertedType;
if (speculatedExpressionOuterType == null)
{
return default;
}
return speculationAnalyzer.SpeculativeSemanticModel.ClassifyConversion(speculatedExpression, speculatedExpressionOuterType);
}
private static bool UserDefinedConversionIsAllowed(ExpressionSyntax expression)
{
expression = expression.WalkUpParentheses();
var parentNode = expression.Parent;
if (parentNode == null)
{
return false;
}
if (parentNode.IsKind(SyntaxKind.ThrowStatement))
{
return false;
}
return true;
}
private static bool ParamsArgumentCastMustBePreserved(
ExpressionSyntax cast,
ITypeSymbol castType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// When a casted value is passed as the single argument to a params parameter,
// we can only remove the cast if it is implicitly convertible to the parameter's type,
// but not the parameter's element type. Otherwise, we could end up changing the invocation
// to pass an array rather than an array with a single element.
//
// IOW, given the following method...
//
// static void Goo(params object[] x) { }
//
// ...we should remove this cast...
//
// Goo((object[])null);
//
// ...but not this cast...
//
// Goo((object)null);
var parent = cast.WalkUpParentheses().Parent;
if (parent is ArgumentSyntax argument)
{
// If there are any arguments to the right (and the argument is not named), we can assume that this is
// not a *single* argument passed to a params parameter.
if (argument.NameColon == null && argument.Parent is BaseArgumentListSyntax argumentList)
{
var argumentIndex = argumentList.Arguments.IndexOf(argument);
if (argumentIndex < argumentList.Arguments.Count - 1)
{
return false;
}
}
var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
if (parent is AttributeArgumentSyntax attributeArgument)
{
if (attributeArgument.Parent is AttributeArgumentListSyntax)
{
// We don't check the position of the argument because in attributes it is allowed that
// params parameter are positioned in between if named arguments are used.
var parameter = attributeArgument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
}
return false;
}
private static bool ParameterTypeMatchesParamsElementType([NotNullWhen(true)] IParameterSymbol? parameter, ITypeSymbol castType, SemanticModel semanticModel)
{
if (parameter?.IsParams == true)
{
// if the method is defined with errors: void M(params int wrongDefined), parameter.IsParams == true but parameter.Type is not an array.
// In such cases is better to be conservative and opt out.
if (!(parameter.Type is IArrayTypeSymbol parameterType))
{
return true;
}
var conversion = semanticModel.Compilation.ClassifyConversion(castType, parameterType);
if (conversion.Exists &&
conversion.IsImplicit)
{
return false;
}
var conversionElementType = semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType);
if (conversionElementType.Exists &&
conversionElementType.IsImplicit)
{
return true;
}
}
return false;
}
private static ITypeSymbol? GetOuterCastType(
ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsIsOrAsExpression)
{
expression = expression.WalkUpParentheses();
parentIsIsOrAsExpression = false;
var parentNode = expression.Parent;
if (parentNode == null)
{
return null;
}
if (parentNode.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression))
{
return semanticModel.GetTypeInfo(castExpression).Type;
}
if (parentNode.IsKind(SyntaxKind.PointerIndirectionExpression))
{
return semanticModel.GetTypeInfo(expression).Type;
}
if (parentNode.IsKind(SyntaxKind.IsExpression) ||
parentNode.IsKind(SyntaxKind.AsExpression))
{
parentIsIsOrAsExpression = true;
return null;
}
if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier))
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32);
}
if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess))
{
if (memberAccess.Expression == expression)
{
var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol;
if (memberSymbol != null)
{
return memberSymbol.ContainingType;
}
}
}
if (parentNode.IsKind(SyntaxKind.ConditionalExpression) &&
((ConditionalExpressionSyntax)parentNode).Condition == expression)
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean);
}
if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) &&
!semanticModel.GetConversion(expression).IsUserDefined)
{
var parentExpression = (ExpressionSyntax)parentNode;
return GetOuterCastType(parentExpression, semanticModel, out parentIsIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentExpression).ConvertedType;
}
if (parentNode is InterpolationSyntax)
{
// $"{(x)y}"
//
// Regardless of the cast to 'x', being in an interpolation automatically casts the result to object
// since this becomes a call to: FormattableStringFactory.Create(string, params object[]).
return semanticModel.Compilation.ObjectType;
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
internal static class CastSimplifier
{
public static bool IsUnnecessaryCast(ExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast is CastExpressionSyntax castExpression ? IsUnnecessaryCast(castExpression, semanticModel, cancellationToken) :
cast is BinaryExpressionSyntax binaryExpression ? IsUnnecessaryAsCast(binaryExpression, semanticModel, cancellationToken) : false;
public static bool IsUnnecessaryCast(CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> IsCastSafeToRemove(cast, cast.Expression, semanticModel, cancellationToken);
public static bool IsUnnecessaryAsCast(BinaryExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast.Kind() == SyntaxKind.AsExpression &&
IsCastSafeToRemove(cast, cast.Left, semanticModel, cancellationToken);
private static bool IsCastSafeToRemove(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(castNode,
castedExpressionNode, semanticModel, cancellationToken,
skipVerificationForReplacedNode: true, failOnOverloadResolutionFailuresInOriginalCode: true);
// First, check to see if the node ultimately parenting this cast has any
// syntax errors. If so, we bail.
if (speculationAnalyzer.SemanticRootOfOriginalExpression.ContainsDiagnostics)
return false;
// Now perform basic checks looking for a few things:
//
// 1. casts that must stay because removal will produce actually illegal code.
// 2. casts that must stay because they have runtime impact (i.e. could cause exceptions to be thrown).
// 3. casts that *seem* unnecessary because they don't violate the above, and the cast seems like it has no
// effect at runtime (i.e. casting a `string` to `object`). Note: just because the cast seems like it
// will have not runtime impact doesn't mean we can remove it. It still may be necessary to preserve the
// meaning of the code (for example for overload resolution). That check will occur after this.
//
// This is the fundamental separation between CastHasNoRuntimeImpact and
// speculationAnalyzer.ReplacementChangesSemantics. The former is simple and is only asking if the cast
// seems like it would have no impact *at runtime*. The latter ensures that the static meaning of the code
// is preserved.
//
// When adding/updating checks keep the above in mind to determine where the check should go.
var castHasRuntimeImpact = CastHasRuntimeImpact(
speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
if (castHasRuntimeImpact)
return false;
// Cast has no runtime effect. But it may change static semantics. Only allow removal if static semantics
// don't change.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
return true;
}
private static bool CastHasRuntimeImpact(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Look for simple patterns we know will never cause any runtime changes.
if (CastDefinitelyHasNoRuntimeImpact(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// Call into our legacy codepath that tries to make the same determination.
return !CastHasNoRuntimeImpact_Legacy(speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
}
private static bool CastDefinitelyHasNoRuntimeImpact(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// NOTE: Keep this method simple. Each type of runtime impact check should just be a new check added
// independently from the rest. We want to make it very clear exactly which cases each check is covering.
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
// $"x {(object)y} z" It's always safe to remove this `(object)` cast as this cast happens automatically.
if (IsObjectCastInInterpolation(castNode, castType))
return true;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`
if (IsEnumToNumericCastThatCanDefinitelyBeRemoved(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
return false;
}
private static bool CastHasNoRuntimeImpact_Legacy(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Note: Legacy codepaths for determining if a cast is removable. As much as possible we should attempt to
// extract simple and clearly defined checks from here and move to CastDefinitelyHasNoRuntimeImpact.
// Then look for patterns for cases where we never want to remove casts.
if (CastMustBePreserved(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// If this changes static semantics (i.e. causes a different overload to be called), then we can't remove it.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
var castTypeInfo = semanticModel.GetTypeInfo(castNode, cancellationToken);
var castType = castTypeInfo.Type;
RoslynDebug.AssertNotNull(castType);
var expressionTypeInfo = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken);
var expressionType = expressionTypeInfo.Type;
var expressionToCastType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
var outerType = GetOuterCastType(castNode, semanticModel, out var parentIsOrAsExpression) ?? castTypeInfo.ConvertedType;
// Clearest case. We know we haven't changed static semantic, and we have an Identity (i.e. no-impact,
// representation-preserving) cast. This is always safe to remove.
//
// Note: while these casts are always safe to remove, there is a case where we still keep them.
// Specifically, if the compiler would warn that the code is no longer clear, then we will keep the cast
// around. These warning checks should go into CastMustBePreserved above.
if (expressionToCastType.IsIdentity)
return true;
// Is this a cast inside a conditional expression? Because of target typing we already sorted that out
// in ReplacementChangesSemantics()
if (IsBranchOfConditionalExpression(castNode))
{
return true;
}
// We already bailed out of we had an explicit/none conversions back in CastMustBePreserved
// (except for implicit user defined conversions).
Debug.Assert(!expressionToCastType.IsExplicit || expressionToCastType.IsUserDefined);
// At this point, the only type of conversion left are implicit or user-defined conversions. These may be
// conversions we can remove, but need further analysis.
Debug.Assert(expressionToCastType.IsImplicit || expressionToCastType.IsUserDefined);
if (expressionToCastType.IsInterpolatedString)
{
// interpolation casts are necessary to preserve semantics if our destination type is not itself
// FormattableString or some interface of FormattableString.
return castType.Equals(castTypeInfo.ConvertedType) ||
ImmutableArray<ITypeSymbol?>.CastUp(castType.AllInterfaces).Contains(castTypeInfo.ConvertedType);
}
if (castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression) &&
!castType.Equals(outerType) &&
outerType.IsNullable())
{
// We have a cast like `(T?)(X)default`. We can't remove the inner cast as it effects what value
// 'default' means in this context.
return false;
}
if (parentIsOrAsExpression)
{
// Note: speculationAnalyzer.ReplacementChangesSemantics() ensures that the parenting is or as expression are not broken.
// Here we just need to ensure that the original cast expression doesn't invoke a user defined operator.
return !expressionToCastType.IsUserDefined;
}
if (outerType != null)
{
var castToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castNode, outerType);
var expressionToOuterType = GetSpeculatedExpressionToOuterTypeConversion(speculationAnalyzer.ReplacedExpression, speculationAnalyzer, cancellationToken);
// if the conversion to the outer type doesn't exist, then we shouldn't offer, except for anonymous functions which can't be reasoned about the same way (see below)
if (!expressionToOuterType.Exists && !expressionToOuterType.IsAnonymousFunction)
{
return false;
}
// CONSIDER: Anonymous function conversions cannot be compared from different semantic models as lambda symbol comparison requires syntax tree equality. Should this be a compiler bug?
// For now, just revert back to computing expressionToOuterType using the original semantic model.
if (expressionToOuterType.IsAnonymousFunction)
{
expressionToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, outerType);
}
// If there is an user-defined conversion from the expression to the cast type or the cast
// to the outer type, we need to make sure that the same user-defined conversion will be
// called if the cast is removed.
if (castToOuterType.IsUserDefined || expressionToCastType.IsUserDefined)
{
return !expressionToOuterType.IsExplicit &&
(HaveSameUserDefinedConversion(expressionToCastType, expressionToOuterType) ||
HaveSameUserDefinedConversion(castToOuterType, expressionToOuterType)) &&
UserDefinedConversionIsAllowed(castNode);
}
else if (expressionToOuterType.IsUserDefined)
{
return false;
}
if (expressionToCastType.IsExplicit &&
expressionToOuterType.IsExplicit)
{
return false;
}
// If the conversion from the expression to the cast type is implicit numeric or constant
// and the conversion from the expression to the outer type is identity, we'll go ahead
// and remove the cast.
if (expressionToOuterType.IsIdentity &&
expressionToCastType.IsImplicit &&
(expressionToCastType.IsNumeric || expressionToCastType.IsConstantExpression))
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
if (!castToOuterType.IsBoxing &&
castToOuterType == expressionToOuterType)
{
if (castToOuterType.IsNullable)
{
// Even though both the nullable conversions (castToOuterType and expressionToOuterType) are equal, we can guarantee no data loss only if there is an
// implicit conversion from expression type to cast type and expression type is non-nullable. For example, consider the cast removal "(float?)" for below:
// Console.WriteLine((int)(float?)(int?)2147483647); // Prints -2147483648
// castToOuterType: ExplicitNullable
// expressionToOuterType: ExplicitNullable
// expressionToCastType: ImplicitNullable
// We should not remove the cast to "float?".
// However, cast to "int?" is unnecessary and should be removable.
return expressionToCastType.IsImplicit && !expressionType.IsNullable();
}
else if (expressionToCastType.IsImplicit && expressionToCastType.IsNumeric && !castToOuterType.IsIdentity)
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
return true;
}
if (castToOuterType.IsIdentity &&
!expressionToCastType.IsUnboxing &&
expressionToCastType == expressionToOuterType)
{
return true;
}
// Special case: It's possible to have useless casts inside delegate creation expressions.
// For example: new Func<string, bool>((Predicate<object>)(y => true)).
if (IsInDelegateCreationExpression(castNode, semanticModel))
{
if (expressionToCastType.IsAnonymousFunction && expressionToOuterType.IsAnonymousFunction)
{
return !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
if (expressionToCastType.IsMethodGroup && expressionToOuterType.IsMethodGroup)
{
return true;
}
}
// Case :
// 1. IList<object> y = (IList<dynamic>)new List<object>()
if (expressionToCastType.IsExplicit && castToOuterType.IsExplicit && expressionToOuterType.IsImplicit)
{
// If both expressionToCastType and castToOuterType are numeric, then this is a required cast as one of the conversions leads to loss of precision.
// Cast removal can change program behavior.
return !(expressionToCastType.IsNumeric && castToOuterType.IsNumeric);
}
// Case :
// 2. object y = (ValueType)1;
if (expressionToCastType.IsBoxing && expressionToOuterType.IsBoxing && castToOuterType.IsImplicit)
{
return true;
}
// Case :
// 3. object y = (NullableValueType)null;
if ((!castToOuterType.IsBoxing || expressionToCastType.IsNullLiteral) &&
castToOuterType.IsImplicit &&
expressionToCastType.IsImplicit &&
expressionToOuterType.IsImplicit)
{
if (expressionToOuterType.IsAnonymousFunction)
{
return expressionToCastType.IsAnonymousFunction &&
!speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
return true;
}
}
return false;
}
private static bool IsObjectCastInInterpolation(ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType)
{
// A casts to object can always be removed from an expression inside of an interpolation, since it'll be converted to object
// in order to call string.Format(...) anyway.
return castType?.SpecialType == SpecialType.System_Object &&
castNode.WalkUpParentheses().IsParentKind(SyntaxKind.Interpolation);
}
private static bool IsEnumToNumericCastThatCanDefinitelyBeRemoved(
ExpressionSyntax castNode,
[NotNullWhen(true)] ITypeSymbol? castType,
[NotNullWhen(true)] ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (!castedExpressionType.IsEnumType(out var castedEnumType))
return false;
if (!Equals(castType, castedEnumType.EnumUnderlyingType))
return false;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`.
castNode = castNode.WalkUpParentheses();
if (castNode.IsParentKind(SyntaxKind.BitwiseNotExpression, out PrefixUnaryExpressionSyntax? prefixUnary))
{
if (!prefixUnary.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax? parentCast))
return false;
// `(int)` in `(E?)~(int)e` is also redundant.
var parentCastType = semanticModel.GetTypeInfo(parentCast.Type, cancellationToken).Type;
if (parentCastType.IsNullable(out var underlyingType))
parentCastType = underlyingType;
return castedEnumType.Equals(parentCastType);
}
// if we have `(int)e == 0` then the cast can be removed. Note: this is only for the exact cast of
// comparing to the constant 0. All other comparisons are not allowed.
if (castNode.Parent is BinaryExpressionSyntax binaryExpression)
{
if (binaryExpression.IsKind(SyntaxKind.EqualsExpression) || binaryExpression.IsKind(SyntaxKind.NotEqualsExpression))
{
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
var otherSideType = semanticModel.GetTypeInfo(otherSide, cancellationToken).Type;
if (Equals(otherSideType, castedEnumType.EnumUnderlyingType))
{
var constantValue = semanticModel.GetConstantValue(otherSide, cancellationToken);
if (constantValue.HasValue &&
IntegerUtilities.IsIntegral(constantValue.Value) &&
IntegerUtilities.ToInt64(constantValue.Value) == 0)
{
return true;
}
}
}
}
return false;
}
private static bool CastMustBePreserved(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// If we don't understand the type, we must keep it.
if (castType == null)
return true;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
var conversion = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
// If we've got an error for some reason, then we don't want to touch this at all.
if (castType.IsErrorType())
return true;
// Almost all explicit conversions can cause an exception or data loss, hence can never be removed.
if (IsExplicitCastThatMustBePreserved(castNode, conversion))
return true;
// If this conversion doesn't even exist, then this code is in error, and we don't want to touch it.
if (!conversion.Exists)
return true;
// `dynamic` changes the semantics of everything and is rarely safe to remove. We could consider removing
// absolutely safe casts (i.e. `(dynamic)(dynamic)a`), but it's likely not worth the effort, so we just
// disallow touching them entirely.
if (InvolvesDynamic(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If removing the cast would cause the compiler to issue a specific warning, then we have to preserve it.
if (CastRemovalWouldCauseSignExtensionWarning(castNode, semanticModel, cancellationToken))
return true;
// *(T*)null. Can't remove this case.
if (IsDereferenceOfNullPointerCast(castNode, castedExpressionNode))
return true;
if (ParamsArgumentCastMustBePreserved(castNode, castType, semanticModel, cancellationToken))
return true;
// `... ? (int?)1 : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
//
// TODO(cyrusn): This should move into SpeculationAnalyzer as it's a static-semantics change.
if (CastMustBePreservedInConditionalBranch(castNode, conversion))
return true;
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
if (CastIsRequiredToPreventUnintendedComparisonWarning(castNode, castedExpressionNode, castType, semanticModel, cancellationToken))
return true;
// Identity fp-casts can actually change the runtime value of the fp number. This can happen because the
// runtime is allowed to perform the operations with wider precision than the actual specified fp-precision.
// i.e. 64-bit doubles can actually be 80 bits at runtime. Even though the language considers this to be an
// identity cast, we don't want to remove these because the user may be depending on that truncation.
RoslynDebug.Assert(!conversion.IsIdentity || castedExpressionType is not null);
if (IdentityFloatingPointCastMustBePreserved(castNode, castedExpressionNode, castType, castedExpressionType!, semanticModel, conversion, cancellationToken))
return true;
if (PointerOrIntPtrCastMustBePreserved(conversion))
return true;
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
if (IsTypeLessExpressionNotInTargetTypedLocation(castNode, castedExpressionType))
return true;
// If we have something like `(nuint)(nint)x` where x is an IntPtr then the nint cast cannot be removed
// as IntPtr to nuint is invalid.
if (IsIntPtrToNativeIntegerNestedCast(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If we have `~(ulong)uintVal` then we have to preserve the `(ulong)` cast. Otherwise, the `~` will
// operate on the shorter-bit value, before being extended out to the full length, rather than operating on
// the full length.
if (IsBitwiseNotOfExtendedUnsignedValue(castNode, conversion, castType, castedExpressionType))
return true;
return false;
}
private static bool IsBitwiseNotOfExtendedUnsignedValue(ExpressionSyntax castNode, Conversion conversion, ITypeSymbol castType, ITypeSymbol castedExressionType)
{
if (castNode.WalkUpParentheses().IsParentKind(SyntaxKind.BitwiseNotExpression) &&
conversion.IsImplicit &&
conversion.IsNumeric)
{
return IsUnsigned(castType) || IsUnsigned(castedExressionType);
}
return false;
}
private static bool IsUnsigned(ITypeSymbol type)
=> type.SpecialType.IsUnsignedIntegralType() || IsNuint(type);
private static bool IsNuint(ITypeSymbol type)
=> type.SpecialType == SpecialType.System_UIntPtr && type.IsNativeIntegerType;
private static bool IsIntPtrToNativeIntegerNestedCast(ExpressionSyntax castNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castedExpressionType == null)
{
return false;
}
if (castType.SpecialType is not (SpecialType.System_IntPtr or SpecialType.System_UIntPtr))
{
return false;
}
if (castNode.WalkUpParentheses().Parent is CastExpressionSyntax castExpression)
{
var parentCastType = semanticModel.GetTypeInfo(castExpression, cancellationToken).Type;
if (parentCastType == null)
{
return false;
}
// Given (nuint)(nint)myIntPtr we would normally suggest removing the (nint) cast as being identity
// but it is required as a means to get from IntPtr to nuint, and vice versa from UIntPtr to nint,
// so we check for an identity cast from [U]IntPtr to n[u]int and then to a number type.
if (castedExpressionType.SpecialType == castType.SpecialType &&
!castedExpressionType.IsNativeIntegerType &&
castType.IsNativeIntegerType &&
parentCastType.IsNumericType())
{
return true;
}
}
return false;
}
private static bool IsTypeLessExpressionNotInTargetTypedLocation(ExpressionSyntax castNode, [NotNullWhen(false)] ITypeSymbol? castedExpressionType)
{
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
// checked if the expression being casted is typeless.
if (castedExpressionType != null)
return false;
if (IsInTargetTypingLocation(castNode))
return false;
// we don't have our own type, and we're not in a location where a type can be inferred. don't remove this
// cast.
return true;
}
private static bool IsInTargetTypingLocation(ExpressionSyntax node)
{
node = node.WalkUpParentheses();
var parent = node.Parent;
// note: the list below is not intended to be exhaustive. For example there are places we can target type,
// but which we don't want to bother doing all the work to validate. For example, technically you can
// target type `throw (Exception)null`, so we could allow `(Exception)` to be removed. But it's such a corner
// case that we don't care about supporting, versus all the hugely valuable cases users will actually run into.
// also: the list doesn't have to be firmly accurate:
// 1. If we have a false positive and we say something is a target typing location, then that means we
// simply try to remove the cast, but then catch the break later.
// 2. If we have a false negative and we say something is not a target typing location, then we simply
// don't try to remove the cast and the user has no impact on their code.
// `null op e2`. Either side can target type the other.
if (parent is BinaryExpressionSyntax)
return true;
// `Goo(null)`. The type of the arg is target typed by the Goo method being called.
//
// This also helps Tuples fall out as they're built of arguments. i.e. `(string s, string y) = (null, null)`.
if (parent is ArgumentSyntax)
return true;
// same as above
if (parent is AttributeArgumentSyntax)
return true;
// `new SomeType[] { null }` or `new [] { null, expr }`.
// Type of the element can be target typed by the array type, or the sibling expression types.
if (parent is InitializerExpressionSyntax)
return true;
// `return null;`. target typed by whatever method this is in.
if (parent is ReturnStatementSyntax)
return true;
// `yield return null;` same as above.
if (parent is YieldStatementSyntax)
return true;
// `x = null`. target typed by the other side.
if (parent is AssignmentExpressionSyntax)
return true;
// ... = null
//
// handles: parameters, variable declarations and the like.
if (parent is EqualsValueClauseSyntax)
return true;
// `(SomeType)null`. Definitely can target type this type-less expression.
if (parent is CastExpressionSyntax)
return true;
// `... ? null : ...`. Either side can target type the other.
if (parent is ConditionalExpressionSyntax)
return true;
// case null:
if (parent is CaseSwitchLabelSyntax)
return true;
return false;
}
private static bool IsExplicitCastThatMustBePreserved(ExpressionSyntax castNode, Conversion conversion)
{
if (conversion.IsExplicit)
{
// Consider the explicit cast in a line like:
//
// string? s = conditional ? (string?)"hello" : null;
//
// That string? cast is an explicit conversion that not IsUserDefined, but it may be removable if we support
// target-typed conditionals; in that case we'll return false here and force the full algorithm to be ran rather
// than this fast-path.
if (IsBranchOfConditionalExpression(castNode) &&
!CastMustBePreservedInConditionalBranch(castNode, conversion))
{
return false;
}
// if it's not a user defined conversion, we must preserve it as it has runtime impact that we don't want to change.
if (!conversion.IsUserDefined)
return true;
// Casts that involve implicit conversions are still represented as explicit casts. Because they're
// implicit though, we may be able to remove it. i.e. if we have `(C)0 + (C)1` we can remove one of the
// casts because it will be inferred from the binary context.
var userMethod = conversion.MethodSymbol;
if (userMethod?.Name != WellKnownMemberNames.ImplicitConversionName)
return true;
}
return false;
}
private static bool PointerOrIntPtrCastMustBePreserved(Conversion conversion)
{
if (!conversion.IsIdentity)
return false;
// if we have a non-identity cast to an int* or IntPtr just do not touch this.
// https://github.com/dotnet/roslyn/issues/2987 tracks improving on this conservative approach.
//
// NOTE(cyrusn): This code should not be necessary. However there is additional code that deals with
// `*(x*)expr` ends up masking that this change should not be safe. That code is suspect and should be
// changed. Until then though we disable this.
return conversion.IsPointer || conversion.IsIntPtr;
}
private static bool InvolvesDynamic(
ExpressionSyntax castNode,
ITypeSymbol? castType,
ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// We do not remove any cast on
// 1. Dynamic Expressions
// 2. If there is any other argument which is dynamic
// 3. Dynamic Invocation
// 4. Assignment to dynamic
if (castType?.Kind == SymbolKind.DynamicType || castedExpressionType?.Kind == SymbolKind.DynamicType)
return true;
return IsDynamicInvocation(castNode, semanticModel, cancellationToken) ||
IsDynamicAssignment(castNode, semanticModel, cancellationToken);
}
private static bool IsDereferenceOfNullPointerCast(ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode)
{
return castNode.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) &&
castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression);
}
private static bool IsBranchOfConditionalExpression(ExpressionSyntax expression)
{
return expression.Parent is ConditionalExpressionSyntax conditionalExpression &&
expression != conditionalExpression.Condition;
}
private static bool CastMustBePreservedInConditionalBranch(
ExpressionSyntax castNode, Conversion conversion)
{
// `... ? (int?)i : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
// It's safe to remove the cast when it's an identity. for example:
// `... ? (int)1 : default`.
if (!conversion.IsIdentity)
{
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is ConditionalExpressionSyntax conditionalExpression)
{
if (conditionalExpression.WhenTrue == castNode ||
conditionalExpression.WhenFalse == castNode)
{
var otherSide = conditionalExpression.WhenTrue == castNode
? conditionalExpression.WhenFalse
: conditionalExpression.WhenTrue;
otherSide = otherSide.WalkDownParentheses();
// In C# 9 we can potentially remove the cast if the other side is null, since the cast was previously required to
// resolve a situation like:
//
// var x = condition ? (int?)i : null
//
// but it isn't with target-typed conditionals. We do have to keep the cast if it's default, as:
//
// var x = condition ? (int?)i : default
//
// is inferred by the compiler to mean 'default(int?)', whereas removing the cast would mean default(int).
var languageVersion = ((CSharpParseOptions)castNode.SyntaxTree.Options).LanguageVersion;
return (otherSide.IsKind(SyntaxKind.NullLiteralExpression) && languageVersion < LanguageVersion.CSharp9) ||
otherSide.IsKind(SyntaxKind.DefaultLiteralExpression);
}
}
}
return false;
}
private static bool CastRemovalWouldCauseSignExtensionWarning(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Logic copied from DiagnosticsPass_Warnings.CheckForBitwiseOrSignExtend. Including comments.
if (!(expression is CastExpressionSyntax castExpression))
return false;
var castRoot = castExpression.WalkUpParentheses();
// Check both binary-or, and assignment-or
//
// x | (...)y
// x |= (...)y
ExpressionSyntax leftOperand, rightOperand;
if (castRoot.Parent is BinaryExpressionSyntax parentBinary)
{
if (!parentBinary.IsKind(SyntaxKind.BitwiseOrExpression))
return false;
(leftOperand, rightOperand) = (parentBinary.Left, parentBinary.Right);
}
else if (castRoot.Parent is AssignmentExpressionSyntax parentAssignment)
{
if (!parentAssignment.IsKind(SyntaxKind.OrAssignmentExpression))
return false;
(leftOperand, rightOperand) = (parentAssignment.Left, parentAssignment.Right);
}
else
{
return false;
}
// The native compiler skips this warning if both sides of the operator are constants.
//
// CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short
// when they are non-constants, or when one is a constant, that we would similarly warn
// when both are constants.
var constantValue = semanticModel.GetConstantValue(castRoot.Parent, cancellationToken);
if (constantValue.HasValue && constantValue.Value != null)
return false;
// Start by determining *which bits on each side are going to be unexpectedly turned on*.
var leftOperation = semanticModel.GetOperation(leftOperand.WalkDownParentheses(), cancellationToken);
var rightOperation = semanticModel.GetOperation(rightOperand.WalkDownParentheses(), cancellationToken);
if (leftOperation == null || rightOperation == null)
return false;
// Note: we are asking the question about if there would be a problem removing the cast. So we have to act
// as if an explicit cast becomes an implicit one. We do this by ignoring the appropriate cast and not
// treating it as explicit when we encounter it.
var left = FindSurprisingSignExtensionBits(leftOperation, leftOperand == castRoot);
var right = FindSurprisingSignExtensionBits(rightOperation, rightOperand == castRoot);
// If they are all the same then there's no warning to give.
if (left == right)
return false;
// Suppress the warning if one side is a constant, and either all the unexpected
// bits are already off, or all the unexpected bits are already on.
var constVal = GetConstantValueForBitwiseOrCheck(leftOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & right) == right || (~val & right) == right)
return false;
}
constVal = GetConstantValueForBitwiseOrCheck(rightOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & left) == left || (~val & left) == left)
return false;
}
// This would produce a warning. Don't offer to remove the cast.
return true;
}
private static ulong? GetConstantValueForBitwiseOrCheck(IOperation operation)
{
// We might have a nullable conversion on top of an integer constant. But only dig out
// one level.
if (operation is IConversionOperation conversion &&
conversion.Conversion.IsImplicit &&
conversion.Conversion.IsNullable)
{
operation = conversion.Operand;
}
var constantValue = operation.ConstantValue;
if (!constantValue.HasValue || constantValue.Value == null)
return null;
RoslynDebug.Assert(operation.Type is not null);
if (!operation.Type.SpecialType.IsIntegralType())
return null;
return IntegerUtilities.ToUInt64(constantValue.Value);
}
// A "surprising" sign extension is:
//
// * a conversion with no cast in source code that goes from a smaller
// signed type to a larger signed or unsigned type.
//
// * an conversion (with or without a cast) from a smaller
// signed type to a larger unsigned type.
private static ulong FindSurprisingSignExtensionBits(IOperation? operation, bool treatExplicitCastAsImplicit)
{
if (!(operation is IConversionOperation conversion))
return 0;
var from = conversion.Operand.Type;
var to = conversion.Type;
if (from is null || to is null)
return 0;
if (from.IsNullable(out var fromUnderlying))
from = fromUnderlying;
if (to.IsNullable(out var toUnderlying))
to = toUnderlying;
var fromSpecialType = from.SpecialType;
var toSpecialType = to.SpecialType;
if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType())
return 0;
var fromSize = fromSpecialType.SizeInBytes();
var toSize = toSpecialType.SizeInBytes();
if (fromSize == 0 || toSize == 0)
return 0;
// The operand might itself be a conversion, and might be contributing
// surprising bits. We might have more, fewer or the same surprising bits
// as the operand.
var recursive = FindSurprisingSignExtensionBits(conversion.Operand, treatExplicitCastAsImplicit: false);
if (fromSize == toSize)
{
// No change.
return recursive;
}
if (toSize < fromSize)
{
// We are casting from a larger type to a smaller type, and are therefore
// losing surprising bits.
switch (toSize)
{
case 1: return unchecked((ulong)(byte)recursive);
case 2: return unchecked((ulong)(ushort)recursive);
case 4: return unchecked((ulong)(uint)recursive);
}
Debug.Assert(false, "How did we get here?");
return recursive;
}
// We are converting from a smaller type to a larger type, and therefore might
// be adding surprising bits. First of all, the smaller type has got to be signed
// for there to be sign extension.
var fromSigned = fromSpecialType.IsSignedIntegralType();
if (!fromSigned)
return recursive;
// OK, we know that the "from" type is a signed integer that is smaller than the
// "to" type, so we are going to have sign extension. Is it surprising? The only
// time that sign extension is *not* surprising is when we have a cast operator
// to a *signed* type. That is, (int)myShort is not a surprising sign extension.
var explicitInCode = !conversion.IsImplicit;
if (!treatExplicitCastAsImplicit &&
explicitInCode &&
toSpecialType.IsSignedIntegralType())
{
return recursive;
}
// Note that we *could* be somewhat more clever here. Consider the following edge case:
//
// (ulong)(int)(uint)(ushort)mySbyte
//
// We could reason that the sbyte-to-ushort conversion is going to add one byte of
// unexpected sign extension. The conversion from ushort to uint adds no more bytes.
// The conversion from uint to int adds no more bytes. Does the conversion from int
// to ulong add any more bytes of unexpected sign extension? Well, no, because we
// know that the previous conversion from ushort to uint will ensure that the top bit
// of the uint is off!
//
// But we are not going to try to be that clever. In the extremely unlikely event that
// someone does this, we will record that the unexpectedly turned-on bits are
// 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00
// are the unexpected bits.
var result = recursive;
for (var i = fromSize; i < toSize; ++i)
result |= (0xFFUL) << (i * 8);
return result;
}
private static bool IdentityFloatingPointCastMustBePreserved(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
ITypeSymbol castType, ITypeSymbol castedExpressionType,
SemanticModel semanticModel, Conversion conversion, CancellationToken cancellationToken)
{
if (!conversion.IsIdentity)
return false;
// Floating point casts can have subtle runtime behavior, even between the same fp types. For example, a
// cast from float-to-float can still change behavior because it may take a higher precision computation and
// truncate it to 32bits.
//
// Because of this we keep floating point conversions unless we can prove that it's safe. The only safe
// times are when we're loading or storing into a location we know has the same size as the cast size
// (i.e. reading/writing into a field).
if (castedExpressionType.SpecialType != SpecialType.System_Double &&
castedExpressionType.SpecialType != SpecialType.System_Single &&
castType.SpecialType != SpecialType.System_Double &&
castType.SpecialType != SpecialType.System_Single)
{
// wasn't a floating point conversion.
return false;
}
// Identity fp conversion is safe if this is a read from a fp field/array
if (IsFieldOrArrayElement(semanticModel, castedExpressionNode, cancellationToken))
return false;
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is AssignmentExpressionSyntax assignmentExpression &&
assignmentExpression.Right == castNode)
{
// Identity fp conversion is safe if this is a write to a fp field/array
if (IsFieldOrArrayElement(semanticModel, assignmentExpression.Left, cancellationToken))
return false;
}
else if (castNode.Parent.IsKind(SyntaxKind.ArrayInitializerExpression, out InitializerExpressionSyntax? arrayInitializer))
{
// Identity fp conversion is safe if this is in an array initializer.
var typeInfo = semanticModel.GetTypeInfo(arrayInitializer, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.ArrayType;
}
else if (castNode.Parent is EqualsValueClauseSyntax equalsValue &&
equalsValue.Value == castNode &&
equalsValue.Parent is VariableDeclaratorSyntax variableDeclarator)
{
// Identity fp conversion is safe if this is in a field initializer.
var symbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
if (symbol?.Kind == SymbolKind.Field)
return false;
}
// We have to preserve this cast.
return true;
}
private static bool IsFieldOrArrayElement(
SemanticModel semanticModel, ExpressionSyntax expr, CancellationToken cancellationToken)
{
expr = expr.WalkDownParentheses();
var castedExpresionSymbol = semanticModel.GetSymbolInfo(expr, cancellationToken).Symbol;
// we're reading from a field of the same size. it's safe to remove this case.
if (castedExpresionSymbol?.Kind == SymbolKind.Field)
return true;
if (expr is ElementAccessExpressionSyntax elementAccess)
{
var locationType = semanticModel.GetTypeInfo(elementAccess.Expression, cancellationToken);
return locationType.Type?.Kind == SymbolKind.ArrayType;
}
return false;
}
private static bool HaveSameUserDefinedConversion(Conversion conversion1, Conversion conversion2)
{
return conversion1.IsUserDefined
&& conversion2.IsUserDefined
&& Equals(conversion1.MethodSymbol, conversion2.MethodSymbol);
}
private static bool IsInDelegateCreationExpression(
ExpressionSyntax castNode, SemanticModel semanticModel)
{
if (!(castNode.WalkUpParentheses().Parent is ArgumentSyntax argument))
{
return false;
}
if (!(argument.Parent is ArgumentListSyntax argumentList))
{
return false;
}
if (!(argumentList.Parent is ObjectCreationExpressionSyntax objectCreation))
{
return false;
}
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type).Symbol;
return typeSymbol != null
&& typeSymbol.IsDelegateType();
}
private static bool IsDynamicInvocation(
ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castExpression.WalkUpParentheses().IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) &&
argument.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList) &&
argument.Parent.Parent.IsKind(SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression))
{
var typeInfo = semanticModel.GetTypeInfo(argument.Parent.Parent, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsDynamicAssignment(ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
castExpression = castExpression.WalkUpParentheses();
if (castExpression.IsRightSideOfAnyAssignExpression())
{
var assignmentExpression = (AssignmentExpressionSyntax)castExpression.Parent!;
var assignmentType = semanticModel.GetTypeInfo(assignmentExpression.Left, cancellationToken).Type;
return assignmentType?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsRequiredImplicitNumericConversion(ITypeSymbol sourceType, ITypeSymbol destinationType)
{
// C# Language Specification: Section 6.1.2 Implicit numeric conversions
// Conversions from int, uint, long, or ulong to float and from long or ulong to double may cause a loss of precision,
// but will never cause a loss of magnitude. The other implicit numeric conversions never lose any information.
switch (destinationType.SpecialType)
{
case SpecialType.System_Single:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
case SpecialType.System_Double:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
default:
return false;
}
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Based on the check in DiagnosticPass.CheckRelationals.
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
// compiler: if (node.Left.Type.SpecialType == SpecialType.System_Object
if (castType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual
castNode = castNode.WalkUpParentheses();
var parent = castNode.Parent;
if (!(parent is BinaryExpressionSyntax binaryExpression))
return false;
if (!binaryExpression.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression))
return false;
var binaryMethod = semanticModel.GetSymbolInfo(binaryExpression, cancellationToken).Symbol as IMethodSymbol;
if (binaryMethod == null)
return false;
if (binaryMethod.ContainingType?.SpecialType != SpecialType.System_Object)
return false;
var operatorName = binaryMethod.Name;
if (operatorName != WellKnownMemberNames.EqualityOperatorName && operatorName != WellKnownMemberNames.InequalityOperatorName)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
otherSide = otherSide.WalkDownParentheses();
return CastIsRequiredToPreventUnintendedComparisonWarning(castedExpressionNode, otherSide, operatorName, semanticModel, cancellationToken) ||
CastIsRequiredToPreventUnintendedComparisonWarning(otherSide, castedExpressionNode, operatorName, semanticModel, cancellationToken);
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax left, ExpressionSyntax right, string operatorName,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// compiler: node.Left.Type.SpecialType == SpecialType.System_Object
var leftType = semanticModel.GetTypeInfo(left, cancellationToken).Type;
if (leftType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: && !IsExplicitCast(node.Left)
if (left.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull)
var constantValue = semanticModel.GetConstantValue(left, cancellationToken);
if (constantValue.HasValue && constantValue.Value is null)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
// Code for: ConvertedHasEqual
// compiler: if (conv.ExplicitCastInCode) return false;
if (right.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol;
// if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface)
var otherSideType = semanticModel.GetTypeInfo(right, cancellationToken).Type as INamedTypeSymbol;
if (otherSideType == null)
return false;
if (!otherSideType.IsReferenceType || otherSideType.TypeKind == TypeKind.Interface)
return false;
// compiler: for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics)
for (var currentType = otherSideType; currentType != null; currentType = currentType.BaseType)
{
// compiler: foreach (var sym in t.GetMembers(opName))
foreach (var opMember in currentType.GetMembers(operatorName))
{
// compiler: MethodSymbol op = sym as MethodSymbol;
var opMethod = opMember as IMethodSymbol;
// compiler: if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue;
if (opMethod == null || opMethod.MethodKind != MethodKind.UserDefinedOperator)
continue;
// compiler: var parameters = op.GetParameters();
// if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2))
// return true
var parameters = opMethod.Parameters;
if (parameters.Length == 2 && Equals(parameters[0].Type, currentType) && Equals(parameters[1].Type, currentType))
return true;
}
}
return false;
}
private static Conversion GetSpeculatedExpressionToOuterTypeConversion(ExpressionSyntax speculatedExpression, SpeculationAnalyzer speculationAnalyzer, CancellationToken cancellationToken)
{
var typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(speculatedExpression, cancellationToken);
var conversion = speculationAnalyzer.SpeculativeSemanticModel.GetConversion(speculatedExpression, cancellationToken);
if (!conversion.IsIdentity)
{
return conversion;
}
var speculatedExpressionOuterType = GetOuterCastType(speculatedExpression, speculationAnalyzer.SpeculativeSemanticModel, out _) ?? typeInfo.ConvertedType;
if (speculatedExpressionOuterType == null)
{
return default;
}
return speculationAnalyzer.SpeculativeSemanticModel.ClassifyConversion(speculatedExpression, speculatedExpressionOuterType);
}
private static bool UserDefinedConversionIsAllowed(ExpressionSyntax expression)
{
expression = expression.WalkUpParentheses();
var parentNode = expression.Parent;
if (parentNode == null)
{
return false;
}
if (parentNode.IsKind(SyntaxKind.ThrowStatement))
{
return false;
}
return true;
}
private static bool ParamsArgumentCastMustBePreserved(
ExpressionSyntax cast,
ITypeSymbol castType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// When a casted value is passed as the single argument to a params parameter,
// we can only remove the cast if it is implicitly convertible to the parameter's type,
// but not the parameter's element type. Otherwise, we could end up changing the invocation
// to pass an array rather than an array with a single element.
//
// IOW, given the following method...
//
// static void Goo(params object[] x) { }
//
// ...we should remove this cast...
//
// Goo((object[])null);
//
// ...but not this cast...
//
// Goo((object)null);
var parent = cast.WalkUpParentheses().Parent;
if (parent is ArgumentSyntax argument)
{
// If there are any arguments to the right (and the argument is not named), we can assume that this is
// not a *single* argument passed to a params parameter.
if (argument.NameColon == null && argument.Parent is BaseArgumentListSyntax argumentList)
{
var argumentIndex = argumentList.Arguments.IndexOf(argument);
if (argumentIndex < argumentList.Arguments.Count - 1)
{
return false;
}
}
var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
if (parent is AttributeArgumentSyntax attributeArgument)
{
if (attributeArgument.Parent is AttributeArgumentListSyntax)
{
// We don't check the position of the argument because in attributes it is allowed that
// params parameter are positioned in between if named arguments are used.
var parameter = attributeArgument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
}
return false;
}
private static bool ParameterTypeMatchesParamsElementType([NotNullWhen(true)] IParameterSymbol? parameter, ITypeSymbol castType, SemanticModel semanticModel)
{
if (parameter?.IsParams == true)
{
// if the method is defined with errors: void M(params int wrongDefined), parameter.IsParams == true but parameter.Type is not an array.
// In such cases is better to be conservative and opt out.
if (!(parameter.Type is IArrayTypeSymbol parameterType))
{
return true;
}
var conversion = semanticModel.Compilation.ClassifyConversion(castType, parameterType);
if (conversion.Exists &&
conversion.IsImplicit)
{
return false;
}
var conversionElementType = semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType);
if (conversionElementType.Exists &&
conversionElementType.IsImplicit)
{
return true;
}
}
return false;
}
private static ITypeSymbol? GetOuterCastType(
ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsIsOrAsExpression)
{
expression = expression.WalkUpParentheses();
parentIsIsOrAsExpression = false;
var parentNode = expression.Parent;
if (parentNode == null)
{
return null;
}
if (parentNode.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression))
{
return semanticModel.GetTypeInfo(castExpression).Type;
}
if (parentNode.IsKind(SyntaxKind.PointerIndirectionExpression))
{
return semanticModel.GetTypeInfo(expression).Type;
}
if (parentNode.IsKind(SyntaxKind.IsExpression) ||
parentNode.IsKind(SyntaxKind.AsExpression))
{
parentIsIsOrAsExpression = true;
return null;
}
if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier))
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32);
}
if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess))
{
if (memberAccess.Expression == expression)
{
var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol;
if (memberSymbol != null)
{
return memberSymbol.ContainingType;
}
}
}
if (parentNode.IsKind(SyntaxKind.ConditionalExpression) &&
((ConditionalExpressionSyntax)parentNode).Condition == expression)
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean);
}
if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) &&
!semanticModel.GetConversion(expression).IsUserDefined)
{
var parentExpression = (ExpressionSyntax)parentNode;
return GetOuterCastType(parentExpression, semanticModel, out parentIsIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentExpression).ConvertedType;
}
if (parentNode is InterpolationSyntax)
{
// $"{(x)y}"
//
// Regardless of the cast to 'x', being in an interpolation automatically casts the result to object
// since this becomes a call to: FormattableStringFactory.Create(string, params object[]).
return semanticModel.Compilation.ObjectType;
}
return null;
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/LanguageServer/Protocol/Handler/Diagnostics/DocumentPullDiagnosticHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics
{
internal class DocumentPullDiagnosticHandler : AbstractPullDiagnosticHandler<VSInternalDocumentDiagnosticsParams, VSInternalDiagnosticReport>
{
private readonly IDiagnosticAnalyzerService _analyzerService;
public override string Method => VSInternalMethods.DocumentPullDiagnosticName;
public DocumentPullDiagnosticHandler(
IDiagnosticService diagnosticService,
IDiagnosticAnalyzerService analyzerService)
: base(diagnosticService)
{
_analyzerService = analyzerService;
}
public override TextDocumentIdentifier? GetTextDocumentIdentifier(VSInternalDocumentDiagnosticsParams diagnosticsParams)
=> diagnosticsParams.TextDocument;
protected override VSInternalDiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId)
=> new VSInternalDiagnosticReport
{
Diagnostics = diagnostics,
ResultId = resultId,
Identifier = DocumentDiagnosticIdentifier,
// Mark these diagnostics as superseding any diagnostics for the same document from the
// WorkspacePullDiagnosticHandler. We are always getting completely accurate and up to date diagnostic
// values for a particular file, so our results should always be preferred over the workspace-pull
// values which are cached and may be out of date.
Supersedes = WorkspaceDiagnosticIdentifier,
};
protected override VSInternalDiagnosticParams[]? GetPreviousResults(VSInternalDocumentDiagnosticsParams diagnosticsParams)
=> new[] { diagnosticsParams };
protected override IProgress<VSInternalDiagnosticReport[]>? GetProgress(VSInternalDocumentDiagnosticsParams diagnosticsParams)
=> diagnosticsParams.PartialResultToken;
protected override DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData)
=> ConvertTags(diagnosticData, potentialDuplicate: false);
protected override ImmutableArray<Document> GetOrderedDocuments(RequestContext context)
{
// For the single document case, that is the only doc we want to process.
//
// Note: context.Document may be null in the case where the client is asking about a document that we have
// since removed from the workspace. In this case, we don't really have anything to process.
// GetPreviousResults will be used to properly realize this and notify the client that the doc is gone.
//
// Only consider open documents here (and only closed ones in the WorkspacePullDiagnosticHandler). Each
// handler treats those as separate worlds that they are responsible for.
if (context.Document == null)
{
context.TraceInformation("Ignoring diagnostics request because no document was provided");
return ImmutableArray<Document>.Empty;
}
if (!context.IsTracking(context.Document.GetURI()))
{
context.TraceInformation($"Ignoring diagnostics request for untracked document: {context.Document.GetURI()}");
return ImmutableArray<Document>.Empty;
}
return ImmutableArray.Create(context.Document);
}
protected override Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(
RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken)
{
// For open documents, directly use the IDiagnosticAnalyzerService. This will use the actual snapshots
// we're passing in. If information is already cached for that snapshot, it will be returned. Otherwise,
// it will be computed on demand. Because it is always accurate as per this snapshot, all spans are correct
// and do not need to be adjusted.
return _analyzerService.GetDiagnosticsForSpanAsync(document, range: null, cancellationToken: cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics
{
internal class DocumentPullDiagnosticHandler : AbstractPullDiagnosticHandler<VSInternalDocumentDiagnosticsParams, VSInternalDiagnosticReport>
{
private readonly IDiagnosticAnalyzerService _analyzerService;
public override string Method => VSInternalMethods.DocumentPullDiagnosticName;
public DocumentPullDiagnosticHandler(
IDiagnosticService diagnosticService,
IDiagnosticAnalyzerService analyzerService)
: base(diagnosticService)
{
_analyzerService = analyzerService;
}
public override TextDocumentIdentifier? GetTextDocumentIdentifier(VSInternalDocumentDiagnosticsParams diagnosticsParams)
=> diagnosticsParams.TextDocument;
protected override VSInternalDiagnosticReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId)
=> new VSInternalDiagnosticReport
{
Diagnostics = diagnostics,
ResultId = resultId,
Identifier = DocumentDiagnosticIdentifier,
// Mark these diagnostics as superseding any diagnostics for the same document from the
// WorkspacePullDiagnosticHandler. We are always getting completely accurate and up to date diagnostic
// values for a particular file, so our results should always be preferred over the workspace-pull
// values which are cached and may be out of date.
Supersedes = WorkspaceDiagnosticIdentifier,
};
protected override VSInternalDiagnosticParams[]? GetPreviousResults(VSInternalDocumentDiagnosticsParams diagnosticsParams)
=> new[] { diagnosticsParams };
protected override IProgress<VSInternalDiagnosticReport[]>? GetProgress(VSInternalDocumentDiagnosticsParams diagnosticsParams)
=> diagnosticsParams.PartialResultToken;
protected override DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData)
=> ConvertTags(diagnosticData, potentialDuplicate: false);
protected override ImmutableArray<Document> GetOrderedDocuments(RequestContext context)
{
// For the single document case, that is the only doc we want to process.
//
// Note: context.Document may be null in the case where the client is asking about a document that we have
// since removed from the workspace. In this case, we don't really have anything to process.
// GetPreviousResults will be used to properly realize this and notify the client that the doc is gone.
//
// Only consider open documents here (and only closed ones in the WorkspacePullDiagnosticHandler). Each
// handler treats those as separate worlds that they are responsible for.
if (context.Document == null)
{
context.TraceInformation("Ignoring diagnostics request because no document was provided");
return ImmutableArray<Document>.Empty;
}
if (!context.IsTracking(context.Document.GetURI()))
{
context.TraceInformation($"Ignoring diagnostics request for untracked document: {context.Document.GetURI()}");
return ImmutableArray<Document>.Empty;
}
return ImmutableArray.Create(context.Document);
}
protected override Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(
RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken)
{
// For open documents, directly use the IDiagnosticAnalyzerService. This will use the actual snapshots
// we're passing in. If information is already cached for that snapshot, it will be returned. Otherwise,
// it will be computed on demand. Because it is always accurate as per this snapshot, all spans are correct
// and do not need to be adjusted.
return _analyzerService.GetDiagnosticsForSpanAsync(document, range: null, cancellationToken: cancellationToken);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Core/Portable/Interop/ClrStrongName.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using System.Security;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interop
{
internal static class ClrStrongName
{
[DllImport("mscoree.dll", PreserveSig = false, EntryPoint = "CLRCreateInstance")]
[return: MarshalAs(UnmanagedType.Interface)]
private static extern object nCreateInterface(
[MarshalAs(UnmanagedType.LPStruct)] Guid clsid,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid);
internal static IClrStrongName GetInstance()
{
var metaHostClsid = new Guid(unchecked((int)0x9280188D), 0xE8E, 0x4867, 0xB3, 0xC, 0x7F, 0xA8, 0x38, 0x84, 0xE8, 0xDE);
var metaHostGuid = new Guid(unchecked((int)0xD332DB9E), unchecked((short)0xB9B3), 0x4125, 0x82, 0x07, 0xA1, 0x48, 0x84, 0xF5, 0x32, 0x16);
var clrStrongNameClsid = new Guid(unchecked((int)0xB79B0ACD), unchecked((short)0xF5CD), 0x409b, 0xB5, 0xA5, 0xA1, 0x62, 0x44, 0x61, 0x0B, 0x92);
var clrRuntimeInfoGuid = new Guid(unchecked((int)0xBD39D1D2), unchecked((short)0xBA2F), 0x486A, 0x89, 0xB0, 0xB4, 0xB0, 0xCB, 0x46, 0x68, 0x91);
var clrStrongNameGuid = new Guid(unchecked((int)0x9FD93CCF), 0x3280, 0x4391, 0xB3, 0xA9, 0x96, 0xE1, 0xCD, 0xE7, 0x7C, 0x8D);
var metaHost = (IClrMetaHost)nCreateInterface(metaHostClsid, metaHostGuid);
var runtime = (IClrRuntimeInfo)metaHost.GetRuntime(GetRuntimeVersion(), clrRuntimeInfoGuid);
return (IClrStrongName)runtime.GetInterface(clrStrongNameClsid, clrStrongNameGuid);
}
internal static string GetRuntimeVersion()
{
// When running in a complus environment we must respect the specified CLR version. This
// important to keeping internal builds running.
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("COMPLUS_InstallRoot")))
{
var version = Environment.GetEnvironmentVariable("COMPLUS_Version");
if (!string.IsNullOrEmpty(version))
{
return version;
}
}
return "v4.0.30319";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using System.Security;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interop
{
internal static class ClrStrongName
{
[DllImport("mscoree.dll", PreserveSig = false, EntryPoint = "CLRCreateInstance")]
[return: MarshalAs(UnmanagedType.Interface)]
private static extern object nCreateInterface(
[MarshalAs(UnmanagedType.LPStruct)] Guid clsid,
[MarshalAs(UnmanagedType.LPStruct)] Guid riid);
internal static IClrStrongName GetInstance()
{
var metaHostClsid = new Guid(unchecked((int)0x9280188D), 0xE8E, 0x4867, 0xB3, 0xC, 0x7F, 0xA8, 0x38, 0x84, 0xE8, 0xDE);
var metaHostGuid = new Guid(unchecked((int)0xD332DB9E), unchecked((short)0xB9B3), 0x4125, 0x82, 0x07, 0xA1, 0x48, 0x84, 0xF5, 0x32, 0x16);
var clrStrongNameClsid = new Guid(unchecked((int)0xB79B0ACD), unchecked((short)0xF5CD), 0x409b, 0xB5, 0xA5, 0xA1, 0x62, 0x44, 0x61, 0x0B, 0x92);
var clrRuntimeInfoGuid = new Guid(unchecked((int)0xBD39D1D2), unchecked((short)0xBA2F), 0x486A, 0x89, 0xB0, 0xB4, 0xB0, 0xCB, 0x46, 0x68, 0x91);
var clrStrongNameGuid = new Guid(unchecked((int)0x9FD93CCF), 0x3280, 0x4391, 0xB3, 0xA9, 0x96, 0xE1, 0xCD, 0xE7, 0x7C, 0x8D);
var metaHost = (IClrMetaHost)nCreateInterface(metaHostClsid, metaHostGuid);
var runtime = (IClrRuntimeInfo)metaHost.GetRuntime(GetRuntimeVersion(), clrRuntimeInfoGuid);
return (IClrStrongName)runtime.GetInterface(clrStrongNameClsid, clrStrongNameGuid);
}
internal static string GetRuntimeVersion()
{
// When running in a complus environment we must respect the specified CLR version. This
// important to keeping internal builds running.
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("COMPLUS_InstallRoot")))
{
var version = Environment.GetEnvironmentVariable("COMPLUS_Version");
if (!string.IsNullOrEmpty(version))
{
return version;
}
}
return "v4.0.30319";
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./eng/pipelines/insert.yml | parameters:
# These are actually booleans but must be defined as string.
# Parameters are evaluated at compile time, but all variables are strings at compile time.
# So in order to pass a parameter that comes from a variable these must be typed as string.
- name: createDraftPR
type: string
default: ''
- name: autoComplete
type: string
default: ''
- name: insertToolset
type: string
default: ''
- name: clientId
type: string
- name: clientSecret
type: string
- name: publishDataURI
type: string
- name: publishDataAccessToken
type: string
default: ''
- name: vsBranchName
type: string
default: ''
- name: componentBuildProjectName
type: string
default: ''
- name: titlePrefix
type: string
default: ''
- name: sourceBranch
type: string
steps:
- checkout: none
- task: NuGetCommand@2
displayName: 'Install RIT from Azure Artifacts'
inputs:
command: custom
arguments: 'install RoslynTools.VisualStudioInsertionTool -PreRelease -Source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json'
- powershell: |
$authorization = if ("" -ne $Env:PublishDataAccessToken) { "Bearer $Env:PublishDataAccessToken" } else { "" }
$response = Invoke-RestMethod -Headers @{Authorization = $authorization} "${{ parameters.publishDataURI }}"
$branchName = "${{ parameters.sourceBranch }}"
$branchData = $response.branches.$branchName
if (!$branchData)
{
Write-Host "No PublishData found for branch '$branchName'. Using PublishData for branch 'main'."
$branchData = $response.branches.main
}
# Set our template variables to reasonable defaults
Write-Host "##vso[task.setvariable variable=Template.CreateDraftPR]$($true)"
Write-Host "##vso[task.setvariable variable=Template.AutoComplete]$($false)"
Write-Host "##vso[task.setvariable variable=Template.TitlePrefix]$('')"
Write-Host "##vso[task.setvariable variable=Template.TitleSuffix]$('[Skip-SymbolCheck]')"
Write-Host "##vso[task.setvariable variable=Template.InsertToolset]$($true)"
Write-Host "##vso[task.setvariable variable=Template.ComponentAzdoUri]$('')"
Write-Host "##vso[task.setvariable variable=Template.ComponentProjectName]$('')"
Write-Host "##vso[task.setvariable variable=Template.ComponentBranchName]$branchName"
Write-Host "##vso[task.setvariable variable=Template.VSBranchName]$($branchData.vsBranch)"
# Overwrite the default template variables with the values from PublishData for this sourceBranch
if ($null -ne $branchData.insertionCreateDraftPR)
{
Write-Host "##vso[task.setvariable variable=Template.CreateDraftPR]$($branchData.insertionCreateDraftPR)"
}
if ($null -ne $branchData.insertionCreateDraftPR)
{
Write-Host "##vso[task.setvariable variable=Template.AutoComplete]$(-not $branchData.insertionCreateDraftPR)"
}
if ($null -ne $branchData.insertionTitlePrefix)
{
Write-Host "##vso[task.setvariable variable=Template.TitlePrefix]$($branchData.insertionTitlePrefix)"
}
if ($null -ne $branchData.insertToolset)
{
Write-Host "##vso[task.setvariable variable=Template.InsertToolset]$($branchData.insertToolset)"
}
displayName: Set Variables from PublishData
env:
PublishDataAccessToken: ${{ parameters.publishDataAccessToken }}
- powershell: |
# Overwrite template variables with values passed into this template as parameters
if ("" -ne $Env:CreateDraftPR)
{
Write-Host "Setting CreateDraftPR to $Env:CreateDraftPR"
Write-Host "##vso[task.setvariable variable=Template.CreateDraftPR]$Env:CreateDraftPR"
}
if ("" -ne $Env:AutoComplete)
{
Write-Host "Setting AutoComplete to $Env:AutoComplete"
Write-Host "##vso[task.setvariable variable=Template.AutoComplete]$Env:AutoComplete"
}
if ("" -ne $Env:TitlePrefix)
{
Write-Host "Setting TitlePrefix to $Env:TitlePrefix"
Write-Host "##vso[task.setvariable variable=Template.TitlePrefix]$Env:TitlePrefix"
}
if ("" -ne $Env:InsertToolset)
{
Write-Host "Setting InsertToolset to $Env:InsertToolset"
Write-Host "##vso[task.setvariable variable=Template.InsertToolset]$Env:InsertToolset"
}
# Workaround for pipeline parameters not supporting optional empty parameters.
if ("" -ne $Env:VSBranchName -and "default" -ne $Env:VSBranchName)
{
Write-Host "Setting VSBranchName to $Env:VSBranchName"
Write-Host "##vso[task.setvariable variable=Template.VSBranchName]$Env:VSBranchName"
}
if ("" -ne $Env:ComponentBuildProjectName)
{
Write-Host "Setting component Azdo parameters $('$(System.CollectionUri)') and $Env:ComponentBuildProjectName"
Write-Host "##vso[task.setvariable variable=Template.ComponentAzdoUri]$('$(System.CollectionUri)')"
Write-Host "##vso[task.setvariable variable=Template.ComponentProjectName]$Env:ComponentBuildProjectName"
}
displayName: Set Variables from Input Parameters
env:
CreateDraftPR: ${{ parameters.createDraftPR }}
AutoComplete: ${{ parameters.autoComplete }}
TitlePrefix: ${{ parameters.titlePrefix }}
InsertToolset: ${{ parameters.insertToolset }}
VSBranchName: ${{ parameters.vsBranchName }}
ComponentBuildProjectName: ${{ parameters.componentBuildProjectName }}
# Now that everything is set, actually perform the insertion.
- powershell: |
mv RoslynTools.VisualStudioInsertionTool.* RIT
.\RIT\tools\OneOffInsertion.ps1 `
-autoComplete "$(Template.AutoComplete)" `
-buildQueueName "$(Build.DefinitionName)" `
-cherryPick "(default)" `
-clientId "${{ parameters.clientId }}" `
-clientSecret "${{ parameters.clientSecret }}" `
-componentAzdoUri "$(Template.ComponentAzdoUri)" `
-componentProjectName "$(Template.ComponentProjectName)" `
-componentName "Roslyn" `
-componentGitHubRepoName "dotnet/roslyn" `
-componentBranchName "$(Template.ComponentBranchName)" `
-createDraftPR "$(Template.CreateDraftPR)" `
-defaultValueSentinel "(default)" `
-dropPath "(default)" `
-insertCore "(default)" `
-insertDevDiv "(default)" `
-insertionCount "1" `
-insertToolset "$(Template.InsertToolset)" `
-titlePrefix "$(Template.TitlePrefix)" `
-titleSuffix "$(Template.TitleSuffix)" `
-queueValidation "true" `
-requiredValueSentinel "REQUIRED" `
-reviewerGUID "6c25b447-1d90-4840-8fde-d8b22cb8733e" `
-specificBuild "$(Build.BuildNumber)" `
-updateAssemblyVersions "(default)" `
-updateCoreXTLibraries "(default)" `
-visualStudioBranchName "$(Template.VSBranchName)" `
-writePullRequest "prid.txt" `
displayName: 'Run OneOffInsertion.ps1'
- script: 'echo. && echo. && type "prid.txt" && echo. && echo.'
displayName: 'Report PR URL'
| parameters:
# These are actually booleans but must be defined as string.
# Parameters are evaluated at compile time, but all variables are strings at compile time.
# So in order to pass a parameter that comes from a variable these must be typed as string.
- name: createDraftPR
type: string
default: ''
- name: autoComplete
type: string
default: ''
- name: insertToolset
type: string
default: ''
- name: clientId
type: string
- name: clientSecret
type: string
- name: publishDataURI
type: string
- name: publishDataAccessToken
type: string
default: ''
- name: vsBranchName
type: string
default: ''
- name: componentBuildProjectName
type: string
default: ''
- name: titlePrefix
type: string
default: ''
- name: sourceBranch
type: string
steps:
- checkout: none
- task: NuGetCommand@2
displayName: 'Install RIT from Azure Artifacts'
inputs:
command: custom
arguments: 'install RoslynTools.VisualStudioInsertionTool -PreRelease -Source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json'
- powershell: |
$authorization = if ("" -ne $Env:PublishDataAccessToken) { "Bearer $Env:PublishDataAccessToken" } else { "" }
$response = Invoke-RestMethod -Headers @{Authorization = $authorization} "${{ parameters.publishDataURI }}"
$branchName = "${{ parameters.sourceBranch }}"
$branchData = $response.branches.$branchName
if (!$branchData)
{
Write-Host "No PublishData found for branch '$branchName'. Using PublishData for branch 'main'."
$branchData = $response.branches.main
}
# Set our template variables to reasonable defaults
Write-Host "##vso[task.setvariable variable=Template.CreateDraftPR]$($true)"
Write-Host "##vso[task.setvariable variable=Template.AutoComplete]$($false)"
Write-Host "##vso[task.setvariable variable=Template.TitlePrefix]$('')"
Write-Host "##vso[task.setvariable variable=Template.TitleSuffix]$('[Skip-SymbolCheck]')"
Write-Host "##vso[task.setvariable variable=Template.InsertToolset]$($true)"
Write-Host "##vso[task.setvariable variable=Template.ComponentAzdoUri]$('')"
Write-Host "##vso[task.setvariable variable=Template.ComponentProjectName]$('')"
Write-Host "##vso[task.setvariable variable=Template.ComponentBranchName]$branchName"
Write-Host "##vso[task.setvariable variable=Template.VSBranchName]$($branchData.vsBranch)"
# Overwrite the default template variables with the values from PublishData for this sourceBranch
if ($null -ne $branchData.insertionCreateDraftPR)
{
Write-Host "##vso[task.setvariable variable=Template.CreateDraftPR]$($branchData.insertionCreateDraftPR)"
}
if ($null -ne $branchData.insertionCreateDraftPR)
{
Write-Host "##vso[task.setvariable variable=Template.AutoComplete]$(-not $branchData.insertionCreateDraftPR)"
}
if ($null -ne $branchData.insertionTitlePrefix)
{
Write-Host "##vso[task.setvariable variable=Template.TitlePrefix]$($branchData.insertionTitlePrefix)"
}
if ($null -ne $branchData.insertToolset)
{
Write-Host "##vso[task.setvariable variable=Template.InsertToolset]$($branchData.insertToolset)"
}
displayName: Set Variables from PublishData
env:
PublishDataAccessToken: ${{ parameters.publishDataAccessToken }}
- powershell: |
# Overwrite template variables with values passed into this template as parameters
if ("" -ne $Env:CreateDraftPR)
{
Write-Host "Setting CreateDraftPR to $Env:CreateDraftPR"
Write-Host "##vso[task.setvariable variable=Template.CreateDraftPR]$Env:CreateDraftPR"
}
if ("" -ne $Env:AutoComplete)
{
Write-Host "Setting AutoComplete to $Env:AutoComplete"
Write-Host "##vso[task.setvariable variable=Template.AutoComplete]$Env:AutoComplete"
}
if ("" -ne $Env:TitlePrefix)
{
Write-Host "Setting TitlePrefix to $Env:TitlePrefix"
Write-Host "##vso[task.setvariable variable=Template.TitlePrefix]$Env:TitlePrefix"
}
if ("" -ne $Env:InsertToolset)
{
Write-Host "Setting InsertToolset to $Env:InsertToolset"
Write-Host "##vso[task.setvariable variable=Template.InsertToolset]$Env:InsertToolset"
}
# Workaround for pipeline parameters not supporting optional empty parameters.
if ("" -ne $Env:VSBranchName -and "default" -ne $Env:VSBranchName)
{
Write-Host "Setting VSBranchName to $Env:VSBranchName"
Write-Host "##vso[task.setvariable variable=Template.VSBranchName]$Env:VSBranchName"
}
if ("" -ne $Env:ComponentBuildProjectName)
{
Write-Host "Setting component Azdo parameters $('$(System.CollectionUri)') and $Env:ComponentBuildProjectName"
Write-Host "##vso[task.setvariable variable=Template.ComponentAzdoUri]$('$(System.CollectionUri)')"
Write-Host "##vso[task.setvariable variable=Template.ComponentProjectName]$Env:ComponentBuildProjectName"
}
displayName: Set Variables from Input Parameters
env:
CreateDraftPR: ${{ parameters.createDraftPR }}
AutoComplete: ${{ parameters.autoComplete }}
TitlePrefix: ${{ parameters.titlePrefix }}
InsertToolset: ${{ parameters.insertToolset }}
VSBranchName: ${{ parameters.vsBranchName }}
ComponentBuildProjectName: ${{ parameters.componentBuildProjectName }}
# Now that everything is set, actually perform the insertion.
- powershell: |
mv RoslynTools.VisualStudioInsertionTool.* RIT
.\RIT\tools\OneOffInsertion.ps1 `
-autoComplete "$(Template.AutoComplete)" `
-buildQueueName "$(Build.DefinitionName)" `
-cherryPick "(default)" `
-clientId "${{ parameters.clientId }}" `
-clientSecret "${{ parameters.clientSecret }}" `
-componentAzdoUri "$(Template.ComponentAzdoUri)" `
-componentProjectName "$(Template.ComponentProjectName)" `
-componentName "Roslyn" `
-componentGitHubRepoName "dotnet/roslyn" `
-componentBranchName "$(Template.ComponentBranchName)" `
-createDraftPR "$(Template.CreateDraftPR)" `
-defaultValueSentinel "(default)" `
-dropPath "(default)" `
-insertCore "(default)" `
-insertDevDiv "(default)" `
-insertionCount "1" `
-insertToolset "$(Template.InsertToolset)" `
-titlePrefix "$(Template.TitlePrefix)" `
-titleSuffix "$(Template.TitleSuffix)" `
-queueValidation "true" `
-requiredValueSentinel "REQUIRED" `
-reviewerGUID "6c25b447-1d90-4840-8fde-d8b22cb8733e" `
-specificBuild "$(Build.BuildNumber)" `
-updateAssemblyVersions "(default)" `
-updateCoreXTLibraries "(default)" `
-visualStudioBranchName "$(Template.VSBranchName)" `
-writePullRequest "prid.txt" `
displayName: 'Run OneOffInsertion.ps1'
- script: 'echo. && echo. && type "prid.txt" && echo. && echo.'
displayName: 'Report PR URL'
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Test/Semantic/Semantics/InterpolationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class InterpolationTests : CompilingTestBase
{
[Fact]
public void TestSimpleInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number }."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 }."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 }."");
Console.WriteLine($""Jenny don\'t change your number { number :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}."");
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"Jenny don't change your number 8675309.
Jenny don't change your number 8675309 .
Jenny don't change your number 8675309.
Jenny don't change your number 867-5309.
Jenny don't change your number 867-5309 .
Jenny don't change your number 867-5309.
8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestOnlyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}{number}"");
}
}";
string expectedOutput =
@"86753098675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}."");
}
}";
string expectedOutput =
@"Jenny don't change your number 867-5309 867-5309.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestEmptyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }."");
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,73): error CS1733: Expected expression
// Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }.");
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73)
);
}
[Fact]
public void TestHalfOpenInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,63): error CS1010: Newline in constant
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63),
// (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 // "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS8077: A single-line comment may not be used in an interpolated string.
// Console.WriteLine($"Jenny don\'t change your number { 8675309 // ");
Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp03()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 /* "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS1035: End-of-file found, '*/' expected
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71),
// (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77),
// (7,2): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2),
// (7,2): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void LambdaInInterp()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
//Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() });
Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}"");
}
static int number = 8675309;
}
";
string expectedOutput = @"jenny (408) 867-5309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void OneLiteral()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""Hello"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Hello""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ret
}
");
}
[Fact]
public void OneInsert()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
Console.WriteLine( $""{hello}"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldstr ""Hello""
IL_0005: dup
IL_0006: brtrue.s IL_000e
IL_0008: pop
IL_0009: ldstr """"
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}
");
}
[Fact]
public void TwoInserts()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $""{hello}, { world }."" );
}
}";
string expectedOutput = @"Hello, world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TwoInserts02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $@""{
hello
},
{
world }."" );
}
}";
string expectedOutput = @"Hello,
world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")]
public void DynamicInterpolation()
{
string source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
dynamic nil = null;
dynamic a = new string[] {""Hello"", ""world""};
Console.WriteLine($""<{nil}>"");
Console.WriteLine($""<{a}>"");
}
Expression<Func<string>> M(dynamic d) {
return () => $""Dynamic: {d}"";
}
}";
string expectedOutput = @"<>
<System.String[]>";
var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics();
}
[Fact]
public void UnclosedInterpolation01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31),
// (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35),
// (7,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6),
// (7,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6),
// (8,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2));
}
[Fact]
public void UnclosedInterpolation02()
{
string source =
@"class Program
{
static void Main(string[] args)
{
var x = $"";";
// The precise error messages are not important, but this must be an error.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,19): error CS1010: Newline in constant
// var x = $";
Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19),
// (5,20): error CS1002: ; expected
// var x = $";
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20)
);
}
[Fact]
public void EmptyFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8089: Empty format specifier.
// Console.WriteLine( $"{3:}" );
Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:d }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $"{3:d }" );
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{3:d
}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $@"{3:d
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d
").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS1733: Expected expression
// Console.WriteLine( $"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32)
);
}
[Fact]
public void MissingInterpolationExpression02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS1733: Expected expression
// Console.WriteLine( $@"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression03()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( ";
var normal = "$\"";
var verbat = "$@\"";
// ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail)
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
"" }
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
""}
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void PreprocessorInsideInterpolation()
{
string source =
@"class Program
{
static void Main()
{
var s = $@""{
#region :
#endregion
0
}"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void EscapedCurly()
{
string source =
@"class Program
{
static void Main()
{
var s1 = $"" \u007B "";
var s2 = $"" \u007D"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string.
// var s1 = $" \u007B ";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21),
// (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var s2 = $" \u007D";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21)
);
}
[Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")]
public void NoFillIns01()
{
string source =
@"class Program
{
static void Main()
{
System.Console.Write($""{{ x }}"");
System.Console.WriteLine($@""This is a test"");
}
}";
string expectedOutput = @"{ x }This is a test";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void BadAlignment()
{
string source =
@"class Program
{
static void Main()
{
var s = $""{1,1E10}"";
var t = $""{1,(int)1E10}"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22),
// (5,22): error CS0150: A constant value is expected
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22),
// (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override)
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22),
// (6,22): error CS0150: A constant value is expected
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22)
);
}
[Fact]
public void NestedInterpolatedVerbatim()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $@""{$@""{1}""}"";
Console.WriteLine(s);
}
}";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
// Since the platform type System.FormattableString is not yet in our platforms (at the
// time of writing), we explicitly include the required platform types into the sources under test.
private const string formattableString = @"
/*============================================================
**
** Class: FormattableString
**
**
** Purpose: implementation of the FormattableString
** class.
**
===========================================================*/
namespace System
{
/// <summary>
/// A composite format string along with the arguments to be formatted. An instance of this
/// type may result from the use of the C# or VB language primitive ""interpolated string"".
/// </summary>
public abstract class FormattableString : IFormattable
{
/// <summary>
/// The composite format string.
/// </summary>
public abstract string Format { get; }
/// <summary>
/// Returns an object array that contains zero or more objects to format. Clients should not
/// mutate the contents of the array.
/// </summary>
public abstract object[] GetArguments();
/// <summary>
/// The number of arguments to be formatted.
/// </summary>
public abstract int ArgumentCount { get; }
/// <summary>
/// Returns one argument to be formatted from argument position <paramref name=""index""/>.
/// </summary>
public abstract object GetArgument(int index);
/// <summary>
/// Format to a string using the given culture.
/// </summary>
public abstract string ToString(IFormatProvider formatProvider);
string IFormattable.ToString(string ignored, IFormatProvider formatProvider)
{
return ToString(formatProvider);
}
/// <summary>
/// Format the given object in the invariant culture. This static method may be
/// imported in C# by
/// <code>
/// using static System.FormattableString;
/// </code>.
/// Within the scope
/// of that import directive an interpolated string may be formatted in the
/// invariant culture by writing, for example,
/// <code>
/// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"")
/// </code>
/// </summary>
public static string Invariant(FormattableString formattable)
{
if (formattable == null)
{
throw new ArgumentNullException(""formattable"");
}
return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
}
public override string ToString()
{
return ToString(Globalization.CultureInfo.CurrentCulture);
}
}
}
/*============================================================
**
** Class: FormattableStringFactory
**
**
** Purpose: implementation of the FormattableStringFactory
** class.
**
===========================================================*/
namespace System.Runtime.CompilerServices
{
/// <summary>
/// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>.
/// </summary>
public static class FormattableStringFactory
{
/// <summary>
/// Create a <see cref=""FormattableString""/> from a composite format string and object
/// array containing zero or more objects to format.
/// </summary>
public static FormattableString Create(string format, params object[] arguments)
{
if (format == null)
{
throw new ArgumentNullException(""format"");
}
if (arguments == null)
{
throw new ArgumentNullException(""arguments"");
}
return new ConcreteFormattableString(format, arguments);
}
private sealed class ConcreteFormattableString : FormattableString
{
private readonly string _format;
private readonly object[] _arguments;
internal ConcreteFormattableString(string format, object[] arguments)
{
_format = format;
_arguments = arguments;
}
public override string Format { get { return _format; } }
public override object[] GetArguments() { return _arguments; }
public override int ArgumentCount { get { return _arguments.Length; } }
public override object GetArgument(int index) { return _arguments[index]; }
public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); }
}
}
}
";
[Fact]
public void TargetType01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
Console.Write(f is System.FormattableString);
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "True");
}
[Fact]
public void TargetType02()
{
string source =
@"using System;
interface I1 { void M(String s); }
interface I2 { void M(FormattableString s); }
interface I3 { void M(IFormattable s); }
interface I4 : I1, I2 {}
interface I5 : I1, I3 {}
interface I6 : I2, I3 {}
interface I7 : I1, I2, I3 {}
class C : I1, I2, I3, I4, I5, I6, I7
{
public void M(String s) { Console.Write(1); }
public void M(FormattableString s) { Console.Write(2); }
public void M(IFormattable s) { Console.Write(3); }
}
class Program {
public static void Main(string[] args)
{
C c = new C();
((I1)c).M($"""");
((I2)c).M($"""");
((I3)c).M($"""");
((I4)c).M($"""");
((I5)c).M($"""");
((I6)c).M($"""");
((I7)c).M($"""");
((C)c).M($"""");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "12311211");
}
[Fact]
public void MissingHelper()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
}
}";
CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics(
// (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported
// IFormattable f = $"test";
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26)
);
}
[Fact]
public void AsyncInterp()
{
string source =
@"using System;
using System.Threading.Tasks;
class Program {
public static void Main(string[] args)
{
Task<string> hello = Task.FromResult(""Hello"");
Task<string> world = Task.FromResult(""world"");
M(hello, world).Wait();
}
public static async Task M(Task<string> hello, Task<string> world)
{
Console.WriteLine($""{ await hello }, { await world }!"");
}
}";
CompileAndVerify(
source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty);
}
[Fact]
public void AlignmentExpression()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , -(3+4) }."");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "X = 123 .");
}
[Fact]
public void AlignmentMagnitude()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , (32768) }."");
Console.WriteLine($""X = { 123 , -(32768) }."");
Console.WriteLine($""X = { 123 , (32767) }."");
Console.WriteLine($""X = { 123 , -(32767) }."");
Console.WriteLine($""X = { 123 , int.MaxValue }."");
Console.WriteLine($""X = { 123 , int.MinValue }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , (32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42),
// (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , -(32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41),
// (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MaxValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41),
// (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MinValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41)
);
}
[WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")]
[Fact]
public void InterpolationExpressionMustBeValue01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { String }."");
Console.WriteLine($""X = { null }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS0119: 'string' is a type, which is not valid in the given context
// Console.WriteLine($"X = { String }.");
Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35)
);
}
[Fact]
public void InterpolationExpressionMustBeValue02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { x=>3 }."");
Console.WriteLine($""X = { Program.Main }."");
Console.WriteLine($""X = { Program.Main(null) }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type
// Console.WriteLine($"X = { x=>3 }.");
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35),
// (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method?
// Console.WriteLine($"X = { Program.Main }.");
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43),
// (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object'
// Console.WriteLine($"X = { Program.Main(null) }.");
Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib01()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String { }
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (15,21): error CS0117: 'string' does not contain a definition for 'Format'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib02()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Boolean Format(string format, int arg) { return true; }
}
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21)
);
}
[Fact]
public void SillyCoreLib01()
{
var text =
@"namespace System
{
interface IFormattable { }
namespace Runtime.CompilerServices {
public static class FormattableStringFactory {
public static Bozo Create(string format, int arg) { return new Bozo(); }
}
}
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Bozo Format(string format, int arg) { return new Bozo(); }
}
public class FormattableString {
}
public class Bozo {
public static implicit operator string(Bozo bozo) { return ""zz""; }
public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); }
}
internal class Program
{
public static void Main()
{
var s1 = $""X = { 1 } "";
FormattableString s2 = $""X = { 1 } "";
}
}
}";
var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
var compilation = CompileAndVerify(comp, verify: Verification.Fails);
compilation.VerifyIL("System.Program.Main",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldstr ""X = {0} ""
IL_0005: ldc.i4.1
IL_0006: call ""System.Bozo string.Format(string, int)""
IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)""
IL_0010: pop
IL_0011: ldstr ""X = {0} ""
IL_0016: ldc.i4.1
IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)""
IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)""
IL_0021: pop
IL_0022: ret
}");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax01()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):\}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40),
// (6,40): error CS1009: Unrecognized escape sequence
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40)
);
}
[WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")]
[Fact]
public void Syntax02()
{
var text =
@"using S = System;
class C
{
void M()
{
var x = $""{ (S:
}
}";
// the precise diagnostics do not matter, as long as it is an error and not a crash.
Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax03()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):}}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'.
// var x = $"{ Math.Abs(value: 1):}}";
Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18)
);
}
[WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")]
[Fact]
public void NoUnexpandedForm()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
string[] arr1 = new string[] { ""xyzzy"" };
object[] arr2 = arr1;
Console.WriteLine($""-{null}-"");
Console.WriteLine($""-{arr1}-"");
Console.WriteLine($""-{arr2}-"");
}
}";
CompileAndVerify(source + formattableString, expectedOutput:
@"--
-System.String[]-
-System.String[]-");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Dynamic01()
{
var text =
@"class C
{
const dynamic a = a;
string s = $""{0,a}"";
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19),
// (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null.
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23),
// (4,21): error CS0150: A constant value is expected
// string s = $"{0,a}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21)
);
}
[WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")]
[Fact]
public void Syntax04()
{
var text =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<string>> e = () => $""\u1{0:\u2}"";
Console.WriteLine(e);
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,46): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46),
// (8,52): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52)
);
}
[Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")]
public void MissingConversionFromFormattableStringToIFormattable()
{
var text =
@"namespace System.Runtime.CompilerServices
{
public static class FormattableStringFactory
{
public static FormattableString Create(string format, params object[] arguments)
{
return null;
}
}
}
namespace System
{
public abstract class FormattableString
{
}
}
static class C
{
static void Main()
{
System.IFormattable i = $""{""""}"";
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics(
// (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable'
// System.IFormattable i = $"{""}";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33)
);
}
[Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")]
[InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")]
[InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")]
public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents)
{
var code = @"
using System;
Console.WriteLine(TwoComponents());
Console.WriteLine(ThreeComponents());
Console.WriteLine(FourComponents());
Console.WriteLine(FiveComponents());
string TwoComponents()
{
string s1 = ""1"";
string s2 = ""2"";
return " + twoComponents + @";
}
string ThreeComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
return " + threeComponents + @";
}
string FourComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
return " + fourComponents + @";
}
string FiveComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
string s5 = ""5"";
return " + fiveComponents + @";
}
";
var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @"
12
123
1234
value:1
value:2
value:3
value:4
value:5
");
verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (string V_0) //s2
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: call ""string string.Concat(string, string)""
IL_0011: ret
}
");
verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @"
{
// Code size 25 (0x19)
.maxstack 3
.locals init (string V_0, //s2
string V_1) //s3
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: call ""string string.Concat(string, string, string)""
IL_0018: ret
}
");
verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @"
{
// Code size 32 (0x20)
.maxstack 4
.locals init (string V_0, //s2
string V_1, //s3
string V_2) //s4
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldstr ""4""
IL_0016: stloc.2
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""string string.Concat(string, string, string, string)""
IL_001f: ret
}
");
verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @"
{
// Code size 89 (0x59)
.maxstack 3
.locals init (string V_0, //s1
string V_1, //s2
string V_2, //s3
string V_3, //s4
string V_4, //s5
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5)
IL_0000: ldstr ""1""
IL_0005: stloc.0
IL_0006: ldstr ""2""
IL_000b: stloc.1
IL_000c: ldstr ""3""
IL_0011: stloc.2
IL_0012: ldstr ""4""
IL_0017: stloc.3
IL_0018: ldstr ""5""
IL_001d: stloc.s V_4
IL_001f: ldloca.s V_5
IL_0021: ldc.i4.0
IL_0022: ldc.i4.5
IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0030: ldloca.s V_5
IL_0032: ldloc.1
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0038: ldloca.s V_5
IL_003a: ldloc.2
IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0040: ldloca.s V_5
IL_0042: ldloc.3
IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0048: ldloca.s V_5
IL_004a: ldloc.s V_4
IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0051: ldloca.s V_5
IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0058: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandler_OverloadsAndBoolReturns(
bool useDefaultParameters,
bool useBoolReturns,
bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"int a = 1;
System.Console.WriteLine(" + expression + @");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference });
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 80 (0x50)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldstr ""X""
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.2
IL_0039: ldstr ""Y""
IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: ldloca.s V_1
IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004a: call ""void System.Console.WriteLine(string)""
IL_004f: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 84 (0x54)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: ldc.i4.0
IL_001b: ldnull
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0021: ldloca.s V_1
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: ldnull
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002b: ldloca.s V_1
IL_002d: ldloc.0
IL_002e: ldc.i4.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldloca.s V_1
IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004e: call ""void System.Console.WriteLine(string)""
IL_0053: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 92 (0x5c)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_004d
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: brfalse.s IL_004d
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: brfalse.s IL_004d
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldstr ""X""
IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003b: brfalse.s IL_004d
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: br.s IL_004e
IL_004d: ldc.i4.0
IL_004e: pop
IL_004f: ldloca.s V_1
IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0056: call ""void System.Console.WriteLine(string)""
IL_005b: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_0051
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0023: brfalse.s IL_0051
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: brfalse.s IL_0051
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldc.i4.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004a
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldc.i4.1
IL_0048: br.s IL_004b
IL_004a: ldc.i4.0
IL_004b: pop
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004e
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: ldc.i4.0
IL_001f: ldnull
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: ldloca.s V_1
IL_0031: ldloc.0
IL_0032: ldc.i4.0
IL_0033: ldstr ""X""
IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0051
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0051
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0025: brfalse.s IL_0051
IL_0027: ldloca.s V_1
IL_0029: ldloc.0
IL_002a: ldc.i4.1
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0030: brfalse.s IL_0051
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 100 (0x64)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0055
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0055
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: ldc.i4.0
IL_0021: ldnull
IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0027: brfalse.s IL_0055
IL_0029: ldloca.s V_1
IL_002b: ldloc.0
IL_002c: ldc.i4.1
IL_002d: ldnull
IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0033: brfalse.s IL_0055
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.0
IL_0039: ldstr ""X""
IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: brfalse.s IL_0055
IL_0045: ldloca.s V_1
IL_0047: ldloc.0
IL_0048: ldc.i4.2
IL_0049: ldstr ""Y""
IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0053: br.s IL_0056
IL_0055: ldc.i4.0
IL_0056: pop
IL_0057: ldloca.s V_1
IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005e: call ""void System.Console.WriteLine(string)""
IL_0063: ret
}
",
};
}
[Fact]
public void UseOfSpanInInterpolationHole_CSharp9()
{
var source = @"
using System;
ReadOnlySpan<char> span = stackalloc char[1];
Console.WriteLine($""{span}"");";
var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// Console.WriteLine($"{span}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22)
);
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly))]
[CombinatorialData]
public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"
using System;
ReadOnlySpan<char> a = ""1"";
System.Console.WriteLine(" + expression + ");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldstr ""X""
IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.2
IL_0042: ldstr ""Y""
IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: ldc.i4.0
IL_0024: ldnull
IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002a: ldloca.s V_1
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0034: ldloca.s V_1
IL_0036: ldloc.0
IL_0037: ldc.i4.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 101 (0x65)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_0056
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002a: brfalse.s IL_0056
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: brfalse.s IL_0056
IL_0037: ldloca.s V_1
IL_0039: ldloc.0
IL_003a: ldstr ""X""
IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0044: brfalse.s IL_0056
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: br.s IL_0057
IL_0056: ldc.i4.0
IL_0057: pop
IL_0058: ldloca.s V_1
IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005f: call ""void System.Console.WriteLine(string)""
IL_0064: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_005a
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: ldc.i4.0
IL_0026: ldnull
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002c: brfalse.s IL_005a
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: brfalse.s IL_005a
IL_003a: ldloca.s V_1
IL_003c: ldloc.0
IL_003d: ldc.i4.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 98 (0x62)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0053
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldc.i4.1
IL_0051: br.s IL_0054
IL_0053: ldc.i4.0
IL_0054: pop
IL_0055: ldloca.s V_1
IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005c: call ""void System.Console.WriteLine(string)""
IL_0061: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005a
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005a
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002e: brfalse.s IL_005a
IL_0030: ldloca.s V_1
IL_0032: ldloc.0
IL_0033: ldc.i4.1
IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0039: brfalse.s IL_005a
IL_003b: ldloca.s V_1
IL_003d: ldloc.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 102 (0x66)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0057
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: ldloca.s V_1
IL_003a: ldloc.0
IL_003b: ldc.i4.0
IL_003c: ldstr ""X""
IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: ldc.i4.1
IL_0055: br.s IL_0058
IL_0057: ldc.i4.0
IL_0058: pop
IL_0059: ldloca.s V_1
IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0060: call ""void System.Console.WriteLine(string)""
IL_0065: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 109 (0x6d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005e
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005e
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: ldc.i4.0
IL_002a: ldnull
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0030: brfalse.s IL_005e
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldnull
IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_003c: brfalse.s IL_005e
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: ldstr ""X""
IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: brfalse.s IL_005e
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: ldc.i4.2
IL_0052: ldstr ""Y""
IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_005c: br.s IL_005f
IL_005e: ldc.i4.0
IL_005f: pop
IL_0060: ldloca.s V_1
IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0067: call ""void System.Console.WriteLine(string)""
IL_006c: ret
}
",
};
}
[Theory]
[InlineData(@"$""base{Throw()}{a = 2}""")]
[InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")]
public void BoolReturns_ShortCircuit(string expression)
{
var source = @"
using System;
int a = 1;
Console.Write(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false");
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
1");
}
[Theory]
[CombinatorialData]
public void BoolOutParameter_ShortCircuits(bool useBoolReturns,
[CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression)
{
var source = @"
using System;
int a = 1;
Console.WriteLine(a);
Console.WriteLine(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
1");
}
[Theory]
[InlineData(@"$""base{await Hole()}""")]
[InlineData(@"$""base"" + $""{await Hole()}""")]
public void AwaitInHoles_UsesFormat(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1");
verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @"
{
// Code size 164 (0xa4)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_003c: leave.s IL_00a3
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base{0}""
IL_0067: ldloc.1
IL_0068: box ""int""
IL_006d: call ""string string.Format(string, object)""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0090
}
catch System.Exception
{
IL_0079: stloc.3
IL_007a: ldarg.0
IL_007b: ldc.i4.s -2
IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0082: ldarg.0
IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0088: ldloc.3
IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_008e: leave.s IL_00a3
}
IL_0090: ldarg.0
IL_0091: ldc.i4.s -2
IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0098: ldarg.0
IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a3: ret
}
"
: @"
{
// Code size 174 (0xae)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_003c: leave.s IL_00ad
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base""
IL_0067: ldstr ""{0}""
IL_006c: ldloc.1
IL_006d: box ""int""
IL_0072: call ""string string.Format(string, object)""
IL_0077: call ""string string.Concat(string, string)""
IL_007c: call ""void System.Console.WriteLine(string)""
IL_0081: leave.s IL_009a
}
catch System.Exception
{
IL_0083: stloc.3
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0092: ldloc.3
IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0098: leave.s IL_00ad
}
IL_009a: ldarg.0
IL_009b: ldc.i4.s -2
IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00a2: ldarg.0
IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00ad: ret
}");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = await Hole();
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
value:1");
verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 185 (0xb9)
.maxstack 3
.locals init (int V_0,
int V_1, //hole
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_003c: leave.s IL_00b8
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldc.i4.4
IL_0063: ldc.i4.1
IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0069: stloc.3
IL_006a: ldloca.s V_3
IL_006c: ldstr ""base""
IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0076: ldloca.s V_3
IL_0078: ldloc.1
IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_007e: ldloca.s V_3
IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0085: call ""void System.Console.WriteLine(string)""
IL_008a: leave.s IL_00a5
}
catch System.Exception
{
IL_008c: stloc.s V_4
IL_008e: ldarg.0
IL_008f: ldc.i4.s -2
IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0096: ldarg.0
IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_009c: ldloc.s V_4
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_00a3: leave.s IL_00b8
}
IL_00a5: ldarg.0
IL_00a6: ldc.i4.s -2
IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00ad: ldarg.0
IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00b8: ret
}
");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = 2;
Test(await M(1), " + expression + @", await M(3));
void Test(int i1, string s, int i2) => Console.WriteLine(s);
Task<int> M(int i)
{
Console.WriteLine(i);
return Task.FromResult(1);
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
3
base
value:2");
verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 328 (0x148)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0050
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00dc
IL_0011: ldarg.0
IL_0012: ldc.i4.2
IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2""
IL_0018: ldc.i4.1
IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)""
IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0023: stloc.2
IL_0024: ldloca.s V_2
IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_002b: brtrue.s IL_006c
IL_002d: ldarg.0
IL_002e: ldc.i4.0
IL_002f: dup
IL_0030: stloc.0
IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0036: ldarg.0
IL_0037: ldloc.2
IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_003d: ldarg.0
IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0043: ldloca.s V_2
IL_0045: ldarg.0
IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_004b: leave IL_0147
IL_0050: ldarg.0
IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0056: stloc.2
IL_0057: ldarg.0
IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0063: ldarg.0
IL_0064: ldc.i4.m1
IL_0065: dup
IL_0066: stloc.0
IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_006c: ldarg.0
IL_006d: ldloca.s V_2
IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2""
IL_0079: ldarg.0
IL_007a: ldc.i4.4
IL_007b: ldc.i4.1
IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0081: stloc.3
IL_0082: ldloca.s V_3
IL_0084: ldstr ""base""
IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_008e: ldloca.s V_3
IL_0090: ldarg.0
IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2""
IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_009b: ldloca.s V_3
IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3""
IL_00a7: ldc.i4.3
IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)""
IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_00b2: stloc.2
IL_00b3: ldloca.s V_2
IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_00ba: brtrue.s IL_00f8
IL_00bc: ldarg.0
IL_00bd: ldc.i4.1
IL_00be: dup
IL_00bf: stloc.0
IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00c5: ldarg.0
IL_00c6: ldloc.2
IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_00cc: ldarg.0
IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_00d2: ldloca.s V_2
IL_00d4: ldarg.0
IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_00da: leave.s IL_0147
IL_00dc: ldarg.0
IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_00e2: stloc.2
IL_00e3: ldarg.0
IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_00ef: ldarg.0
IL_00f0: ldc.i4.m1
IL_00f1: dup
IL_00f2: stloc.0
IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00f8: ldloca.s V_2
IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00ff: stloc.1
IL_0100: ldarg.0
IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2""
IL_0106: ldarg.0
IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3""
IL_010c: ldloc.1
IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)""
IL_0112: ldarg.0
IL_0113: ldnull
IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3""
IL_0119: leave.s IL_0134
}
catch System.Exception
{
IL_011b: stloc.s V_4
IL_011d: ldarg.0
IL_011e: ldc.i4.s -2
IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0125: ldarg.0
IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_012b: ldloc.s V_4
IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0132: leave.s IL_0147
}
IL_0134: ldarg.0
IL_0135: ldc.i4.s -2
IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_013c: ldarg.0
IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0147: ret
}
");
}
[Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void DynamicInHoles_UsesFormat(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
dynamic hole = 1;
Console.WriteLine(" + expression + @");
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1");
verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+')
? @"
{
// Code size 34 (0x22)
.maxstack 3
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""base""
IL_000c: ldstr ""{0}""
IL_0011: ldloc.0
IL_0012: call ""string string.Format(string, object)""
IL_0017: call ""string string.Concat(string, string)""
IL_001c: call ""void System.Console.WriteLine(string)""
IL_0021: ret
}
"
: @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""base{0}""
IL_000c: ldloc.0
IL_000d: call ""string string.Format(string, object)""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}
");
}
[Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")]
[InlineData(@"$""{hole}base""")]
[InlineData(@"$""{hole}"" + $""base""")]
public void DynamicInHoles_UsesFormat2(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
dynamic hole = 1;
Console.WriteLine(" + expression + @");
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base");
verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+')
? @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""{0}""
IL_000c: ldloc.0
IL_000d: call ""string string.Format(string, object)""
IL_0012: ldstr ""base""
IL_0017: call ""string string.Concat(string, string)""
IL_001c: call ""void System.Console.WriteLine(string)""
IL_0021: ret
}
"
: @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""{0}base""
IL_000c: ldloc.0
IL_000d: call ""string string.Format(string, object)""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}
");
}
[Fact]
public void ImplicitConversionsInConstructor()
{
var code = @"
using System.Runtime.CompilerServices;
CustomHandler c = $"""";
[InterpolatedStringHandler]
struct CustomHandler
{
public CustomHandler(object literalLength, object formattedCount) {}
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute });
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: box ""int""
IL_0006: ldc.i4.0
IL_0007: box ""int""
IL_000c: newobj ""CustomHandler..ctor(object, object)""
IL_0011: pop
IL_0012: ret
}
");
}
[Fact]
public void MissingCreate_01()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_02()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_03()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5)
);
}
[Theory]
[InlineData(null)]
[InlineData("public string ToStringAndClear(int literalLength) => throw null;")]
[InlineData("public void ToStringAndClear() => throw null;")]
[InlineData("public static string ToStringAndClear() => throw null;")]
public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod)
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
" + toStringAndClearMethod + @"
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteCreateMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
[System.Obsolete(""Constructor is obsolete"", error: true)]
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteAppendLiteralMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
[System.Obsolete(""AppendLiteral is obsolete"", error: true)]
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7)
);
}
[Fact]
public void ObsoleteAppendFormattedMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
[System.Obsolete(""AppendFormatted is obsolete"", error: true)]
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11)
);
}
private const string UnmanagedCallersOnlyIl = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
}
}";
[Fact]
public void UnmanagedCallersOnlyAppendFormattedMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void Dispose () cil managed
{
ldnull
throw
}
.method public hidebysig virtual
instance string ToString () cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics(
// (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7)
);
}
[Fact]
public void UnmanagedCallersOnlyToStringMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig instance string ToStringAndClear () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5)
);
}
[Theory]
[InlineData(@"$""{i}{s}""")]
[InlineData(@"$""{i}"" + $""{s}""")]
public void UnsupportedArgumentType(string expression)
{
var source = @"
unsafe
{
int* i = null;
var s = new S();
_ = " + expression + @";
}
ref struct S
{
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,11): error CS0306: The type 'int*' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11),
// (6,14): error CS0306: The type 'S' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length)
);
}
[Theory]
[InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")]
[InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")]
public void TargetTypedInterpolationHoles(string expression)
{
var source = @"
bool b = true;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2
value:
value:");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (bool V_0, //b
object V_1,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.0
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0017
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: stloc.1
IL_0015: br.s IL_0019
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldloca.s V_2
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0021: ldloca.s V_2
IL_0023: ldloc.0
IL_0024: brfalse.s IL_002e
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: br.s IL_002f
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0034: ldloca.s V_2
IL_0036: ldnull
IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_003c: ldloca.s V_2
IL_003e: ldnull
IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0044: ldloca.s V_2
IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004b: call ""void System.Console.WriteLine(string)""
IL_0050: ret
}
");
}
[Theory]
[InlineData(@"$""{(null, default)}{new()}""")]
[InlineData(@"$""{(null, default)}"" + $""{new()}""")]
public void TargetTypedInterpolationHoles_Errors(string expression)
{
var source = @"System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object'
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29),
// (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29),
// (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length)
);
}
[Fact]
public void RefTernary()
{
var source = @"
bool b = true;
int i = 1;
System.Console.WriteLine($""{(!b ? ref i : ref i)}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
}
[Fact]
public void NestedInterpolatedStrings_01()
{
var source = @"
int i = 1;
System.Console.WriteLine($""{$""{i}""}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldloc.0
IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0013: ldloca.s V_1
IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001a: call ""void System.Console.WriteLine(string)""
IL_001f: ret
}
");
}
[Theory]
[InlineData(@"$""{$""{i1}""}{$""{i2}""}""")]
[InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")]
public void NestedInterpolatedStrings_02(string expression)
{
var source = @"
int i1 = 1;
int i2 = 2;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 63 (0x3f)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldloca.s V_2
IL_0006: ldc.i4.0
IL_0007: ldc.i4.1
IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000d: ldloca.s V_2
IL_000f: ldloc.0
IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0015: ldloca.s V_2
IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001c: ldloca.s V_2
IL_001e: ldc.i4.0
IL_001f: ldc.i4.1
IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0025: ldloca.s V_2
IL_0027: ldloc.1
IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_002d: ldloca.s V_2
IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0034: call ""string string.Concat(string, string)""
IL_0039: call ""void System.Console.WriteLine(string)""
IL_003e: ret
}
");
}
[Fact]
public void ExceptionFilter_01()
{
var source = @"
using System;
int i = 1;
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = i };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{i}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public int Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 95 (0x5f)
.maxstack 4
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
.try
{
IL_0002: ldstr ""Starting try""
IL_0007: call ""void System.Console.WriteLine(string)""
IL_000c: newobj ""MyException..ctor()""
IL_0011: dup
IL_0012: ldloc.0
IL_0013: callvirt ""void MyException.Prop.set""
IL_0018: throw
}
filter
{
IL_0019: isinst ""MyException""
IL_001e: dup
IL_001f: brtrue.s IL_0025
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: br.s IL_004f
IL_0025: callvirt ""string object.ToString()""
IL_002a: ldloca.s V_1
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0033: ldloca.s V_1
IL_0035: ldloc.0
IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_003b: ldloca.s V_1
IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0042: callvirt ""string string.Trim()""
IL_0047: call ""bool string.op_Equality(string, string)""
IL_004c: ldc.i4.0
IL_004d: cgt.un
IL_004f: endfilter
} // end filter
{ // handler
IL_0051: pop
IL_0052: ldstr ""Caught""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: leave.s IL_005e
}
IL_005e: ret
}
");
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
public void ExceptionFilter_02()
{
var source = @"
using System;
ReadOnlySpan<char> s = new char[] { 'i' };
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = s.ToString() };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{s}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public string Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 122 (0x7a)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //s
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newarr ""char""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.s 105
IL_000a: stelem.i2
IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])""
IL_0010: stloc.0
.try
{
IL_0011: ldstr ""Starting try""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: newobj ""MyException..ctor()""
IL_0020: dup
IL_0021: ldloca.s V_0
IL_0023: constrained. ""System.ReadOnlySpan<char>""
IL_0029: callvirt ""string object.ToString()""
IL_002e: callvirt ""void MyException.Prop.set""
IL_0033: throw
}
filter
{
IL_0034: isinst ""MyException""
IL_0039: dup
IL_003a: brtrue.s IL_0040
IL_003c: pop
IL_003d: ldc.i4.0
IL_003e: br.s IL_006a
IL_0040: callvirt ""string object.ToString()""
IL_0045: ldloca.s V_1
IL_0047: ldc.i4.0
IL_0048: ldc.i4.1
IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0056: ldloca.s V_1
IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005d: callvirt ""string string.Trim()""
IL_0062: call ""bool string.op_Equality(string, string)""
IL_0067: ldc.i4.0
IL_0068: cgt.un
IL_006a: endfilter
} // end filter
{ // handler
IL_006c: pop
IL_006d: ldstr ""Caught""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0079
}
IL_0079: ret
}
");
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
[InlineData(@"$""{s}{c}""")]
[InlineData(@"$""{s}"" + $""{c}""")]
public void ImplicitUserDefinedConversionInHole(string expression)
{
var source = @"
using System;
S s = default;
C c = new C();
Console.WriteLine(" + expression + @");
ref struct S
{
public static implicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
class C
{
public static implicit operator ReadOnlySpan<char>(C s) => ""C converted"";
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder },
targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:S converted
value:C");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0, //s
C V_1, //c
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.0
IL_0011: ldc.i4.2
IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0024: ldloca.s V_2
IL_0026: ldloc.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)""
IL_002c: ldloca.s V_2
IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0033: call ""void System.Console.WriteLine(string)""
IL_0038: ret
}
");
}
[Fact]
public void ExplicitUserDefinedConversionInHole()
{
var source = @"
using System;
S s = default;
Console.WriteLine($""{s}"");
ref struct S
{
public static explicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,21): error CS0306: The type 'S' may not be used as a type argument
// Console.WriteLine($"{s}");
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ImplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static implicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var verifier = CompileAndVerify(source, expectedOutput: @"
literal:Text
value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 52 (0x34)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Text""
IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)""
IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)""
IL_001a: ldloca.s V_0
IL_001c: ldc.i4.1
IL_001d: box ""int""
IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0027: ldloca.s V_0
IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
");
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ExplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static explicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct'
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void InvalidBuilderReturnType(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public int AppendLiteral(string s) => 0;
public int AppendFormatted(object o) => 0;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21),
// (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length)
);
}
[Fact]
public void MissingAppendMethods()
{
var source = @"
using System.Runtime.CompilerServices;
CustomHandler c = $""Literal{1}"";
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount) { }
}
";
var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute });
comp.VerifyDiagnostics(
// (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?)
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21),
// (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'.
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21),
// (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?)
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28),
// (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'.
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28)
);
}
[Fact]
public void MissingBoolType()
{
var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var handlerRef = CreateCompilation(handlerSource).EmitToImageReference();
var source = @"CustomHandler c = $""Literal{1}"";";
var comp = CreateCompilation(source, references: new[] { handlerRef });
comp.MakeTypeMissing(SpecialType.System_Boolean);
comp.VerifyDiagnostics(
// (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19)
);
}
[Fact]
public void MissingVoidType()
{
var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false);
var handlerRef = CreateCompilation(handlerSource).EmitToImageReference();
var source = @"
class C
{
public bool M()
{
CustomHandler c = $""Literal{1}"";
return true;
}
}
";
var comp = CreateCompilation(source, references: new[] { handlerRef });
comp.MakeTypeMissing(SpecialType.System_Void);
comp.VerifyEmitDiagnostics();
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_01(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length)
);
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_02(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(string s) { }
public bool AppendFormatted(object o) => true;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length)
);
}
[Fact]
public void MixedBuilderReturnTypes_03()
{
var source = @"
using System;
Console.WriteLine($""{1}"");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o)
{
_builder.AppendLine(""value:"" + o.ToString());
}
}
}";
CompileAndVerify(source, expectedOutput: "value:1");
}
[Fact]
public void MixedBuilderReturnTypes_04()
{
var source = @"
using System;
using System.Text;
using System.Runtime.CompilerServices;
Console.WriteLine((CustomHandler)$""l"");
[InterpolatedStringHandler]
public class CustomHandler
{
private readonly StringBuilder _builder;
public CustomHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public override string ToString() => _builder.ToString();
public bool AppendFormatted(object o) => true;
public void AppendLiteral(string s)
{
_builder.AppendLine(""literal:"" + s.ToString());
}
}
";
CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l");
}
private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler")
{
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var descendentNodes = tree.GetRoot().DescendantNodes();
var interpolatedString =
(ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>()
.Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any())
.FirstOrDefault()
?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(interpolatedString);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.Exists);
Assert.True(semanticInfo.ImplicitConversion.IsValid);
Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler);
Assert.Null(semanticInfo.ImplicitConversion.Method);
if (interpolatedString is BinaryExpressionSyntax)
{
Assert.False(semanticInfo.ConstantValue.HasValue);
AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString());
}
// https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings.
}
private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput)
=> CompileAndVerify(
compilation,
expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null,
verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped);
[Theory]
[CombinatorialData]
public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns,
[CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression)
{
var code = @"
CustomHandler builder = " + expression + @";
System.Console.WriteLine(builder.ToString());";
var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns);
var comp = CreateCompilation(new[] { code, builder });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:Literal
value:1
alignment:2
format:f");
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (type, useBoolReturns) switch
{
(type: "struct", useBoolReturns: true) => @"
{
// Code size 67 (0x43)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""bool CustomHandler.AppendLiteral(string)""
IL_0015: brfalse.s IL_002c
IL_0017: ldloca.s V_1
IL_0019: ldc.i4.1
IL_001a: box ""int""
IL_001f: ldc.i4.2
IL_0020: ldstr ""f""
IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_002a: br.s IL_002d
IL_002c: ldc.i4.0
IL_002d: pop
IL_002e: ldloc.1
IL_002f: stloc.0
IL_0030: ldloca.s V_0
IL_0032: constrained. ""CustomHandler""
IL_0038: callvirt ""string object.ToString()""
IL_003d: call ""void System.Console.WriteLine(string)""
IL_0042: ret
}
",
(type: "struct", useBoolReturns: false) => @"
{
// Code size 61 (0x3d)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(string)""
IL_0015: ldloca.s V_1
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: ldc.i4.2
IL_001e: ldstr ""f""
IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0028: ldloc.1
IL_0029: stloc.0
IL_002a: ldloca.s V_0
IL_002c: constrained. ""CustomHandler""
IL_0032: callvirt ""string object.ToString()""
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ret
}
",
(type: "class", useBoolReturns: true) => @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""Literal""
IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0013: brfalse.s IL_0029
IL_0015: ldloc.0
IL_0016: ldc.i4.1
IL_0017: box ""int""
IL_001c: ldc.i4.2
IL_001d: ldstr ""f""
IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: callvirt ""string object.ToString()""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ret
}
",
(type: "class", useBoolReturns: false) => @"
{
// Code size 47 (0x2f)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldstr ""Literal""
IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: box ""int""
IL_0019: ldc.i4.2
IL_001a: ldstr ""f""
IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0024: callvirt ""string object.ToString()""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ret
}
",
_ => throw ExceptionUtilities.Unreachable
};
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void CustomHandlerMethodArgument(string expression)
{
var code = @"
M(" + expression + @");
void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"($""{1,2:f}"" + $""Literal"")")]
public void ExplicitHandlerCast_InCode(string expression)
{
var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) });
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
syntax = ((CastExpressionSyntax)syntax).Expression;
Assert.Equal(expression, syntax.ToString());
semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
// https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: call ""void System.Console.WriteLine(object)""
IL_0029: ret
}
");
}
[Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void HandlerConversionPreferredOverStringForNonConstant(string expression)
{
var code = @"
CultureInfoNormalizer.Normalize();
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.7
IL_0006: ldc.i4.1
IL_0007: newobj ""CustomHandler..ctor(int, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: ldc.i4.2
IL_0015: ldstr ""f""
IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001f: brfalse.s IL_002e
IL_0021: ldloc.0
IL_0022: ldstr ""Literal""
IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_002c: br.s IL_002f
IL_002e: ldc.i4.0
IL_002f: pop
IL_0030: ldloc.0
IL_0031: call ""void C.M(CustomHandler)""
IL_0036: ret
}
");
comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9);
verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: ldstr ""Literal""
IL_001a: call ""string string.Concat(string, string)""
IL_001f: call ""void C.M(string)""
IL_0024: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}Literal""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: call ""void C.M(string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
throw null;
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Literal""
IL_0005: call ""void C.M(string)""
IL_000a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}{2}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type
// [Attr($"{1}{2}")]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2)
);
VerifyInterpolatedStringExpression(comp);
var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate);
void validate(ModuleSymbol m)
{
var attr = m.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => throw null;
public static void M(CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
comp.VerifyDiagnostics(
// (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)'
// C.M($"");
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_01(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_02(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_03(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'.
// C.M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_01(string expression)
{
var code = @"
C.M(" + expression + @", default(CustomHandler));
C.M(default(CustomHandler), " + expression + @");
class C
{
public static void M<T>(T t1, T t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M($"{1,2:f}Literal", default(CustomHandler));
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3),
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_02(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), () => $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_03(string expression)
{
var code = @"
using System;
C.M(" + expression + @", default(CustomHandler));
class C
{
public static void M<T>(T t1, T t2) => Console.WriteLine(t1);
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ldnull
IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)""
IL_0032: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_04(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2());
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_01(string expression)
{
var code = @"
using System;
Func<CustomHandler> f = () => " + expression + @";
Console.WriteLine(f());
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_02(string expression)
{
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(() => " + expression + @");
class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
";
// Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string,
// so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec).
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
// No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldstr ""{0,2:f}Literal""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldstr ""{0,2:f}""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ldstr ""Literal""
IL_0015: call ""string string.Concat(string, string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_03(string expression)
{
// Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct
// when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to
// fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>.
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => throw null;
public static void M(Func<CustomHandler> f) => Console.WriteLine(f());
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
public ref struct S
{
public string Field { get; set; }
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 35 (0x23)
.maxstack 4
.locals init (S V_0)
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldloca.s V_0
IL_000a: initobj ""S""
IL_0010: ldloca.s V_0
IL_0012: ldstr ""Field""
IL_0017: call ""void S.Field.set""
IL_001c: ldloc.0
IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)""
IL_0022: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_04(string expression)
{
// Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type)
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => throw null;
}
public ref struct S
{
public string Field { get; set; }
}
namespace System.Runtime.CompilerServices
{
public ref partial struct DefaultInterpolatedStringHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
}
";
string[] source = new[] {
code,
GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false),
GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11),
// (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0,
S V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldloca.s V_1
IL_000d: initobj ""S""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""Field""
IL_001a: call ""void S.Field.set""
IL_001f: ldloc.1
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)""
IL_0025: ldloca.s V_0
IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_05(string expression)
{
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => throw null;
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_06(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion
// means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec)
// and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type
// has an identity conversion to the return type of Func<bool, string>, that is preferred.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ret
}
"
: @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_07(string expression)
{
// Same as 5, but with an implicit conversion from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_08(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)'
// C.M(b =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void LambdaInference_AmbiguousInOlderLangVersions(string expression)
{
var code = @"
using System;
C.M(param =>
{
param = " + expression + @";
});
static class C
{
public static void M(Action<string> f) => throw null;
public static void M(Action<CustomHandler> f) => throw null;
}
";
var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) };
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
// This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04
// We should not be changing binding behavior based on LangVersion.
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)'
// C.M(param =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_01(string expression)
{
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_0024
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: br.s IL_0032
IL_0024: ldloca.s V_0
IL_0026: initobj ""CustomHandler""
IL_002c: ldloc.0
IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
"
: @"
{
// Code size 66 (0x42)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_002e
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: br.s IL_003c
IL_002e: ldloca.s V_0
IL_0030: initobj ""CustomHandler""
IL_0036: ldloc.0
IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_03(string expression)
{
// Same as 02, but with a target-type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_04(string expression)
{
// Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_05(string expression)
{
// Same 01, but with a conversion from string to CustomHandler and CustomHandler to string.
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another
// var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_06(string expression)
{
// Same 05, but with a target type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0046: call ""void System.Console.WriteLine(string)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_01(string expression)
{
// Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types
// and not on expression conversions, no best type can be found for this switch expression.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 59 (0x3b)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_0034
IL_0023: ldstr ""{0,2:f}Literal""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
"
: @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_003e
IL_0023: ldstr ""{0,2:f}""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: ldstr ""Literal""
IL_0038: call ""string string.Concat(string, string)""
IL_003d: stloc.0
IL_003e: ldloc.0
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_03(string expression)
{
// Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile).
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_04(string expression)
{
// Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: box ""CustomHandler""
IL_0049: call ""void System.Console.WriteLine(object)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_05(string expression)
{
// Same as 01, but with conversions in both directions. No best common type can be found.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_06(string expression)
{
// Same as 05, but with a target type.
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_01(string expression)
{
var code = @"
M(" + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_02(string expression)
{
var code = @"
M(" + expression + @");
M(ref " + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword
// M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3),
// (3,7): error CS1510: A ref or out value must be an assignable variable
// M(ref $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_03(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 45 (0x2d)
.maxstack 5
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: stloc.0
IL_0025: ldloca.s V_0
IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_04(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => throw null;
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c);
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void RefOverloadResolution_MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => System.Console.WriteLine(c);
public static void M(ref CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
VerifyInterpolatedStringExpression(comp, "CustomHandler1");
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler1 V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler1..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler1.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler1)""
IL_002e: ret
}
");
}
private const string InterpolatedStringHandlerAttributesVB = @"
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerAttribute
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute
Inherits Attribute
Public Sub New(argument As String)
Arguments = { argument }
End Sub
Public Sub New(ParamArray arguments() as String)
Me.Arguments = arguments
End Sub
Public ReadOnly Property Arguments As String()
End Class
End Namespace
";
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (8,27): error CS8946: 'string' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27)
);
var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String)
End Sub
End Class
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
// Note: there is no compilation error here because the natural type of a string is still string, and
// we just bind to that method without checking the handler attribute.
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70)
);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'.
// public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34),
// (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
_ = new C(" + expression + @");
class C
{
public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11),
// (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C<CustomHandler>.M(" + expression + @");
public class C<T>
{
public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20),
// (8,27): error CS8946: 'T' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27)
);
var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C");
var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler");
var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler)));
var cParam = substitutedC.GetMethod("M").Parameters.Single();
Assert.IsType<SubstitutedParameterSymbol>(cParam);
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C(Of T)
Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var goodCode = @"
int i = 10;
C.M(i: i, c: " + expression + @");
";
var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"
i:10
literal:text
");
verifier.VerifyDiagnostics(
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
verifyIL(verifier);
var badCode = @"C.M(" + expression + @", 1);";
comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'.
// C.M($"", 1);
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length),
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
void verifyIL(CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloca.s V_2
IL_0007: ldc.i4.4
IL_0008: ldc.i4.0
IL_0009: ldloc.0
IL_000a: call ""CustomHandler..ctor(int, int, int)""
IL_000f: ldloca.s V_2
IL_0011: ldstr ""text""
IL_0016: call ""bool CustomHandler.AppendLiteral(string)""
IL_001b: pop
IL_001c: ldloc.2
IL_001d: ldloc.1
IL_001e: call ""void C.M(CustomHandler, int)""
IL_0023: ret
}
"
: @"
{
// Code size 43 (0x2b)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldc.i4.4
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_3
IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000f: stloc.2
IL_0010: ldloc.3
IL_0011: brfalse.s IL_0021
IL_0013: ldloca.s V_2
IL_0015: ldstr ""text""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: br.s IL_0022
IL_0021: ldc.i4.0
IL_0022: pop
IL_0023: ldloc.2
IL_0024: ldloc.1
IL_0025: call ""void C.M(CustomHandler, int)""
IL_002a: ret
}
");
}
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
private CustomHandler(int literalLength, int formattedCount, int i) : this() {}
static void InCustomHandler()
{
C.M(1, " + expression + @");
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() });
comp.VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 0;
C.M(" + mRef + @" i, " + expression + @");
public class C
{
public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression,
// (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6));
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this()
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var expectedDiagnostics = extraConstructorArg == ""
? new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5)
}
: new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5),
// (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8)
};
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
comp = CreateCompilation(executableCode, new[] { d });
comp.VerifyDiagnostics(expectedDiagnostics);
}
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString();
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
using System;
int i = 10;
Console.WriteLine(C.M(i, " + expression + @"));
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.1
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""CustomHandler..ctor(int, int, int)""
IL_000e: ldloca.s V_1
IL_0010: ldstr ""2""
IL_0015: call ""bool CustomHandler.AppendLiteral(string)""
IL_001a: pop
IL_001b: ldloc.1
IL_001c: call ""string C.M(int, CustomHandler)""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ret
}
"
: @"
{
// Code size 46 (0x2e)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: ldc.i4.0
IL_0006: ldloc.0
IL_0007: ldloca.s V_2
IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000e: stloc.1
IL_000f: ldloc.2
IL_0010: brfalse.s IL_0020
IL_0012: ldloca.s V_1
IL_0014: ldstr ""2""
IL_0019: call ""bool CustomHandler.AppendLiteral(string)""
IL_001e: br.s IL_0021
IL_0020: ldc.i4.0
IL_0021: pop
IL_0022: ldloc.1
IL_0023: call ""string C.M(int, CustomHandler)""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
int i = 10;
string s = ""arg"";
C.M(i, s, " + expression + @");
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
string expectedOutput = @"
i:10
s:arg
literal:literal
";
var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol verifier)
{
var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 44 (0x2c)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldloca.s V_3
IL_000f: ldc.i4.7
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloc.2
IL_0013: call ""CustomHandler..ctor(int, int, int, string)""
IL_0018: ldloca.s V_3
IL_001a: ldstr ""literal""
IL_001f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0024: pop
IL_0025: ldloc.3
IL_0026: call ""void C.M(int, string, CustomHandler)""
IL_002b: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldc.i4.7
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: ldloc.2
IL_0011: ldloca.s V_4
IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_0018: stloc.3
IL_0019: ldloc.s V_4
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_3
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.3
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
string s = null;
object o;
C.M(i, ref s, out o, " + expression + @");
Console.WriteLine(s);
Console.WriteLine(o);
public class C
{
public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c)
{
Console.WriteLine(s);
o = ""o in M"";
s = ""s in M"";
Console.Write(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
o = null;
s = ""s in constructor"";
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
s in constructor
i:1
literal:literal
s in M
o in M
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 67 (0x43)
.maxstack 8
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)""
IL_0020: stloc.s V_6
IL_0022: ldloca.s V_6
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: pop
IL_002f: ldloc.s V_6
IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_0036: ldloc.1
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ldloc.2
IL_003d: call ""void System.Console.WriteLine(object)""
IL_0042: ret
}
"
: @"
{
// Code size 76 (0x4c)
.maxstack 9
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6,
bool V_7)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: ldloca.s V_7
IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)""
IL_0022: stloc.s V_6
IL_0024: ldloc.s V_7
IL_0026: brfalse.s IL_0036
IL_0028: ldloca.s V_6
IL_002a: ldstr ""literal""
IL_002f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0034: br.s IL_0037
IL_0036: ldc.i4.0
IL_0037: pop
IL_0038: ldloc.s V_6
IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_003f: ldloc.1
IL_0040: call ""void System.Console.WriteLine(string)""
IL_0045: ldloc.2
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), GetString(), " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
GetString
s:str
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 45 (0x2d)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: call ""CustomHandler..ctor(int, int, string, int)""
IL_0019: ldloca.s V_2
IL_001b: ldstr ""literal""
IL_0020: call ""bool CustomHandler.AppendLiteral(string)""
IL_0025: pop
IL_0026: ldloc.2
IL_0027: call ""void C.M(int, string, CustomHandler)""
IL_002c: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_3
IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)""
IL_0019: stloc.2
IL_001a: ldloc.3
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_2
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.2
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetC().M(s: GetString(), i: GetInt(), c: " + expression + @");
C GetC()
{
Console.WriteLine(""GetC"");
return new C { Field = 5 };
}
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public int Field;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetC
GetString
GetInt
s:str
c.Field:5
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 56 (0x38)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4)
IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldloca.s V_4
IL_0019: ldc.i4.7
IL_001a: ldc.i4.0
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: ldloc.2
IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)""
IL_0023: ldloca.s V_4
IL_0025: ldstr ""literal""
IL_002a: call ""bool CustomHandler.AppendLiteral(string)""
IL_002f: pop
IL_0030: ldloc.s V_4
IL_0032: callvirt ""void C.M(int, string, CustomHandler)""
IL_0037: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4,
bool V_5)
IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldc.i4.7
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: ldloca.s V_5
IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)""
IL_0023: stloc.s V_4
IL_0025: ldloc.s V_5
IL_0027: brfalse.s IL_0037
IL_0029: ldloca.s V_4
IL_002b: ldstr ""literal""
IL_0030: call ""bool CustomHandler.AppendLiteral(string)""
IL_0035: br.s IL_0038
IL_0037: ldc.i4.0
IL_0038: pop
IL_0039: ldloc.s V_4
IL_003b: callvirt ""void C.M(int, string, CustomHandler)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), """", " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""i2:"" + i2.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
i1:10
i2:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 43 (0x2b)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldloca.s V_1
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.0
IL_0012: call ""CustomHandler..ctor(int, int, int, int)""
IL_0017: ldloca.s V_1
IL_0019: ldstr ""literal""
IL_001e: call ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: ldloc.1
IL_0025: call ""void C.M(int, string, CustomHandler)""
IL_002a: ret
}
"
: @"
{
// Code size 50 (0x32)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldc.i4.7
IL_000d: ldc.i4.0
IL_000e: ldloc.0
IL_000f: ldloc.0
IL_0010: ldloca.s V_2
IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)""
IL_0017: stloc.1
IL_0018: ldloc.2
IL_0019: brfalse.s IL_0029
IL_001b: ldloca.s V_1
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.1
IL_002c: call ""void C.M(int, string, CustomHandler)""
IL_0031: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, """", " + expression + @");
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 19 (0x13)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: newobj ""CustomHandler..ctor(int, int)""
IL_000d: call ""void C.M(int, string, CustomHandler)""
IL_0012: ret
}
"
: @"
{
// Code size 21 (0x15)
.maxstack 5
.locals init (bool V_0)
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldloca.s V_0
IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)""
IL_000f: call ""void C.M(int, string, CustomHandler)""
IL_0014: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { }
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics(
(extraConstructorArg == "")
? new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12),
// (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12)
}
: new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12),
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12)
}
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
Console.WriteLine(c[10, ""str"", " + expression + @"]);
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: callvirt ""string C.this[int, string, CustomHandler].get""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""string C.this[int, string, CustomHandler].get""
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
c[10, ""str"", " + expression + @"] = """";
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: ldstr """"
IL_002e: callvirt ""void C.this[int, string, CustomHandler].set""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: ldstr """"
IL_0035: callvirt ""void C.this[int, string, CustomHandler].set""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
(new C(5)).M((int)10, ""str"", " + expression + @");
public class C
{
public int Prop { get; }
public C(int i) => Prop = i;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""c.Prop:"" + c.Prop.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
c.Prop:5
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 51 (0x33)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldloca.s V_3
IL_0015: ldc.i4.7
IL_0016: ldc.i4.0
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)""
IL_001f: ldloca.s V_3
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: pop
IL_002c: ldloc.3
IL_002d: callvirt ""void C.M(int, string, CustomHandler)""
IL_0032: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldc.i4.7
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldloc.2
IL_0018: ldloca.s V_4
IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)""
IL_001f: stloc.3
IL_0020: ldloc.s V_4
IL_0022: brfalse.s IL_0032
IL_0024: ldloca.s V_3
IL_0026: ldstr ""literal""
IL_002b: call ""bool CustomHandler.AppendLiteral(string)""
IL_0030: br.s IL_0033
IL_0032: ldc.i4.0
IL_0033: pop
IL_0034: ldloc.3
IL_0035: callvirt ""void C.M(int, string, CustomHandler)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
_ = new C(5, " + expression + @");
public class C
{
public int Prop { get; }
public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
i:5
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 34 (0x22)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.5
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldloca.s V_1
IL_0005: ldc.i4.7
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: call ""CustomHandler..ctor(int, int, int)""
IL_000d: ldloca.s V_1
IL_000f: ldstr ""literal""
IL_0014: call ""bool CustomHandler.AppendLiteral(string)""
IL_0019: pop
IL_001a: ldloc.1
IL_001b: newobj ""C..ctor(int, CustomHandler)""
IL_0020: pop
IL_0021: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public class C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: callvirt ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public struct C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: call ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: call ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC().M(" + expression + @");
" + refness + @" C GetC() => throw null;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword
// GetC().M($"literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10)
);
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
ref C GetC(ref C c) => ref c;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// GetC(ref c).M($"literal");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Rvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(s2, " + expression + @");
public struct S
{
public int I;
public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
s1.I:1
s2.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 6
.locals init (S V_0, //s2
S V_1,
S V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: ldloca.s V_1
IL_0013: initobj ""S""
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.2
IL_001c: stfld ""int S.I""
IL_0021: ldloc.1
IL_0022: stloc.0
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: stloc.2
IL_0028: ldloc.2
IL_0029: ldc.i4.0
IL_002a: ldc.i4.0
IL_002b: ldloc.1
IL_002c: ldloc.2
IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)""
IL_0032: call ""void S.M(S, CustomHandler)""
IL_0037: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Lvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(ref s2, " + expression + @");
public struct S
{
public int I;
public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword
// s1.M(ref s2, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByVal(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(s, " + expression + @");
public struct S
{
public int I;
public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 33 (0x21)
.maxstack 4
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.0
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: ldc.i4.0
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: newobj ""CustomHandler..ctor(int, int, S)""
IL_001b: call ""void S.M(S, CustomHandler)""
IL_0020: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByRef(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(ref s, " + expression + @");
public struct S
{
public int I;
public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (S V_0, //s
S V_1,
S& V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldc.i4.0
IL_0017: ldc.i4.0
IL_0018: ldloc.2
IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)""
IL_001e: call ""void S.M(ref S, CustomHandler)""
IL_0023: ret
}
");
}
[Theory]
[CombinatorialData]
public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetReceiver().M(
GetArg(""Unrelated parameter 1""),
GetArg(""Second value""),
GetArg(""Unrelated parameter 2""),
GetArg(""First value""),
" + expression + @",
GetArg(""Unrelated parameter 4""));
C GetReceiver()
{
Console.WriteLine(""GetReceiver"");
return new C() { Prop = ""Prop"" };
}
string GetArg(string s)
{
Console.WriteLine(s);
return s;
}
public class C
{
public string Prop { get; set; }
public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6)
=> Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @")
: this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""s1:"" + s1);
_builder.AppendLine(""c.Prop:"" + c.Prop);
_builder.AppendLine(""s2:"" + s2);
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns);
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @"
GetReceiver
Unrelated parameter 1
Second value
Unrelated parameter 2
First value
Handler constructor
Unrelated parameter 4
s1:First value
c.Prop:Prop
s2:Second value
literal:literal
");
verifier.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$""literal"" + $""""")]
public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression)
{
var code = @"
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
int i = 1;
C.M(i, " + expression + @");
public class C
{
public static implicit operator C(int i) => throw null;
public static implicit operator C(double d)
{
Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture));
return new C();
}
public override string ToString() => ""C"";
public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (double V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: conv.r8
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.7
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""C C.op_Implicit(double)""
IL_000e: call ""CustomHandler..ctor(int, int, C)""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""literal""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: pop
IL_0020: ldloc.1
IL_0021: call ""void C.M(double, CustomHandler)""
IL_0026: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
public int Prop { get; set; }
public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
return 0;
}
set
{
Console.WriteLine(""Indexer setter"");
Console.WriteLine(c.ToString());
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
GetInt2
Indexer setter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 85 (0x55)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.s V_5
IL_0039: stloc.s V_4
IL_003b: ldloc.2
IL_003c: ldloc.3
IL_003d: ldloc.s V_4
IL_003f: ldloc.2
IL_0040: ldloc.3
IL_0041: ldloc.s V_4
IL_0043: callvirt ""int C.this[int, CustomHandler].get""
IL_0048: ldc.i4.2
IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004e: add
IL_004f: callvirt ""void C.this[int, CustomHandler].set""
IL_0054: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 96 (0x60)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0040
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""void CustomHandler.AppendLiteral(string)""
IL_002e: ldloca.s V_5
IL_0030: ldloc.0
IL_0031: box ""int""
IL_0036: ldc.i4.0
IL_0037: ldnull
IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003d: ldc.i4.1
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.s V_5
IL_0044: stloc.s V_4
IL_0046: ldloc.2
IL_0047: ldloc.3
IL_0048: ldloc.s V_4
IL_004a: ldloc.2
IL_004b: ldloc.3
IL_004c: ldloc.s V_4
IL_004e: callvirt ""int C.this[int, CustomHandler].get""
IL_0053: ldc.i4.2
IL_0054: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0059: add
IL_005a: callvirt ""void C.this[int, CustomHandler].set""
IL_005f: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 91 (0x5b)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_5
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.s V_5
IL_003f: stloc.s V_4
IL_0041: ldloc.2
IL_0042: ldloc.3
IL_0043: ldloc.s V_4
IL_0045: ldloc.2
IL_0046: ldloc.3
IL_0047: ldloc.s V_4
IL_0049: callvirt ""int C.this[int, CustomHandler].get""
IL_004e: ldc.i4.2
IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0054: add
IL_0055: callvirt ""void C.this[int, CustomHandler].set""
IL_005a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 97 (0x61)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0041
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: brfalse.s IL_0041
IL_0030: ldloca.s V_5
IL_0032: ldloc.0
IL_0033: box ""int""
IL_0038: ldc.i4.0
IL_0039: ldnull
IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003f: br.s IL_0042
IL_0041: ldc.i4.0
IL_0042: pop
IL_0043: ldloc.s V_5
IL_0045: stloc.s V_4
IL_0047: ldloc.2
IL_0048: ldloc.3
IL_0049: ldloc.s V_4
IL_004b: ldloc.2
IL_004c: ldloc.3
IL_004d: ldloc.s V_4
IL_004f: callvirt ""int C.this[int, CustomHandler].get""
IL_0054: ldc.i4.2
IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_005a: add
IL_005b: callvirt ""void C.this[int, CustomHandler].set""
IL_0060: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
Console.WriteLine(c.ToString());
return ref field;
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.this[int, CustomHandler].get""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC().M(GetInt(1), " + expression + @") += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c)
{
Console.WriteLine(""M"");
Console.WriteLine(c.ToString());
return ref field;
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
M
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.M(int, CustomHandler)""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.M(int, CustomHandler)""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.M(int, CustomHandler)""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.M(int, CustomHandler)""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression)
{
var code = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
_ = new C(1) { " + expression + @" };
public class C : IEnumerable<int>
{
public int Field;
public C(int i)
{
Field = i;
}
public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c)
{
Console.WriteLine(c.ToString());
}
public IEnumerator<int> GetEnumerator() => throw null;
IEnumerator IEnumerable.GetEnumerator() => throw null;
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
c.Field:1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 37 (0x25)
.maxstack 5
.locals init (C V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.7
IL_000b: ldc.i4.0
IL_000c: ldloc.0
IL_000d: call ""CustomHandler..ctor(int, int, C)""
IL_0012: ldloca.s V_1
IL_0014: ldstr ""literal""
IL_0019: call ""void CustomHandler.AppendLiteral(string)""
IL_001e: ldloc.1
IL_001f: callvirt ""void C.Add(CustomHandler)""
IL_0024: ret
}
");
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
_ = new C(1) { [" + expression + @"] = 1 };
public class C
{
public int Field;
public C(int i)
{
Field = i;
}
public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c]
{
set => Console.WriteLine(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
c.Field:1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 40 (0x28)
.maxstack 4
.locals init (C V_0,
CustomHandler V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_2
IL_0009: ldc.i4.7
IL_000a: ldc.i4.0
IL_000b: ldloc.0
IL_000c: call ""CustomHandler..ctor(int, int, C)""
IL_0011: ldloca.s V_2
IL_0013: ldstr ""literal""
IL_0018: call ""void CustomHandler.AppendLiteral(string)""
IL_001d: ldloc.2
IL_001e: stloc.1
IL_001f: ldloc.0
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: callvirt ""void C.this[CustomHandler].set""
IL_0027: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter,
[CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler)
{
Console.WriteLine(handler.ToString());
}
}
public partial class CustomHandler
{
private int I = 0;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""int constructor"");
I = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""CustomHandler constructor"");
_builder.AppendLine(""c.I:"" + c.I.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c)
{
_builder.AppendLine(""CustomHandler AppendFormatted"");
_builder.Append(c.ToString());
" + (useBoolReturns ? "return true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
int constructor
CustomHandler constructor
CustomHandler AppendFormatted
c.I:1
literal:Inner string
value:2
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 59 (0x3b)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: dup
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldc.i4.s 12
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0017: dup
IL_0018: ldstr ""Inner string""
IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: box ""int""
IL_002e: ldc.i4.0
IL_002f: ldnull
IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: call ""void C.M(int, CustomHandler)""
IL_003a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0034
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0031: ldc.i4.1
IL_0032: br.s IL_0035
IL_0034: ldc.i4.0
IL_0035: pop
IL_0036: ldloc.s V_4
IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_003d: ldloc.1
IL_003e: ldc.i4.2
IL_003f: box ""int""
IL_0044: ldc.i4.0
IL_0045: ldnull
IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 68 (0x44)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: stloc.2
IL_000e: ldloc.2
IL_000f: ldc.i4.s 12
IL_0011: ldc.i4.0
IL_0012: ldloc.2
IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0018: dup
IL_0019: ldstr ""Inner string""
IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_0029: brfalse.s IL_003b
IL_002b: ldloc.1
IL_002c: ldc.i4.2
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.1
IL_003e: call ""void C.M(int, CustomHandler)""
IL_0043: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0033
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0031: br.s IL_0034
IL_0033: ldc.i4.0
IL_0034: pop
IL_0035: ldloc.s V_4
IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_003c: brfalse.s IL_004e
IL_003e: ldloc.1
IL_003f: ldc.i4.2
IL_0040: box ""int""
IL_0045: ldc.i4.0
IL_0046: ldnull
IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void DiscardsUsedAsParameters(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(out _, " + expression + @");
public class C
{
public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c)
{
i = 0;
Console.WriteLine(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount)
{
i = 1;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 31 (0x1f)
.maxstack 4
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: ldstr ""literal""
IL_0013: call ""void CustomHandler.AppendLiteral(string)""
IL_0018: ldloc.1
IL_0019: call ""void C.M(out int, CustomHandler)""
IL_001e: ret
}
");
}
[Fact]
public void DiscardsUsedAsParameters_DefinedInVB()
{
var vb = @"
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler)
Console.WriteLine(i)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer)
i = 1
End Sub
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var code = @"C.M(out _, $"""");";
var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() });
var verifier = CompileAndVerify(comp, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: call ""void C.M(out int, CustomHandler)""
IL_0010: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DisallowedInExpressionTrees(string expression)
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<CustomHandler>> expr = () => " + expression + @";
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler });
comp.VerifyDiagnostics(
// (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion.
// Expression<Func<CustomHandler>> expr = () => $"";
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46)
);
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_01()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_02()
{
var code = @"
using System.Linq.Expressions;
Expression e = (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_03()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_04()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression e = Func<string, string> () => (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_05()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 167 (0xa7)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldstr ""literal""
IL_0073: ldtoken ""string""
IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0082: ldtoken ""string string.Concat(string, string)""
IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_008c: castclass ""System.Reflection.MethodInfo""
IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0096: ldc.i4.1
IL_0097: newarr ""System.Linq.Expressions.ParameterExpression""
IL_009c: dup
IL_009d: ldc.i4.0
IL_009e: ldloc.0
IL_009f: stelem.ref
IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_00a5: pop
IL_00a6: ret
}
");
}
[Theory]
[CombinatorialData]
public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @", " + expression + @");
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString());
}
public partial class CustomHandler
{
private int i;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
this.i = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.i:"" + c.i.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
};
}
[Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")]
public void AsFormattableString()
{
var code = @"
M($""{1}"" + $""literal"");
System.FormattableString s = $""{1}"" + $""literal"";
void M(System.FormattableString s)
{
}
";
var comp = CreateCompilation(code);
comp.VerifyDiagnostics(
// (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString'
// M($"{1}" + $"literal");
Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3),
// (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString'
// System.FormattableString s = $"{1}" + $"literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30)
);
}
[Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")]
public void AsIFormattable()
{
var code = @"
M($""{1}"" + $""literal"");
System.IFormattable s = $""{1}"" + $""literal"";
void M(System.IFormattable s)
{
}
";
var comp = CreateCompilation(code);
comp.VerifyDiagnostics(
// (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable'
// M($"{1}" + $"literal");
Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3),
// (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable'
// System.IFormattable s = $"{1}" + $"literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25)
);
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter,
[CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression)
{
var code = @"
int i;
string s;
CustomHandler c = " + expression + @";
_ = i.ToString();
_ = o.ToString();
_ = s.ToString();
string M(out object o)
{
o = null;
return null;
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (6,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5),
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else if (useBoolReturns)
{
comp.VerifyDiagnostics(
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression)
{
var code = @"
int i;
CustomHandler c = " + expression + @";
_ = i.ToString();
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (5,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
dynamic d = 1;
M(d, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount)
{
Console.WriteLine(""d:"" + d.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "d:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: box ""int""
IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)""
IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)""
IL_0015: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(dynamic literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: box ""int""
IL_0006: ldc.i4.0
IL_0007: newobj ""CustomHandler..ctor(dynamic, int)""
IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_0011: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
public CustomHandler(dynamic literalLength, int formattedCount)
{
throw null;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_000c: ret
}
");
}
[Theory]
[InlineData(@"$""Literal""")]
[InlineData(@"$"""" + $""Literal""")]
public void DynamicConstruction_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_0015: ldloc.0
IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_001b: ret
}
");
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""""")]
public void DynamicConstruction_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)""
IL_0016: ldloc.0
IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_001c: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_08(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 128 (0x80)
.maxstack 9
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0021: brtrue.s IL_0062
IL_0023: ldc.i4 0x100
IL_0028: ldstr ""AppendFormatted""
IL_002d: ldnull
IL_002e: ldtoken ""Program""
IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0038: ldc.i4.2
IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_003e: dup
IL_003f: ldc.i4.0
IL_0040: ldc.i4.s 9
IL_0042: ldnull
IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0048: stelem.ref
IL_0049: dup
IL_004a: ldc.i4.1
IL_004b: ldc.i4.0
IL_004c: ldnull
IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0052: stelem.ref
IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target""
IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0071: ldloca.s V_1
IL_0073: ldloc.0
IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_0079: ldloc.1
IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_007f: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_09(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public bool AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
return true;
}
public bool AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
return true;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 196 (0xc4)
.maxstack 11
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)""
IL_001c: brfalse IL_00bb
IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_0026: brtrue.s IL_004c
IL_0028: ldc.i4.0
IL_0029: ldtoken ""bool""
IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0033: ldtoken ""Program""
IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target""
IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_0060: brtrue.s IL_009d
IL_0062: ldc.i4.0
IL_0063: ldstr ""AppendFormatted""
IL_0068: ldnull
IL_0069: ldtoken ""Program""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: ldc.i4.2
IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0079: dup
IL_007a: ldc.i4.0
IL_007b: ldc.i4.s 9
IL_007d: ldnull
IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0083: stelem.ref
IL_0084: dup
IL_0085: ldc.i4.1
IL_0086: ldc.i4.0
IL_0087: ldnull
IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_008d: stelem.ref
IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target""
IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_00ac: ldloca.s V_1
IL_00ae: ldloc.0
IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00b9: br.s IL_00bc
IL_00bb: ldc.i4.0
IL_00bc: pop
IL_00bd: ldloc.1
IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_00c3: ret
}
");
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_01(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// return $"{s}";
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_02(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8150: By-value returns may only be used in methods that return by value
// return $"{s}";
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return ref " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref $"{s}";
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
S1 s1;
public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; }
public void AppendFormatted(Span<char> s) => this.s1.s = s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s1, " + expression + @");
}
public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9),
// (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23)
);
}
[Theory]
[InlineData(@"$""{s1}""")]
[InlineData(@"$""{s1}"" + $""""")]
public void RefEscape_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; }
public void AppendFormatted(S1 s1) => s1.s = this.s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s, " + expression + @");
}
public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Fact]
public void RefEscape_08()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; }
public static CustomHandler M()
{
Span<char> s = stackalloc char[10];
ref CustomHandler c = ref M2(ref s, $"""");
return c;
}
public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler)
{
return ref handler;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope
// return c;
Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16)
);
}
[Fact]
public void RefEscape_09()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; }
public static void M(ref S1 s1)
{
Span<char> s2 = stackalloc char[10];
M2(ref s1, $""{s2}"");
}
public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { }
public void AppendFormatted(Span<char> s) { this.s = s; }
}
public ref struct S1
{
public CustomHandler Handler;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope
// M2(ref s1, $"{s2}");
Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9),
// (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope
// M2(ref s1, $"{s2}");
Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23)
);
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_01(string expression)
{
var code = @"
int i = 1;
System.Console.WriteLine(" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
{
value:1
}");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""{ ""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldstr "" }""
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_002b: ldloca.s V_1
IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
");
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_02(string expression)
{
var code = @"
int i = 1;
CustomHandler c = " + expression + @";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:{
value:1
alignment:0
format:
literal: }");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 71 (0x47)
.maxstack 4
.locals init (int V_0, //i
CustomHandler V_1, //c
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_2
IL_000d: ldstr ""{ ""
IL_0012: call ""void CustomHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: box ""int""
IL_001f: ldc.i4.0
IL_0020: ldnull
IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0026: ldloca.s V_2
IL_0028: ldstr "" }""
IL_002d: call ""void CustomHandler.AppendLiteral(string)""
IL_0032: ldloc.2
IL_0033: stloc.1
IL_0034: ldloca.s V_1
IL_0036: constrained. ""CustomHandler""
IL_003c: callvirt ""string object.ToString()""
IL_0041: call ""void System.Console.WriteLine(string)""
IL_0046: ret
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
int i4 = 4;
System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
value:2
value:3
4
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 66 (0x42)
.maxstack 3
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
int V_3, //i4
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldc.i4.4
IL_0007: stloc.3
IL_0008: ldloca.s V_4
IL_000a: ldc.i4.0
IL_000b: ldc.i4.3
IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0011: ldloca.s V_4
IL_0013: ldloc.0
IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0019: ldloca.s V_4
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: ldloca.s V_4
IL_0023: ldloc.2
IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0029: ldloca.s V_4
IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0030: ldloca.s V_3
IL_0032: call ""string int.ToString()""
IL_0037: call ""string string.Concat(string, string)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Theory]
[InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")]
[InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")]
[InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")]
public void InterpolatedStringsAddedUnderObjectAddition2(string expression)
{
var code = $@"
int i1 = 1;
int i2 = 2;
int i3 = 3;
System.Console.WriteLine({expression});";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
CompileAndVerify(comp, expectedOutput: @"
(
value:1
),
[
value:2
],
{
value:3
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition3()
{
var code = @"
#nullable enable
using System;
try
{
var s = string.Empty;
Console.WriteLine($""{s = null}{s.Length}"" + $"""");
}
catch (NullReferenceException)
{
Console.WriteLine(""Null reference exception caught."");
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (string V_0, //s
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
.try
{
IL_0000: ldsfld ""string string.Empty""
IL_0005: stloc.0
IL_0006: ldc.i4.0
IL_0007: ldc.i4.2
IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000d: stloc.1
IL_000e: ldloca.s V_1
IL_0010: ldnull
IL_0011: dup
IL_0012: stloc.0
IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0018: ldloca.s V_1
IL_001a: ldloc.0
IL_001b: callvirt ""int string.Length.get""
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0025: ldloca.s V_1
IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002c: call ""void System.Console.WriteLine(string)""
IL_0031: leave.s IL_0040
}
catch System.NullReferenceException
{
IL_0033: pop
IL_0034: ldstr ""Null reference exception caught.""
IL_0039: call ""void System.Console.WriteLine(string)""
IL_003e: leave.s IL_0040
}
IL_0040: ret
}
").VerifyDiagnostics(
// (9,36): warning CS8602: Dereference of a possibly null reference.
// Console.WriteLine($"{s = null}{s.Length}" + $"");
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36)
);
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment()
{
var code = @"
object o1;
object o2;
object o3;
_ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1;
o1.ToString();
o2.ToString();
o3.ToString();
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) });
comp.VerifyDiagnostics(
// (7,1): error CS0165: Use of unassigned local variable 'o2'
// o2.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1),
// (8,1): error CS0165: Use of unassigned local variable 'o3'
// o3.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1)
);
}
[Fact]
public void ParenthesizedAdditiveExpression_01()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = ($""{i1}"" + $""{i2}"") + $""{i3}"";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
value:3
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 82 (0x52)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
CustomHandler V_3, //c
CustomHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldloca.s V_4
IL_0008: ldc.i4.0
IL_0009: ldc.i4.3
IL_000a: call ""CustomHandler..ctor(int, int)""
IL_000f: ldloca.s V_4
IL_0011: ldloc.0
IL_0012: box ""int""
IL_0017: ldc.i4.0
IL_0018: ldnull
IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001e: ldloca.s V_4
IL_0020: ldloc.1
IL_0021: box ""int""
IL_0026: ldc.i4.0
IL_0027: ldnull
IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_002d: ldloca.s V_4
IL_002f: ldloc.2
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldloc.s V_4
IL_003e: stloc.3
IL_003f: ldloca.s V_3
IL_0041: constrained. ""CustomHandler""
IL_0047: callvirt ""string object.ToString()""
IL_004c: call ""void System.Console.WriteLine(string)""
IL_0051: ret
}");
}
[Fact]
public void ParenthesizedAdditiveExpression_02()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = $""{i1}"" + ($""{i2}"" + $""{i3}"");
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (6,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler c = $"{i1}" + ($"{i2}" + $"{i3}");
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{i1}"" + ($""{i2}"" + $""{i3}"")").WithArguments("string", "CustomHandler").WithLocation(6, 19)
);
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_01(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) = (" + initializer + @");
System.Console.Write(c1.ToString());
System.Console.WriteLine(c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 91 (0x5b)
.maxstack 4
.locals init (CustomHandler V_0, //c1
CustomHandler V_1, //c2
CustomHandler V_2,
CustomHandler V_3)
IL_0000: ldloca.s V_3
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_3
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.0
IL_0012: ldnull
IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0018: ldloc.3
IL_0019: stloc.2
IL_001a: ldloca.s V_3
IL_001c: ldc.i4.0
IL_001d: ldc.i4.1
IL_001e: call ""CustomHandler..ctor(int, int)""
IL_0023: ldloca.s V_3
IL_0025: ldc.i4.2
IL_0026: box ""int""
IL_002b: ldc.i4.0
IL_002c: ldnull
IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0032: ldloc.3
IL_0033: ldloc.2
IL_0034: stloc.0
IL_0035: stloc.1
IL_0036: ldloca.s V_0
IL_0038: constrained. ""CustomHandler""
IL_003e: callvirt ""string object.ToString()""
IL_0043: call ""void System.Console.Write(string)""
IL_0048: ldloca.s V_1
IL_004a: constrained. ""CustomHandler""
IL_0050: callvirt ""string object.ToString()""
IL_0055: call ""void System.Console.WriteLine(string)""
IL_005a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_02(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) t = (" + initializer + @");
System.Console.Write(t.c1.ToString());
System.Console.WriteLine(t.c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 104 (0x68)
.maxstack 6
.locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.1
IL_000e: box ""int""
IL_0013: ldc.i4.0
IL_0014: ldnull
IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001a: ldloc.1
IL_001b: ldloca.s V_1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.1
IL_001f: call ""CustomHandler..ctor(int, int)""
IL_0024: ldloca.s V_1
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: ldc.i4.0
IL_002d: ldnull
IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0033: ldloc.1
IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)""
IL_0039: ldloca.s V_0
IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1""
IL_0040: constrained. ""CustomHandler""
IL_0046: callvirt ""string object.ToString()""
IL_004b: call ""void System.Console.Write(string)""
IL_0050: ldloca.s V_0
IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2""
IL_0057: constrained. ""CustomHandler""
IL_005d: callvirt ""string object.ToString()""
IL_0062: call ""void System.Console.WriteLine(string)""
IL_0067: ret
}
");
}
[Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")]
[InlineData(@"$""{h1}{h2}""")]
[InlineData(@"$""{h1}"" + $""{h2}""")]
public void RefStructHandler_DynamicInHole(string expression)
{
var code = @"
dynamic h1 = 1;
dynamic h2 = 2;
CustomHandler c = " + expression + ";";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false);
var comp = CreateCompilationWithCSharp(new[] { code, handler });
// Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an
// error here. This will crash at runtime because of this.
comp.VerifyEmitDiagnostics();
}
[Theory]
[InlineData(@"$""Literal{1}""")]
[InlineData(@"$""Literal"" + $""{1}""")]
public void ConversionInParamsArguments(string expression)
{
var code = @"
using System;
using System.Linq;
M(" + expression + ", " + expression + @");
void M(params CustomHandler[] handlers)
{
Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString())));
}
";
var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @"
literal:Literal
value:1
alignment:0
format:
literal:Literal
value:1
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 100 (0x64)
.maxstack 7
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.2
IL_0001: newarr ""CustomHandler""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.7
IL_000b: ldc.i4.1
IL_000c: call ""CustomHandler..ctor(int, int)""
IL_0011: ldloca.s V_0
IL_0013: ldstr ""Literal""
IL_0018: call ""void CustomHandler.AppendLiteral(string)""
IL_001d: ldloca.s V_0
IL_001f: ldc.i4.1
IL_0020: box ""int""
IL_0025: ldc.i4.0
IL_0026: ldnull
IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_002c: ldloc.0
IL_002d: stelem ""CustomHandler""
IL_0032: dup
IL_0033: ldc.i4.1
IL_0034: ldloca.s V_0
IL_0036: ldc.i4.7
IL_0037: ldc.i4.1
IL_0038: call ""CustomHandler..ctor(int, int)""
IL_003d: ldloca.s V_0
IL_003f: ldstr ""Literal""
IL_0044: call ""void CustomHandler.AppendLiteral(string)""
IL_0049: ldloca.s V_0
IL_004b: ldc.i4.1
IL_004c: box ""int""
IL_0051: ldc.i4.0
IL_0052: ldnull
IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0058: ldloc.0
IL_0059: stelem ""CustomHandler""
IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])""
IL_0063: ret
}
");
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLocalFunctions_01(string mod)
{
var code = @"
using System.Runtime.CompilerServices;
M($"""");
" + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { }
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3),
// (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { }
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length)
);
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLocalFunctions_02(string mod)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(1, $"""");
" + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString());
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)""
IL_0010: ret
}
");
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLambdas_01(string mod)
{
var code = @"
using System.Runtime.CompilerServices;
var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { };
a($"""");
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.
// var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { };
Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length),
// (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument.
// var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { };
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length)
);
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLambdas_02(string mod)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
a(1, $"""");
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) => throw null;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"");
verifier.VerifyDiagnostics(
// (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.
// var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length)
);
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 45 (0x2d)
.maxstack 4
IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0""
IL_0005: dup
IL_0006: brtrue.s IL_001f
IL_0008: pop
IL_0009: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)""
IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)""
IL_0019: dup
IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0""
IL_001f: ldc.i4.1
IL_0020: ldc.i4.0
IL_0021: ldc.i4.0
IL_0022: newobj ""CustomHandler..ctor(int, int)""
IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)""
IL_002c: ret
}
");
}
[Fact]
public void ArgumentsOnDelegateTypes_01()
{
var code = @"
using System.Runtime.CompilerServices;
M m = null;
m($"""");
delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c);
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// m($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3),
// (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c);
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18)
);
}
[Fact]
public void ArgumentsOnDelegateTypes_02()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler)
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var code = @"
M m = null;
m($"""");
";
var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// m($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3),
// (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// m($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3),
// (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// m($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3)
);
}
[Fact]
public void ArgumentsOnDelegateTypes_03()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M m = (i, c) => Console.WriteLine(c.ToString());
m(1, $"""");
delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c);
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString());
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 5
.locals init (int V_0)
IL_0000: ldsfld ""M Program.<>c.<>9__0_0""
IL_0005: dup
IL_0006: brtrue.s IL_001f
IL_0008: pop
IL_0009: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)""
IL_0014: newobj ""M..ctor(object, System.IntPtr)""
IL_0019: dup
IL_001a: stsfld ""M Program.<>c.<>9__0_0""
IL_001f: ldc.i4.1
IL_0020: stloc.0
IL_0021: ldloc.0
IL_0022: ldc.i4.0
IL_0023: ldc.i4.0
IL_0024: ldloc.0
IL_0025: newobj ""CustomHandler..ctor(int, int, int)""
IL_002a: callvirt ""void M.Invoke(int, CustomHandler)""
IL_002f: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_01()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M($"""");
class C
{
public static void M(CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private int _i = 0;
public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i;
public override string ToString() => _i.ToString();
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 14 (0xe)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: ldc.i4.1
IL_0003: newobj ""CustomHandler..ctor(int, int, int)""
IL_0008: call ""void C.M(CustomHandler)""
IL_000d: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_02()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M($""Literal"");
class C
{
public static void M(CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private string _s = null;
public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; }
public void AppendLiteral(string s) => _s += s;
public override string ToString() => _s;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 38 (0x26)
.maxstack 4
.locals init (CustomHandler V_0,
bool V_1)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.1
IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)""
IL_000a: stloc.0
IL_000b: ldloc.1
IL_000c: brfalse.s IL_001d
IL_000e: ldloca.s V_0
IL_0010: ldstr ""Literal""
IL_0015: call ""void CustomHandler.AppendLiteral(string)""
IL_001a: ldc.i4.1
IL_001b: br.s IL_001e
IL_001d: ldc.i4.0
IL_001e: pop
IL_001f: ldloc.0
IL_0020: call ""void C.M(CustomHandler)""
IL_0025: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_03()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, $"""");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private string _s = null;
public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); }
public void AppendLiteral(string s) => _s += s;
public override string ToString() => _s;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 18 (0x12)
.maxstack 5
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldc.i4.2
IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)""
IL_000c: call ""void C.M(int, CustomHandler)""
IL_0011: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_04()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, $""Literal"");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private string _s = null;
public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; }
public void AppendLiteral(string s) => _s += s;
public override string ToString() => _s;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.7
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: ldc.i4.2
IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)""
IL_000e: stloc.1
IL_000f: ldloc.2
IL_0010: brfalse.s IL_0021
IL_0012: ldloca.s V_1
IL_0014: ldstr ""Literal""
IL_0019: call ""void CustomHandler.AppendLiteral(string)""
IL_001e: ldc.i4.1
IL_001f: br.s IL_0022
IL_0021: ldc.i4.0
IL_0022: pop
IL_0023: ldloc.1
IL_0024: call ""void C.M(int, CustomHandler)""
IL_0029: ret
}
");
}
[Fact]
public void HandlerExtensionMethod_01()
{
var code = @"
$""Test"".M();
public static class StringExt
{
public static void M(this CustomHandler handler) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler'
// $"Test".M();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1)
);
}
[Fact]
public void HandlerExtensionMethod_02()
{
var code = @"
using System.Runtime.CompilerServices;
var s = new S1();
s.M($"""");
public struct S1
{
public int Field = 1;
}
public static class S1Ext
{
public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null;
}
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// s.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5),
// (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null;
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38)
);
}
[Fact]
public void HandlerExtensionMethod_03()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var s = new S1();
s.M($"""");
public struct S1
{
public int Field = 1;
}
public static class S1Ext
{
public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field);
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1");
verifier.VerifyDiagnostics();
}
[Fact]
public void NoStandaloneConstructor()
{
var code = @"
using System.Runtime.CompilerServices;
CustomHandler c = $"""";
[InterpolatedStringHandler]
struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s) {}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute });
comp.VerifyDiagnostics(
// (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)'
// CustomHandler c = $"";
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19),
// (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword
// CustomHandler c = $"";
Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class InterpolationTests : CompilingTestBase
{
[Fact]
public void TestSimpleInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number }."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 }."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 }."");
Console.WriteLine($""Jenny don\'t change your number { number :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}."");
Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}."");
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"Jenny don't change your number 8675309.
Jenny don't change your number 8675309 .
Jenny don't change your number 8675309.
Jenny don't change your number 867-5309.
Jenny don't change your number 867-5309 .
Jenny don't change your number 867-5309.
8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestOnlyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}"");
}
}";
string expectedOutput =
@"8675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""{number}{number}"");
}
}";
string expectedOutput =
@"86753098675309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestDoubleInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
var number = 8675309;
Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}."");
}
}";
string expectedOutput =
@"Jenny don't change your number 867-5309 867-5309.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestEmptyInterp()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }."");
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,73): error CS1733: Expected expression
// Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }.");
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73)
);
}
[Fact]
public void TestHalfOpenInterp01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,63): error CS1010: Newline in constant
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63),
// (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 // "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS8077: A single-line comment may not be used in an interpolated string.
// Console.WriteLine($"Jenny don\'t change your number { 8675309 // ");
Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71),
// (6,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6),
// (6,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void TestHalfOpenInterp03()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""Jenny don\'t change your number { 8675309 /* "");
}
}";
// too many diagnostics perhaps, but it starts the right way.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,71): error CS1035: End-of-file found, '*/' expected
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71),
// (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine($"Jenny don\'t change your number { 8675309 /* ");
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77),
// (7,2): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2),
// (7,2): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2),
// (7,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2));
}
[Fact]
public void LambdaInInterp()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
//Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() });
Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}"");
}
static int number = 8675309;
}
";
string expectedOutput = @"jenny (408) 867-5309";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void OneLiteral()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""Hello"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Hello""
IL_0005: call ""void System.Console.WriteLine(string)""
IL_000a: ret
}
");
}
[Fact]
public void OneInsert()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
Console.WriteLine( $""{hello}"" );
}
}";
string expectedOutput = @"Hello";
var verifier = CompileAndVerify(source, expectedOutput: expectedOutput);
verifier.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldstr ""Hello""
IL_0005: dup
IL_0006: brtrue.s IL_000e
IL_0008: pop
IL_0009: ldstr """"
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}
");
}
[Fact]
public void TwoInserts()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $""{hello}, { world }."" );
}
}";
string expectedOutput = @"Hello, world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TwoInserts02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var hello = $""Hello"";
var world = $""world"" ;
Console.WriteLine( $@""{
hello
},
{
world }."" );
}
}";
string expectedOutput = @"Hello,
world.";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")]
public void DynamicInterpolation()
{
string source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
dynamic nil = null;
dynamic a = new string[] {""Hello"", ""world""};
Console.WriteLine($""<{nil}>"");
Console.WriteLine($""<{a}>"");
}
Expression<Func<string>> M(dynamic d) {
return () => $""Dynamic: {d}"";
}
}";
string expectedOutput = @"<>
<System.String[]>";
var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics();
}
[Fact]
public void UnclosedInterpolation01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31),
// (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string
// Console.WriteLine( $"{" );
Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35),
// (7,6): error CS1026: ) expected
// }
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6),
// (7,6): error CS1002: ; expected
// }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6),
// (8,2): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2));
}
[Fact]
public void UnclosedInterpolation02()
{
string source =
@"class Program
{
static void Main(string[] args)
{
var x = $"";";
// The precise error messages are not important, but this must be an error.
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,19): error CS1010: Newline in constant
// var x = $";
Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19),
// (5,20): error CS1002: ; expected
// var x = $";
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20),
// (5,20): error CS1513: } expected
// var x = $";
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20)
);
}
[Fact]
public void EmptyFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8089: Empty format specifier.
// Console.WriteLine( $"{3:}" );
Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{3:d }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $"{3:d }" );
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32)
);
}
[Fact]
public void TrailingSpaceInFormatSpecifier02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{3:d
}"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS8088: A format specifier may not contain trailing whitespace.
// Console.WriteLine( $@"{3:d
Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d
").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,32): error CS1733: Expected expression
// Console.WriteLine( $"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32)
);
}
[Fact]
public void MissingInterpolationExpression02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( $@""{ }"" );
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (6,33): error CS1733: Expected expression
// Console.WriteLine( $@"{ }" );
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33)
);
}
[Fact]
public void MissingInterpolationExpression03()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine( ";
var normal = "$\"";
var verbat = "$@\"";
// ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail)
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline01()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
"" }
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void MisplacedNewline02()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $""{ @""
""}
"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void PreprocessorInsideInterpolation()
{
string source =
@"class Program
{
static void Main()
{
var s = $@""{
#region :
#endregion
0
}"";
}
}";
// The precise error messages are not important, but this must be an error.
Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[Fact]
public void EscapedCurly()
{
string source =
@"class Program
{
static void Main()
{
var s1 = $"" \u007B "";
var s2 = $"" \u007D"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string.
// var s1 = $" \u007B ";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21),
// (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var s2 = $" \u007D";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21)
);
}
[Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")]
public void NoFillIns01()
{
string source =
@"class Program
{
static void Main()
{
System.Console.Write($""{{ x }}"");
System.Console.WriteLine($@""This is a test"");
}
}";
string expectedOutput = @"{ x }This is a test";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void BadAlignment()
{
string source =
@"class Program
{
static void Main()
{
var s = $""{1,1E10}"";
var t = $""{1,(int)1E10}"";
}
}";
CreateCompilationWithMscorlib45(source).VerifyDiagnostics(
// (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22),
// (5,22): error CS0150: A constant value is expected
// var s = $"{1,1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22),
// (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override)
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22),
// (6,22): error CS0150: A constant value is expected
// var t = $"{1,(int)1E10}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22)
);
}
[Fact]
public void NestedInterpolatedVerbatim()
{
string source =
@"using System;
class Program
{
static void Main(string[] args)
{
var s = $@""{$@""{1}""}"";
Console.WriteLine(s);
}
}";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
// Since the platform type System.FormattableString is not yet in our platforms (at the
// time of writing), we explicitly include the required platform types into the sources under test.
private const string formattableString = @"
/*============================================================
**
** Class: FormattableString
**
**
** Purpose: implementation of the FormattableString
** class.
**
===========================================================*/
namespace System
{
/// <summary>
/// A composite format string along with the arguments to be formatted. An instance of this
/// type may result from the use of the C# or VB language primitive ""interpolated string"".
/// </summary>
public abstract class FormattableString : IFormattable
{
/// <summary>
/// The composite format string.
/// </summary>
public abstract string Format { get; }
/// <summary>
/// Returns an object array that contains zero or more objects to format. Clients should not
/// mutate the contents of the array.
/// </summary>
public abstract object[] GetArguments();
/// <summary>
/// The number of arguments to be formatted.
/// </summary>
public abstract int ArgumentCount { get; }
/// <summary>
/// Returns one argument to be formatted from argument position <paramref name=""index""/>.
/// </summary>
public abstract object GetArgument(int index);
/// <summary>
/// Format to a string using the given culture.
/// </summary>
public abstract string ToString(IFormatProvider formatProvider);
string IFormattable.ToString(string ignored, IFormatProvider formatProvider)
{
return ToString(formatProvider);
}
/// <summary>
/// Format the given object in the invariant culture. This static method may be
/// imported in C# by
/// <code>
/// using static System.FormattableString;
/// </code>.
/// Within the scope
/// of that import directive an interpolated string may be formatted in the
/// invariant culture by writing, for example,
/// <code>
/// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"")
/// </code>
/// </summary>
public static string Invariant(FormattableString formattable)
{
if (formattable == null)
{
throw new ArgumentNullException(""formattable"");
}
return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
}
public override string ToString()
{
return ToString(Globalization.CultureInfo.CurrentCulture);
}
}
}
/*============================================================
**
** Class: FormattableStringFactory
**
**
** Purpose: implementation of the FormattableStringFactory
** class.
**
===========================================================*/
namespace System.Runtime.CompilerServices
{
/// <summary>
/// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>.
/// </summary>
public static class FormattableStringFactory
{
/// <summary>
/// Create a <see cref=""FormattableString""/> from a composite format string and object
/// array containing zero or more objects to format.
/// </summary>
public static FormattableString Create(string format, params object[] arguments)
{
if (format == null)
{
throw new ArgumentNullException(""format"");
}
if (arguments == null)
{
throw new ArgumentNullException(""arguments"");
}
return new ConcreteFormattableString(format, arguments);
}
private sealed class ConcreteFormattableString : FormattableString
{
private readonly string _format;
private readonly object[] _arguments;
internal ConcreteFormattableString(string format, object[] arguments)
{
_format = format;
_arguments = arguments;
}
public override string Format { get { return _format; } }
public override object[] GetArguments() { return _arguments; }
public override int ArgumentCount { get { return _arguments.Length; } }
public override object GetArgument(int index) { return _arguments[index]; }
public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); }
}
}
}
";
[Fact]
public void TargetType01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
Console.Write(f is System.FormattableString);
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "True");
}
[Fact]
public void TargetType02()
{
string source =
@"using System;
interface I1 { void M(String s); }
interface I2 { void M(FormattableString s); }
interface I3 { void M(IFormattable s); }
interface I4 : I1, I2 {}
interface I5 : I1, I3 {}
interface I6 : I2, I3 {}
interface I7 : I1, I2, I3 {}
class C : I1, I2, I3, I4, I5, I6, I7
{
public void M(String s) { Console.Write(1); }
public void M(FormattableString s) { Console.Write(2); }
public void M(IFormattable s) { Console.Write(3); }
}
class Program {
public static void Main(string[] args)
{
C c = new C();
((I1)c).M($"""");
((I2)c).M($"""");
((I3)c).M($"""");
((I4)c).M($"""");
((I5)c).M($"""");
((I6)c).M($"""");
((I7)c).M($"""");
((C)c).M($"""");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "12311211");
}
[Fact]
public void MissingHelper()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
IFormattable f = $""test"";
}
}";
CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics(
// (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported
// IFormattable f = $"test";
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26)
);
}
[Fact]
public void AsyncInterp()
{
string source =
@"using System;
using System.Threading.Tasks;
class Program {
public static void Main(string[] args)
{
Task<string> hello = Task.FromResult(""Hello"");
Task<string> world = Task.FromResult(""world"");
M(hello, world).Wait();
}
public static async Task M(Task<string> hello, Task<string> world)
{
Console.WriteLine($""{ await hello }, { await world }!"");
}
}";
CompileAndVerify(
source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty);
}
[Fact]
public void AlignmentExpression()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , -(3+4) }."");
}
}";
CompileAndVerify(source + formattableString, expectedOutput: "X = 123 .");
}
[Fact]
public void AlignmentMagnitude()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { 123 , (32768) }."");
Console.WriteLine($""X = { 123 , -(32768) }."");
Console.WriteLine($""X = { 123 , (32767) }."");
Console.WriteLine($""X = { 123 , -(32767) }."");
Console.WriteLine($""X = { 123 , int.MaxValue }."");
Console.WriteLine($""X = { 123 , int.MinValue }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , (32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42),
// (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , -(32768) }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41),
// (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MaxValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41),
// (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string.
// Console.WriteLine($"X = { 123 , int.MinValue }.");
Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41)
);
}
[WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")]
[Fact]
public void InterpolationExpressionMustBeValue01()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { String }."");
Console.WriteLine($""X = { null }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS0119: 'string' is a type, which is not valid in the given context
// Console.WriteLine($"X = { String }.");
Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35)
);
}
[Fact]
public void InterpolationExpressionMustBeValue02()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
Console.WriteLine($""X = { x=>3 }."");
Console.WriteLine($""X = { Program.Main }."");
Console.WriteLine($""X = { Program.Main(null) }."");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type
// Console.WriteLine($"X = { x=>3 }.");
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35),
// (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method?
// Console.WriteLine($"X = { Program.Main }.");
Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43),
// (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object'
// Console.WriteLine($"X = { Program.Main(null) }.");
Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib01()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String { }
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (15,21): error CS0117: 'string' does not contain a definition for 'Format'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21)
);
}
[WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")]
[Fact]
public void BadCorelib02()
{
var text =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Boolean Format(string format, int arg) { return true; }
}
internal class Program
{
public static void Main()
{
var s = $""X = { 1 } "";
}
}
}";
CreateEmptyCompilation(text, options: TestOptions.DebugExe)
.VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"),
// (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string'
// var s = $"X = { 1 } ";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21)
);
}
[Fact]
public void SillyCoreLib01()
{
var text =
@"namespace System
{
interface IFormattable { }
namespace Runtime.CompilerServices {
public static class FormattableStringFactory {
public static Bozo Create(string format, int arg) { return new Bozo(); }
}
}
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } }
public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } }
public struct Char { }
public class String {
public static Bozo Format(string format, int arg) { return new Bozo(); }
}
public class FormattableString {
}
public class Bozo {
public static implicit operator string(Bozo bozo) { return ""zz""; }
public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); }
}
internal class Program
{
public static void Main()
{
var s1 = $""X = { 1 } "";
FormattableString s2 = $""X = { 1 } "";
}
}
}";
var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics();
var compilation = CompileAndVerify(comp, verify: Verification.Fails);
compilation.VerifyIL("System.Program.Main",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldstr ""X = {0} ""
IL_0005: ldc.i4.1
IL_0006: call ""System.Bozo string.Format(string, int)""
IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)""
IL_0010: pop
IL_0011: ldstr ""X = {0} ""
IL_0016: ldc.i4.1
IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)""
IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)""
IL_0021: pop
IL_0022: ret
}");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax01()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):\}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string.
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40),
// (6,40): error CS1009: Unrecognized escape sequence
// var x = $"{ Math.Abs(value: 1):\}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40)
);
}
[WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")]
[Fact]
public void Syntax02()
{
var text =
@"using S = System;
class C
{
void M()
{
var x = $""{ (S:
}
}";
// the precise diagnostics do not matter, as long as it is an error and not a crash.
Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Syntax03()
{
var text =
@"using System;
class Program
{
static void Main(string[] args)
{
var x = $""{ Math.Abs(value: 1):}}"";
var y = x;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'.
// var x = $"{ Math.Abs(value: 1):}}";
Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18)
);
}
[WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")]
[Fact]
public void NoUnexpandedForm()
{
string source =
@"using System;
class Program {
public static void Main(string[] args)
{
string[] arr1 = new string[] { ""xyzzy"" };
object[] arr2 = arr1;
Console.WriteLine($""-{null}-"");
Console.WriteLine($""-{arr1}-"");
Console.WriteLine($""-{arr2}-"");
}
}";
CompileAndVerify(source + formattableString, expectedOutput:
@"--
-System.String[]-
-System.String[]-");
}
[WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")]
[Fact]
public void Dynamic01()
{
var text =
@"class C
{
const dynamic a = a;
string s = $""{0,a}"";
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19),
// (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null.
// const dynamic a = a;
Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23),
// (4,21): error CS0150: A constant value is expected
// string s = $"{0,a}";
Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21)
);
}
[WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")]
[Fact]
public void Syntax04()
{
var text =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<string>> e = () => $""\u1{0:\u2}"";
Console.WriteLine(e);
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,46): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46),
// (8,52): error CS1009: Unrecognized escape sequence
// Expression<Func<string>> e = () => $"\u1{0:\u2}";
Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52)
);
}
[Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")]
public void MissingConversionFromFormattableStringToIFormattable()
{
var text =
@"namespace System.Runtime.CompilerServices
{
public static class FormattableStringFactory
{
public static FormattableString Create(string format, params object[] arguments)
{
return null;
}
}
}
namespace System
{
public abstract class FormattableString
{
}
}
static class C
{
static void Main()
{
System.IFormattable i = $""{""""}"";
}
}";
CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics(
// (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable'
// System.IFormattable i = $"{""}";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33)
);
}
[Theory, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")]
[InlineData(@"$""{s1}{s2}""", @"$""{s1}{s2}{s3}""", @"$""{s1}{s2}{s3}{s4}""", @"$""{s1}{s2}{s3}{s4}{s5}""")]
[InlineData(@"$""{s1}"" + $""{s2}""", @"$""{s1}"" + $""{s2}"" + $""{s3}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}""", @"$""{s1}"" + $""{s2}"" + $""{s3}"" + $""{s4}"" + $""{s5}""")]
public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements(string twoComponents, string threeComponents, string fourComponents, string fiveComponents)
{
var code = @"
using System;
Console.WriteLine(TwoComponents());
Console.WriteLine(ThreeComponents());
Console.WriteLine(FourComponents());
Console.WriteLine(FiveComponents());
string TwoComponents()
{
string s1 = ""1"";
string s2 = ""2"";
return " + twoComponents + @";
}
string ThreeComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
return " + threeComponents + @";
}
string FourComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
return " + fourComponents + @";
}
string FiveComponents()
{
string s1 = ""1"";
string s2 = ""2"";
string s3 = ""3"";
string s4 = ""4"";
string s5 = ""5"";
return " + fiveComponents + @";
}
";
var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @"
12
123
1234
value:1
value:2
value:3
value:4
value:5
");
verifier.VerifyIL("Program.<<Main>$>g__TwoComponents|0_0()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (string V_0) //s2
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: call ""string string.Concat(string, string)""
IL_0011: ret
}
");
verifier.VerifyIL("Program.<<Main>$>g__ThreeComponents|0_1()", @"
{
// Code size 25 (0x19)
.maxstack 3
.locals init (string V_0, //s2
string V_1) //s3
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: call ""string string.Concat(string, string, string)""
IL_0018: ret
}
");
verifier.VerifyIL("Program.<<Main>$>g__FourComponents|0_2()", @"
{
// Code size 32 (0x20)
.maxstack 4
.locals init (string V_0, //s2
string V_1, //s3
string V_2) //s4
IL_0000: ldstr ""1""
IL_0005: ldstr ""2""
IL_000a: stloc.0
IL_000b: ldstr ""3""
IL_0010: stloc.1
IL_0011: ldstr ""4""
IL_0016: stloc.2
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""string string.Concat(string, string, string, string)""
IL_001f: ret
}
");
verifier.VerifyIL("Program.<<Main>$>g__FiveComponents|0_3()", @"
{
// Code size 89 (0x59)
.maxstack 3
.locals init (string V_0, //s1
string V_1, //s2
string V_2, //s3
string V_3, //s4
string V_4, //s5
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5)
IL_0000: ldstr ""1""
IL_0005: stloc.0
IL_0006: ldstr ""2""
IL_000b: stloc.1
IL_000c: ldstr ""3""
IL_0011: stloc.2
IL_0012: ldstr ""4""
IL_0017: stloc.3
IL_0018: ldstr ""5""
IL_001d: stloc.s V_4
IL_001f: ldloca.s V_5
IL_0021: ldc.i4.0
IL_0022: ldc.i4.5
IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0030: ldloca.s V_5
IL_0032: ldloc.1
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0038: ldloca.s V_5
IL_003a: ldloc.2
IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0040: ldloca.s V_5
IL_0042: ldloc.3
IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0048: ldloca.s V_5
IL_004a: ldloc.s V_4
IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0051: ldloca.s V_5
IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0058: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandler_OverloadsAndBoolReturns(
bool useDefaultParameters,
bool useBoolReturns,
bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"int a = 1;
System.Console.WriteLine(" + expression + @");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference });
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 80 (0x50)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldloc.0
IL_0022: ldc.i4.1
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldstr ""X""
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.2
IL_0039: ldstr ""Y""
IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: ldloca.s V_1
IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004a: call ""void System.Console.WriteLine(string)""
IL_004f: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 84 (0x54)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: ldc.i4.0
IL_001b: ldnull
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0021: ldloca.s V_1
IL_0023: ldloc.0
IL_0024: ldc.i4.1
IL_0025: ldnull
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002b: ldloca.s V_1
IL_002d: ldloc.0
IL_002e: ldc.i4.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldloca.s V_1
IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004e: call ""void System.Console.WriteLine(string)""
IL_0053: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 92 (0x5c)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_004d
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: brfalse.s IL_004d
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: brfalse.s IL_004d
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldstr ""X""
IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003b: brfalse.s IL_004d
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: br.s IL_004e
IL_004d: ldc.i4.0
IL_004e: pop
IL_004f: ldloca.s V_1
IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0056: call ""void System.Console.WriteLine(string)""
IL_005b: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""base""
IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: brfalse.s IL_0051
IL_0019: ldloca.s V_1
IL_001b: ldloc.0
IL_001c: ldc.i4.0
IL_001d: ldnull
IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0023: brfalse.s IL_0051
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: brfalse.s IL_0051
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldc.i4.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004a
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0023: ldloca.s V_1
IL_0025: ldloc.0
IL_0026: ldc.i4.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldstr ""X""
IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_0039: ldloca.s V_1
IL_003b: ldloc.0
IL_003c: ldc.i4.2
IL_003d: ldstr ""Y""
IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0047: ldc.i4.1
IL_0048: br.s IL_004b
IL_004a: ldc.i4.0
IL_004b: pop
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_004e
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: ldloca.s V_1
IL_001d: ldloc.0
IL_001e: ldc.i4.0
IL_001f: ldnull
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0025: ldloca.s V_1
IL_0027: ldloc.0
IL_0028: ldc.i4.1
IL_0029: ldnull
IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_002f: ldloca.s V_1
IL_0031: ldloc.0
IL_0032: ldc.i4.0
IL_0033: ldstr ""X""
IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_003d: ldloca.s V_1
IL_003f: ldloc.0
IL_0040: ldc.i4.2
IL_0041: ldstr ""Y""
IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 96 (0x60)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0051
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0051
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0025: brfalse.s IL_0051
IL_0027: ldloca.s V_1
IL_0029: ldloc.0
IL_002a: ldc.i4.1
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)""
IL_0030: brfalse.s IL_0051
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldstr ""X""
IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)""
IL_003f: brfalse.s IL_0051
IL_0041: ldloca.s V_1
IL_0043: ldloc.0
IL_0044: ldc.i4.2
IL_0045: ldstr ""Y""
IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_004f: br.s IL_0052
IL_0051: ldc.i4.0
IL_0052: pop
IL_0053: ldloca.s V_1
IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 100 (0x64)
.maxstack 4
.locals init (int V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.4
IL_0004: ldloca.s V_2
IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_000b: stloc.1
IL_000c: ldloc.2
IL_000d: brfalse.s IL_0055
IL_000f: ldloca.s V_1
IL_0011: ldstr ""base""
IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_001b: brfalse.s IL_0055
IL_001d: ldloca.s V_1
IL_001f: ldloc.0
IL_0020: ldc.i4.0
IL_0021: ldnull
IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0027: brfalse.s IL_0055
IL_0029: ldloca.s V_1
IL_002b: ldloc.0
IL_002c: ldc.i4.1
IL_002d: ldnull
IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0033: brfalse.s IL_0055
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldc.i4.0
IL_0039: ldstr ""X""
IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0043: brfalse.s IL_0055
IL_0045: ldloca.s V_1
IL_0047: ldloc.0
IL_0048: ldc.i4.2
IL_0049: ldstr ""Y""
IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)""
IL_0053: br.s IL_0056
IL_0055: ldc.i4.0
IL_0056: pop
IL_0057: ldloca.s V_1
IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005e: call ""void System.Console.WriteLine(string)""
IL_0063: ret
}
",
};
}
[Fact]
public void UseOfSpanInInterpolationHole_CSharp9()
{
var source = @"
using System;
ReadOnlySpan<char> span = stackalloc char[1];
Console.WriteLine($""{span}"");";
var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// Console.WriteLine($"{span}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22)
);
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly))]
[CombinatorialData]
public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg,
[CombinatorialValues(@"$""base{a}{a,1}{a:X}{a,2:Y}""", @"$""base"" + $""{a}"" + $""{a,1}"" + $""{a:X}"" + $""{a,2:Y}""")] string expression)
{
var source =
@"
using System;
ReadOnlySpan<char> a = ""1"";
System.Console.WriteLine(" + expression + ");";
string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg);
string expectedOutput = useDefaultParameters ?
@"base
value:1,alignment:0:format:
value:1,alignment:1:format:
value:1,alignment:0:format:X
value:1,alignment:2:format:Y" :
@"base
value:1
value:1,alignment:1
value:1:format:X
value:1,alignment:2:format:Y";
string expectedIl = getIl();
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp);
foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() })
{
var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10);
verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput);
verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl);
}
string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch
{
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 89 (0x59)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0028: ldloca.s V_1
IL_002a: ldloc.0
IL_002b: ldc.i4.1
IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0031: ldloca.s V_1
IL_0033: ldloc.0
IL_0034: ldstr ""X""
IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.2
IL_0042: ldstr ""Y""
IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: ldloca.s V_1
IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0053: call ""void System.Console.WriteLine(string)""
IL_0058: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @"
{
// Code size 93 (0x5d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: ldloca.s V_1
IL_0022: ldloc.0
IL_0023: ldc.i4.0
IL_0024: ldnull
IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002a: ldloca.s V_1
IL_002c: ldloc.0
IL_002d: ldc.i4.1
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0034: ldloca.s V_1
IL_0036: ldloc.0
IL_0037: ldc.i4.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldloca.s V_1
IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 101 (0x65)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_0056
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002a: brfalse.s IL_0056
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: brfalse.s IL_0056
IL_0037: ldloca.s V_1
IL_0039: ldloc.0
IL_003a: ldstr ""X""
IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0044: brfalse.s IL_0056
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: br.s IL_0057
IL_0056: ldc.i4.0
IL_0057: pop
IL_0058: ldloca.s V_1
IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005f: call ""void System.Console.WriteLine(string)""
IL_0064: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.4
IL_000e: ldc.i4.4
IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0014: ldloca.s V_1
IL_0016: ldstr ""base""
IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0020: brfalse.s IL_005a
IL_0022: ldloca.s V_1
IL_0024: ldloc.0
IL_0025: ldc.i4.0
IL_0026: ldnull
IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002c: brfalse.s IL_005a
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: brfalse.s IL_005a
IL_003a: ldloca.s V_1
IL_003c: ldloc.0
IL_003d: ldc.i4.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 98 (0x62)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0053
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002c: ldloca.s V_1
IL_002e: ldloc.0
IL_002f: ldc.i4.1
IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0035: ldloca.s V_1
IL_0037: ldloc.0
IL_0038: ldstr ""X""
IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0042: ldloca.s V_1
IL_0044: ldloc.0
IL_0045: ldc.i4.2
IL_0046: ldstr ""Y""
IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0050: ldc.i4.1
IL_0051: br.s IL_0054
IL_0053: ldc.i4.0
IL_0054: pop
IL_0055: ldloca.s V_1
IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005c: call ""void System.Console.WriteLine(string)""
IL_0061: ret
}
",
(useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 105 (0x69)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005a
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005a
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_002e: brfalse.s IL_005a
IL_0030: ldloca.s V_1
IL_0032: ldloc.0
IL_0033: ldc.i4.1
IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)""
IL_0039: brfalse.s IL_005a
IL_003b: ldloca.s V_1
IL_003d: ldloc.0
IL_003e: ldstr ""X""
IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)""
IL_0048: brfalse.s IL_005a
IL_004a: ldloca.s V_1
IL_004c: ldloc.0
IL_004d: ldc.i4.2
IL_004e: ldstr ""Y""
IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0058: br.s IL_005b
IL_005a: ldc.i4.0
IL_005b: pop
IL_005c: ldloca.s V_1
IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0063: call ""void System.Console.WriteLine(string)""
IL_0068: ret
}
",
(useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @"
{
// Code size 102 (0x66)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0057
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_002e: ldloca.s V_1
IL_0030: ldloc.0
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0038: ldloca.s V_1
IL_003a: ldloc.0
IL_003b: ldc.i4.0
IL_003c: ldstr ""X""
IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0046: ldloca.s V_1
IL_0048: ldloc.0
IL_0049: ldc.i4.2
IL_004a: ldstr ""Y""
IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0054: ldc.i4.1
IL_0055: br.s IL_0058
IL_0057: ldc.i4.0
IL_0058: pop
IL_0059: ldloca.s V_1
IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0060: call ""void System.Console.WriteLine(string)""
IL_0065: ret
}
",
(useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @"
{
// Code size 109 (0x6d)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //a
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1,
bool V_2)
IL_0000: ldstr ""1""
IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)""
IL_000a: stloc.0
IL_000b: ldc.i4.4
IL_000c: ldc.i4.4
IL_000d: ldloca.s V_2
IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)""
IL_0014: stloc.1
IL_0015: ldloc.2
IL_0016: brfalse.s IL_005e
IL_0018: ldloca.s V_1
IL_001a: ldstr ""base""
IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0024: brfalse.s IL_005e
IL_0026: ldloca.s V_1
IL_0028: ldloc.0
IL_0029: ldc.i4.0
IL_002a: ldnull
IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_0030: brfalse.s IL_005e
IL_0032: ldloca.s V_1
IL_0034: ldloc.0
IL_0035: ldc.i4.1
IL_0036: ldnull
IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_003c: brfalse.s IL_005e
IL_003e: ldloca.s V_1
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: ldstr ""X""
IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_004c: brfalse.s IL_005e
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: ldc.i4.2
IL_0052: ldstr ""Y""
IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)""
IL_005c: br.s IL_005f
IL_005e: ldc.i4.0
IL_005f: pop
IL_0060: ldloca.s V_1
IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0067: call ""void System.Console.WriteLine(string)""
IL_006c: ret
}
",
};
}
[Theory]
[InlineData(@"$""base{Throw()}{a = 2}""")]
[InlineData(@"$""base"" + $""{Throw()}"" + $""{a = 2}""")]
public void BoolReturns_ShortCircuit(string expression)
{
var source = @"
using System;
int a = 1;
Console.Write(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false");
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
1");
}
[Theory]
[CombinatorialData]
public void BoolOutParameter_ShortCircuits(bool useBoolReturns,
[CombinatorialValues(@"$""{Throw()}{a = 2}""", @"$""{Throw()}"" + $""{a = 2}""")] string expression)
{
var source = @"
using System;
int a = 1;
Console.WriteLine(a);
Console.WriteLine(" + expression + @");
Console.WriteLine(a);
string Throw() => throw new Exception();
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
1");
}
[Theory]
[InlineData(@"$""base{await Hole()}""")]
[InlineData(@"$""base"" + $""{await Hole()}""")]
public void AwaitInHoles_UsesFormat(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1");
verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", !expression.Contains("+") ? @"
{
// Code size 164 (0xa4)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_003c: leave.s IL_00a3
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base{0}""
IL_0067: ldloc.1
IL_0068: box ""int""
IL_006d: call ""string string.Format(string, object)""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0090
}
catch System.Exception
{
IL_0079: stloc.3
IL_007a: ldarg.0
IL_007b: ldc.i4.s -2
IL_007d: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0082: ldarg.0
IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0088: ldloc.3
IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_008e: leave.s IL_00a3
}
IL_0090: ldarg.0
IL_0091: ldc.i4.s -2
IL_0093: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0098: ldarg.0
IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a3: ret
}
"
: @"
{
// Code size 174 (0xae)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_003c: leave.s IL_00ad
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldstr ""base""
IL_0067: ldstr ""{0}""
IL_006c: ldloc.1
IL_006d: box ""int""
IL_0072: call ""string string.Format(string, object)""
IL_0077: call ""string string.Concat(string, string)""
IL_007c: call ""void System.Console.WriteLine(string)""
IL_0081: leave.s IL_009a
}
catch System.Exception
{
IL_0083: stloc.3
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0092: ldloc.3
IL_0093: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0098: leave.s IL_00ad
}
IL_009a: ldarg.0
IL_009b: ldc.i4.s -2
IL_009d: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00a2: ldarg.0
IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00ad: ret
}");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = await Hole();
Console.WriteLine(" + expression + @");
Task<int> Hole() => Task.FromResult(1);";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
base
value:1");
verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 185 (0xb9)
.maxstack 3
.locals init (int V_0,
int V_1, //hole
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_003e
IL_000a: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__Hole|0_0()""
IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.0
IL_0022: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_002e: ldarg.0
IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_003c: leave.s IL_00b8
IL_003e: ldarg.0
IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0044: stloc.2
IL_0045: ldarg.0
IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0051: ldarg.0
IL_0052: ldc.i4.m1
IL_0053: dup
IL_0054: stloc.0
IL_0055: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_005a: ldloca.s V_2
IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0061: stloc.1
IL_0062: ldc.i4.4
IL_0063: ldc.i4.1
IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0069: stloc.3
IL_006a: ldloca.s V_3
IL_006c: ldstr ""base""
IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0076: ldloca.s V_3
IL_0078: ldloc.1
IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_007e: ldloca.s V_3
IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0085: call ""void System.Console.WriteLine(string)""
IL_008a: leave.s IL_00a5
}
catch System.Exception
{
IL_008c: stloc.s V_4
IL_008e: ldarg.0
IL_008f: ldc.i4.s -2
IL_0091: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0096: ldarg.0
IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_009c: ldloc.s V_4
IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_00a3: leave.s IL_00b8
}
IL_00a5: ldarg.0
IL_00a6: ldc.i4.s -2
IL_00a8: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00ad: ldarg.0
IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00b8: ret
}
");
}
[Theory]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void NoAwaitInHoles_AwaitInExpression_UsesBuilder(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
var hole = 2;
Test(await M(1), " + expression + @", await M(3));
void Test(int i1, string s, int i2) => Console.WriteLine(s);
Task<int> M(int i)
{
Console.WriteLine(i);
return Task.FromResult(1);
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
1
3
base
value:2");
verifier.VerifyIL("Program.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 328 (0x148)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0050
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00dc
IL_0011: ldarg.0
IL_0012: ldc.i4.2
IL_0013: stfld ""int Program.<<Main>$>d__0.<hole>5__2""
IL_0018: ldc.i4.1
IL_0019: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)""
IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0023: stloc.2
IL_0024: ldloca.s V_2
IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_002b: brtrue.s IL_006c
IL_002d: ldarg.0
IL_002e: ldc.i4.0
IL_002f: dup
IL_0030: stloc.0
IL_0031: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0036: ldarg.0
IL_0037: ldloc.2
IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_003d: ldarg.0
IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0043: ldloca.s V_2
IL_0045: ldarg.0
IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_004b: leave IL_0147
IL_0050: ldarg.0
IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_0056: stloc.2
IL_0057: ldarg.0
IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_0063: ldarg.0
IL_0064: ldc.i4.m1
IL_0065: dup
IL_0066: stloc.0
IL_0067: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_006c: ldarg.0
IL_006d: ldloca.s V_2
IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_0074: stfld ""int Program.<<Main>$>d__0.<>7__wrap2""
IL_0079: ldarg.0
IL_007a: ldc.i4.4
IL_007b: ldc.i4.1
IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0081: stloc.3
IL_0082: ldloca.s V_3
IL_0084: ldstr ""base""
IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_008e: ldloca.s V_3
IL_0090: ldarg.0
IL_0091: ldfld ""int Program.<<Main>$>d__0.<hole>5__2""
IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_009b: ldloca.s V_3
IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_00a2: stfld ""string Program.<<Main>$>d__0.<>7__wrap3""
IL_00a7: ldc.i4.3
IL_00a8: call ""System.Threading.Tasks.Task<int> Program.<<Main>$>g__M|0_1(int)""
IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_00b2: stloc.2
IL_00b3: ldloca.s V_2
IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_00ba: brtrue.s IL_00f8
IL_00bc: ldarg.0
IL_00bd: ldc.i4.1
IL_00be: dup
IL_00bf: stloc.0
IL_00c0: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00c5: ldarg.0
IL_00c6: ldloc.2
IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_00cc: ldarg.0
IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_00d2: ldloca.s V_2
IL_00d4: ldarg.0
IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Program.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Program.<<Main>$>d__0)""
IL_00da: leave.s IL_0147
IL_00dc: ldarg.0
IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_00e2: stloc.2
IL_00e3: ldarg.0
IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Program.<<Main>$>d__0.<>u__1""
IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_00ef: ldarg.0
IL_00f0: ldc.i4.m1
IL_00f1: dup
IL_00f2: stloc.0
IL_00f3: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_00f8: ldloca.s V_2
IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00ff: stloc.1
IL_0100: ldarg.0
IL_0101: ldfld ""int Program.<<Main>$>d__0.<>7__wrap2""
IL_0106: ldarg.0
IL_0107: ldfld ""string Program.<<Main>$>d__0.<>7__wrap3""
IL_010c: ldloc.1
IL_010d: call ""void Program.<<Main>$>g__Test|0_0(int, string, int)""
IL_0112: ldarg.0
IL_0113: ldnull
IL_0114: stfld ""string Program.<<Main>$>d__0.<>7__wrap3""
IL_0119: leave.s IL_0134
}
catch System.Exception
{
IL_011b: stloc.s V_4
IL_011d: ldarg.0
IL_011e: ldc.i4.s -2
IL_0120: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_0125: ldarg.0
IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_012b: ldloc.s V_4
IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0132: leave.s IL_0147
}
IL_0134: ldarg.0
IL_0135: ldc.i4.s -2
IL_0137: stfld ""int Program.<<Main>$>d__0.<>1__state""
IL_013c: ldarg.0
IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<<Main>$>d__0.<>t__builder""
IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0147: ret
}
");
}
[Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")]
[InlineData(@"$""base{hole}""")]
[InlineData(@"$""base"" + $""{hole}""")]
public void DynamicInHoles_UsesFormat(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
dynamic hole = 1;
Console.WriteLine(" + expression + @");
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1");
verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+')
? @"
{
// Code size 34 (0x22)
.maxstack 3
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""base""
IL_000c: ldstr ""{0}""
IL_0011: ldloc.0
IL_0012: call ""string string.Format(string, object)""
IL_0017: call ""string string.Concat(string, string)""
IL_001c: call ""void System.Console.WriteLine(string)""
IL_0021: ret
}
"
: @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""base{0}""
IL_000c: ldloc.0
IL_000d: call ""string string.Format(string, object)""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}
");
}
[Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")]
[InlineData(@"$""{hole}base""")]
[InlineData(@"$""{hole}"" + $""base""")]
public void DynamicInHoles_UsesFormat2(string expression)
{
var source = @"
using System;
using System.Threading.Tasks;
dynamic hole = 1;
Console.WriteLine(" + expression + @");
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerifyWithCSharp(new[] { source, interpolatedStringBuilder }, expectedOutput: @"1base");
verifier.VerifyIL("<top-level-statements-entry-point>", expression.Contains('+')
? @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""{0}""
IL_000c: ldloc.0
IL_000d: call ""string string.Format(string, object)""
IL_0012: ldstr ""base""
IL_0017: call ""string string.Concat(string, string)""
IL_001c: call ""void System.Console.WriteLine(string)""
IL_0021: ret
}
"
: @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0) //hole
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldstr ""{0}base""
IL_000c: ldloc.0
IL_000d: call ""string string.Format(string, object)""
IL_0012: call ""void System.Console.WriteLine(string)""
IL_0017: ret
}
");
}
[Fact]
public void ImplicitConversionsInConstructor()
{
var code = @"
using System.Runtime.CompilerServices;
CustomHandler c = $"""";
[InterpolatedStringHandler]
struct CustomHandler
{
public CustomHandler(object literalLength, object formattedCount) {}
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerAttribute });
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: box ""int""
IL_0006: ldc.i4.0
IL_0007: box ""int""
IL_000c: newobj ""CustomHandler..ctor(object, object)""
IL_0011: pop
IL_0012: ret
}
");
}
[Fact]
public void MissingCreate_01()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_02()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5)
);
}
[Fact]
public void MissingCreate_03()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null;
public override string ToString() => throw null;
public void Dispose() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5)
);
}
[Theory]
[InlineData(null)]
[InlineData("public string ToStringAndClear(int literalLength) => throw null;")]
[InlineData("public void ToStringAndClear() => throw null;")]
[InlineData("public static string ToStringAndClear() => throw null;")]
public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod)
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
" + toStringAndClearMethod + @"
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteCreateMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
[System.Obsolete(""Constructor is obsolete"", error: true)]
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete'
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5)
);
}
[Fact]
public void ObsoleteAppendLiteralMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
[System.Obsolete(""AppendLiteral is obsolete"", error: true)]
public void AppendLiteral(string value) => throw null;
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7)
);
}
[Fact]
public void ObsoleteAppendFormattedMethod()
{
var code = @"_ = $""base{(object)1}"";";
var interpolatedStringBuilder = @"
namespace System.Runtime.CompilerServices
{
public ref struct DefaultInterpolatedStringHandler
{
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null;
public void Dispose() => throw null;
public override string ToString() => throw null;
public void AppendLiteral(string value) => throw null;
[System.Obsolete(""AppendFormatted is obsolete"", error: true)]
public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null;
}
}
";
var comp = CreateCompilation(new[] { code, interpolatedStringBuilder });
comp.VerifyDiagnostics(
// (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete'
// _ = $"base{(object)1}";
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11)
);
}
private const string UnmanagedCallersOnlyIl = @"
.class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute
{
.custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = (
01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72
69 74 65 64 00
)
.field public class [mscorlib]System.Type[] CallConvs
.field public string EntryPoint
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
ldarg.0
call instance void [mscorlib]System.Attribute::.ctor()
ret
}
}";
[Fact]
public void UnmanagedCallersOnlyAppendFormattedMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void Dispose () cil managed
{
ldnull
throw
}
.method public hidebysig virtual
instance string ToString () cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics(
// (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7)
);
}
[Fact]
public void UnmanagedCallersOnlyToStringMethod()
{
var code = @"_ = $""{(object)1}"";";
var interpolatedStringBuilder = @"
.class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler
extends [mscorlib]System.ValueType
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (
01 00 00 00
)
.custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = (
01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d
62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65
73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72
74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73
69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70
69 6c 65 72 2e 01 00 00
)
.pack 0
.size 1
.method public hidebysig specialname rtspecialname
instance void .ctor (
int32 literalLength,
int32 formattedCount
) cil managed
{
ldnull
throw
}
.method public hidebysig instance string ToStringAndClear () cil managed
{
.custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = (
01 00 00 00
)
ldnull
throw
}
.method public hidebysig
instance void AppendLiteral (
string 'value'
) cil managed
{
ldnull
throw
}
.method public hidebysig
instance void AppendFormatted<T> (
!!T hole,
[opt] int32 'alignment',
[opt] string format
) cil managed
{
.param [2] = int32(0)
.param [3] = nullref
ldnull
throw
}
}
";
var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language
// _ = $"{(object)1}";
Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5)
);
}
[Theory]
[InlineData(@"$""{i}{s}""")]
[InlineData(@"$""{i}"" + $""{s}""")]
public void UnsupportedArgumentType(string expression)
{
var source = @"
unsafe
{
int* i = null;
var s = new S();
_ = " + expression + @";
}
ref struct S
{
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (6,11): error CS0306: The type 'int*' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11),
// (6,14): error CS0306: The type 'S' may not be used as a type argument
// _ = $"{i}{s}";
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 5 + expression.Length)
);
}
[Theory]
[InlineData(@"$""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}""")]
[InlineData(@"$""{b switch { true => 1, false => null }}"" + $""{(!b ? null : 2)}"" + $""{default}"" + $""{null}""")]
public void TargetTypedInterpolationHoles(string expression)
{
var source = @"
bool b = true;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2
value:
value:");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (bool V_0, //b
object V_1,
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.0
IL_0005: ldc.i4.4
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0017
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: stloc.1
IL_0015: br.s IL_0019
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldloca.s V_2
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0021: ldloca.s V_2
IL_0023: ldloc.0
IL_0024: brfalse.s IL_002e
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: br.s IL_002f
IL_002e: ldnull
IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0034: ldloca.s V_2
IL_0036: ldnull
IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_003c: ldloca.s V_2
IL_003e: ldnull
IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0044: ldloca.s V_2
IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_004b: call ""void System.Console.WriteLine(string)""
IL_0050: ret
}
");
}
[Theory]
[InlineData(@"$""{(null, default)}{new()}""")]
[InlineData(@"$""{(null, default)}"" + $""{new()}""")]
public void TargetTypedInterpolationHoles_Errors(string expression)
{
var source = @"System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object'
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29),
// (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29),
// (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments
// System.Console.WriteLine($"{(null, default)}{new()}");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 19 + expression.Length)
);
}
[Fact]
public void RefTernary()
{
var source = @"
bool b = true;
int i = 1;
System.Console.WriteLine($""{(!b ? ref i : ref i)}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
}
[Fact]
public void NestedInterpolatedStrings_01()
{
var source = @"
int i = 1;
System.Console.WriteLine($""{$""{i}""}"");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldloc.0
IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0013: ldloca.s V_1
IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001a: call ""void System.Console.WriteLine(string)""
IL_001f: ret
}
");
}
[Theory]
[InlineData(@"$""{$""{i1}""}{$""{i2}""}""")]
[InlineData(@"$""{$""{i1}""}"" + $""{$""{i2}""}""")]
public void NestedInterpolatedStrings_02(string expression)
{
var source = @"
int i1 = 1;
int i2 = 2;
System.Console.WriteLine(" + expression + @");";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
value:1
value:2");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 63 (0x3f)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldloca.s V_2
IL_0006: ldc.i4.0
IL_0007: ldc.i4.1
IL_0008: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000d: ldloca.s V_2
IL_000f: ldloc.0
IL_0010: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0015: ldloca.s V_2
IL_0017: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_001c: ldloca.s V_2
IL_001e: ldc.i4.0
IL_001f: ldc.i4.1
IL_0020: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0025: ldloca.s V_2
IL_0027: ldloc.1
IL_0028: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_002d: ldloca.s V_2
IL_002f: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0034: call ""string string.Concat(string, string)""
IL_0039: call ""void System.Console.WriteLine(string)""
IL_003e: ret
}
");
}
[Fact]
public void ExceptionFilter_01()
{
var source = @"
using System;
int i = 1;
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = i };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{i}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public int Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 95 (0x5f)
.maxstack 4
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
.try
{
IL_0002: ldstr ""Starting try""
IL_0007: call ""void System.Console.WriteLine(string)""
IL_000c: newobj ""MyException..ctor()""
IL_0011: dup
IL_0012: ldloc.0
IL_0013: callvirt ""void MyException.Prop.set""
IL_0018: throw
}
filter
{
IL_0019: isinst ""MyException""
IL_001e: dup
IL_001f: brtrue.s IL_0025
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: br.s IL_004f
IL_0025: callvirt ""string object.ToString()""
IL_002a: ldloca.s V_1
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0033: ldloca.s V_1
IL_0035: ldloc.0
IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_003b: ldloca.s V_1
IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0042: callvirt ""string string.Trim()""
IL_0047: call ""bool string.op_Equality(string, string)""
IL_004c: ldc.i4.0
IL_004d: cgt.un
IL_004f: endfilter
} // end filter
{ // handler
IL_0051: pop
IL_0052: ldstr ""Caught""
IL_0057: call ""void System.Console.WriteLine(string)""
IL_005c: leave.s IL_005e
}
IL_005e: ret
}
");
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
public void ExceptionFilter_02()
{
var source = @"
using System;
ReadOnlySpan<char> s = new char[] { 'i' };
try
{
Console.WriteLine(""Starting try"");
throw new MyException { Prop = s.ToString() };
}
// Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace
catch (MyException e) when (e.ToString() == $""{s}"".Trim())
{
Console.WriteLine(""Caught"");
}
class MyException : Exception
{
public string Prop { get; set; }
public override string ToString() => ""value:"" + Prop.ToString();
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @"
Starting try
Caught");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 122 (0x7a)
.maxstack 4
.locals init (System.ReadOnlySpan<char> V_0, //s
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newarr ""char""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.s 105
IL_000a: stelem.i2
IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])""
IL_0010: stloc.0
.try
{
IL_0011: ldstr ""Starting try""
IL_0016: call ""void System.Console.WriteLine(string)""
IL_001b: newobj ""MyException..ctor()""
IL_0020: dup
IL_0021: ldloca.s V_0
IL_0023: constrained. ""System.ReadOnlySpan<char>""
IL_0029: callvirt ""string object.ToString()""
IL_002e: callvirt ""void MyException.Prop.set""
IL_0033: throw
}
filter
{
IL_0034: isinst ""MyException""
IL_0039: dup
IL_003a: brtrue.s IL_0040
IL_003c: pop
IL_003d: ldc.i4.0
IL_003e: br.s IL_006a
IL_0040: callvirt ""string object.ToString()""
IL_0045: ldloca.s V_1
IL_0047: ldc.i4.0
IL_0048: ldc.i4.1
IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_004e: ldloca.s V_1
IL_0050: ldloc.0
IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0056: ldloca.s V_1
IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_005d: callvirt ""string string.Trim()""
IL_0062: call ""bool string.op_Equality(string, string)""
IL_0067: ldc.i4.0
IL_0068: cgt.un
IL_006a: endfilter
} // end filter
{ // handler
IL_006c: pop
IL_006d: ldstr ""Caught""
IL_0072: call ""void System.Console.WriteLine(string)""
IL_0077: leave.s IL_0079
}
IL_0079: ret
}
");
}
[ConditionalTheory(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))]
[InlineData(@"$""{s}{c}""")]
[InlineData(@"$""{s}"" + $""{c}""")]
public void ImplicitUserDefinedConversionInHole(string expression)
{
var source = @"
using System;
S s = default;
C c = new C();
Console.WriteLine(" + expression + @");
ref struct S
{
public static implicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
class C
{
public static implicit operator ReadOnlySpan<char>(C s) => ""C converted"";
}";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder },
targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:S converted
value:C");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0, //s
C V_1, //c
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.0
IL_0011: ldc.i4.2
IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)""
IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)""
IL_0024: ldloca.s V_2
IL_0026: ldloc.1
IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)""
IL_002c: ldloca.s V_2
IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0033: call ""void System.Console.WriteLine(string)""
IL_0038: ret
}
");
}
[Fact]
public void ExplicitUserDefinedConversionInHole()
{
var source = @"
using System;
S s = default;
Console.WriteLine($""{s}"");
ref struct S
{
public static explicit operator ReadOnlySpan<char>(S s) => ""S converted"";
}
";
var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false);
var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (5,21): error CS0306: The type 'S' may not be used as a type argument
// Console.WriteLine($"{s}");
Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ImplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static implicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var verifier = CompileAndVerify(source, expectedOutput: @"
literal:Text
value:1");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 52 (0x34)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.4
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Text""
IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)""
IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)""
IL_001a: ldloca.s V_0
IL_001c: ldc.i4.1
IL_001d: box ""int""
IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)""
IL_0027: ldloca.s V_0
IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
");
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void ExplicitUserDefinedConversionInLiteral(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
public struct CustomStruct
{
public static explicit operator CustomStruct(string s) => new CustomStruct { S = s };
public string S { get; set; }
public override string ToString() => ""literal:"" + S;
}
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString());
public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct'
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21)
);
}
[Theory]
[InlineData(@"$""Text{1}""")]
[InlineData(@"$""Text"" + $""{1}""")]
public void InvalidBuilderReturnType(string expression)
{
var source = @"
using System;
Console.WriteLine(" + expression + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public int AppendLiteral(string s) => 0;
public int AppendFormatted(object o) => 0;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21),
// (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 15 + expression.Length)
);
}
[Fact]
public void MissingAppendMethods()
{
var source = @"
using System.Runtime.CompilerServices;
CustomHandler c = $""Literal{1}"";
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount) { }
}
";
var comp = CreateCompilation(new[] { source, InterpolatedStringHandlerAttribute });
comp.VerifyDiagnostics(
// (4,21): error CS1061: 'CustomHandler' does not contain a definition for 'AppendLiteral' and no accessible extension method 'AppendLiteral' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?)
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Literal").WithArguments("CustomHandler", "AppendLiteral").WithLocation(4, 21),
// (4,21): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'.
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Literal").WithArguments("?.()").WithLocation(4, 21),
// (4,28): error CS1061: 'CustomHandler' does not contain a definition for 'AppendFormatted' and no accessible extension method 'AppendFormatted' accepting a first argument of type 'CustomHandler' could be found (are you missing a using directive or an assembly reference?)
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "{1}").WithArguments("CustomHandler", "AppendFormatted").WithLocation(4, 28),
// (4,28): error CS8941: Interpolated string handler method '?.()' is malformed. It does not return 'void' or 'bool'.
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("?.()").WithLocation(4, 28)
);
}
[Fact]
public void MissingBoolType()
{
var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var handlerRef = CreateCompilation(handlerSource).EmitToImageReference();
var source = @"CustomHandler c = $""Literal{1}"";";
var comp = CreateCompilation(source, references: new[] { handlerRef });
comp.MakeTypeMissing(SpecialType.System_Boolean);
comp.VerifyDiagnostics(
// (1,19): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// CustomHandler c = $"Literal{1}";
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""Literal{1}""").WithArguments("System.Boolean").WithLocation(1, 19)
);
}
[Fact]
public void MissingVoidType()
{
var handlerSource = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false);
var handlerRef = CreateCompilation(handlerSource).EmitToImageReference();
var source = @"
class C
{
public bool M()
{
CustomHandler c = $""Literal{1}"";
return true;
}
}
";
var comp = CreateCompilation(source, references: new[] { handlerRef });
comp.MakeTypeMissing(SpecialType.System_Void);
comp.VerifyEmitDiagnostics();
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_01(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 14 + expression2.Length)
);
}
[Theory]
[InlineData(@"$""Text{1}""", @"$""{1}Text""")]
[InlineData(@"$""Text"" + $""{1}""", @"$""{1}"" + $""Text""")]
public void MixedBuilderReturnTypes_02(string expression1, string expression2)
{
var source = @"
using System;
Console.WriteLine(" + expression1 + @");
Console.WriteLine(" + expression2 + @");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public void AppendLiteral(string s) { }
public bool AppendFormatted(object o) => true;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'.
// Console.WriteLine($"Text{1}");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 15 + expression1.Length),
// (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'.
// Console.WriteLine($"{1}Text");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 14 + expression2.Length)
);
}
[Fact]
public void MixedBuilderReturnTypes_03()
{
var source = @"
using System;
Console.WriteLine($""{1}"");
namespace System.Runtime.CompilerServices
{
using System.Text;
public ref struct DefaultInterpolatedStringHandler
{
private readonly StringBuilder _builder;
public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public string ToStringAndClear() => _builder.ToString();
public bool AppendLiteral(string s) => true;
public void AppendFormatted(object o)
{
_builder.AppendLine(""value:"" + o.ToString());
}
}
}";
CompileAndVerify(source, expectedOutput: "value:1");
}
[Fact]
public void MixedBuilderReturnTypes_04()
{
var source = @"
using System;
using System.Text;
using System.Runtime.CompilerServices;
Console.WriteLine((CustomHandler)$""l"");
[InterpolatedStringHandler]
public class CustomHandler
{
private readonly StringBuilder _builder;
public CustomHandler(int literalLength, int formattedCount)
{
_builder = new StringBuilder();
}
public override string ToString() => _builder.ToString();
public bool AppendFormatted(object o) => true;
public void AppendLiteral(string s)
{
_builder.AppendLine(""literal:"" + s.ToString());
}
}
";
CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l");
}
private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler")
{
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var descendentNodes = tree.GetRoot().DescendantNodes();
var interpolatedString =
(ExpressionSyntax)descendentNodes.OfType<BinaryExpressionSyntax>()
.Where(b => b.DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Any())
.FirstOrDefault()
?? descendentNodes.OfType<InterpolatedStringExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(interpolatedString);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString());
Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind);
Assert.True(semanticInfo.ImplicitConversion.Exists);
Assert.True(semanticInfo.ImplicitConversion.IsValid);
Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler);
Assert.Null(semanticInfo.ImplicitConversion.Method);
if (interpolatedString is BinaryExpressionSyntax)
{
Assert.False(semanticInfo.ConstantValue.HasValue);
AssertEx.Equal("System.String System.String.op_Addition(System.String left, System.String right)", semanticInfo.Symbol.ToTestDisplayString());
}
// https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings.
}
private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput)
=> CompileAndVerify(
compilation,
expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null,
verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped);
[Theory]
[CombinatorialData]
public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns,
[CombinatorialValues(@"$""Literal{1,2:f}""", @"$""Literal"" + $""{1,2:f}""")] string expression)
{
var code = @"
CustomHandler builder = " + expression + @";
System.Console.WriteLine(builder.ToString());";
var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns);
var comp = CreateCompilation(new[] { code, builder });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:Literal
value:1
alignment:2
format:f");
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (type, useBoolReturns) switch
{
(type: "struct", useBoolReturns: true) => @"
{
// Code size 67 (0x43)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""bool CustomHandler.AppendLiteral(string)""
IL_0015: brfalse.s IL_002c
IL_0017: ldloca.s V_1
IL_0019: ldc.i4.1
IL_001a: box ""int""
IL_001f: ldc.i4.2
IL_0020: ldstr ""f""
IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_002a: br.s IL_002d
IL_002c: ldc.i4.0
IL_002d: pop
IL_002e: ldloc.1
IL_002f: stloc.0
IL_0030: ldloca.s V_0
IL_0032: constrained. ""CustomHandler""
IL_0038: callvirt ""string object.ToString()""
IL_003d: call ""void System.Console.WriteLine(string)""
IL_0042: ret
}
",
(type: "struct", useBoolReturns: false) => @"
{
// Code size 61 (0x3d)
.maxstack 4
.locals init (CustomHandler V_0, //builder
CustomHandler V_1)
IL_0000: ldloca.s V_1
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_1
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(string)""
IL_0015: ldloca.s V_1
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: ldc.i4.2
IL_001e: ldstr ""f""
IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0028: ldloc.1
IL_0029: stloc.0
IL_002a: ldloca.s V_0
IL_002c: constrained. ""CustomHandler""
IL_0032: callvirt ""string object.ToString()""
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ret
}
",
(type: "class", useBoolReturns: true) => @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""Literal""
IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0013: brfalse.s IL_0029
IL_0015: ldloc.0
IL_0016: ldc.i4.1
IL_0017: box ""int""
IL_001c: ldc.i4.2
IL_001d: ldstr ""f""
IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: callvirt ""string object.ToString()""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ret
}
",
(type: "class", useBoolReturns: false) => @"
{
// Code size 47 (0x2f)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldstr ""Literal""
IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0012: dup
IL_0013: ldc.i4.1
IL_0014: box ""int""
IL_0019: ldc.i4.2
IL_001a: ldstr ""f""
IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0024: callvirt ""string object.ToString()""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ret
}
",
_ => throw ExceptionUtilities.Unreachable
};
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void CustomHandlerMethodArgument(string expression)
{
var code = @"
M(" + expression + @");
void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"($""{1,2:f}"" + $""Literal"")")]
public void ExplicitHandlerCast_InCode(string expression)
{
var code = @"System.Console.WriteLine((CustomHandler)" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) });
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single();
var semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString());
Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind);
syntax = ((CastExpressionSyntax)syntax).Expression;
Assert.Equal(expression, syntax.ToString());
semanticInfo = model.GetSemanticInfoSummary(syntax);
Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType);
Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind);
// https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 5
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: call ""void System.Console.WriteLine(object)""
IL_0029: ret
}
");
}
[Theory, WorkItem(55345, "https://github.com/dotnet/roslyn/issues/55345")]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void HandlerConversionPreferredOverStringForNonConstant(string expression)
{
var code = @"
CultureInfoNormalizer.Normalize();
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
System.Console.WriteLine(b.ToString());
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.7
IL_0006: ldc.i4.1
IL_0007: newobj ""CustomHandler..ctor(int, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.1
IL_000f: box ""int""
IL_0014: ldc.i4.2
IL_0015: ldstr ""f""
IL_001a: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001f: brfalse.s IL_002e
IL_0021: ldloc.0
IL_0022: ldstr ""Literal""
IL_0027: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_002c: br.s IL_002f
IL_002e: ldc.i4.0
IL_002f: pop
IL_0030: ldloc.0
IL_0031: call ""void C.M(CustomHandler)""
IL_0036: ret
}
");
comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular9);
verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", expression.Contains('+') ? @"
{
// Code size 37 (0x25)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: ldstr ""Literal""
IL_001a: call ""string string.Concat(string, string)""
IL_001f: call ""void C.M(string)""
IL_0024: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldstr ""{0,2:f}Literal""
IL_000a: ldc.i4.1
IL_000b: box ""int""
IL_0010: call ""string string.Format(string, object)""
IL_0015: call ""void C.M(string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler b)
{
throw null;
}
public static void M(string s)
{
System.Console.WriteLine(s);
}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"Literal");
verifier.VerifyIL(@"<top-level-statements-entry-point>", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""Literal""
IL_0005: call ""void C.M(string)""
IL_000a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}{2}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type
// [Attr($"{1}{2}")]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2)
);
VerifyInterpolatedStringExpression(comp);
var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
[Theory]
[InlineData(@"$""{""Literal""}""")]
[InlineData(@"$""{""Lit""}"" + $""{""eral""}""")]
public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor(string expression)
{
var code = @"
using System;
[Attr(" + expression + @")]
class Attr : Attribute
{
public Attr(string s) {}
public Attr(CustomHandler c) {}
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate);
void validate(ModuleSymbol m)
{
var attr = m.GlobalNamespace.GetTypeMember("Attr");
Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString());
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => throw null;
public static void M(CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
comp.VerifyDiagnostics(
// (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)'
// C.M($"");
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_01(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_02(string expression)
{
var code = @"
using System;
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
public static void M(CustomHandler c) => Console.WriteLine(c);
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 50 (0x32)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: call ""void C.M(CustomHandler)""
IL_0031: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericOverloadResolution_03(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M<T>(T t) where T : CustomHandler => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'.
// C.M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_01(string expression)
{
var code = @"
C.M(" + expression + @", default(CustomHandler));
C.M(default(CustomHandler), " + expression + @");
class C
{
public static void M<T>(T t1, T t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M($"{1,2:f}Literal", default(CustomHandler));
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3),
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_02(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
comp.VerifyDiagnostics(
// (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// C.M(default(CustomHandler), () => $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_03(string expression)
{
var code = @"
using System;
C.M(" + expression + @", default(CustomHandler));
class C
{
public static void M<T>(T t1, T t2) => Console.WriteLine(t1);
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ldnull
IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)""
IL_0032: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void GenericInference_04(string expression)
{
var code = @"
using System;
C.M(default(CustomHandler), () => " + expression + @");
class C
{
public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2());
}
partial class CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_01(string expression)
{
var code = @"
using System;
Func<CustomHandler> f = () => " + expression + @";
Console.WriteLine(f());
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldc.i4.1
IL_000a: box ""int""
IL_000f: ldc.i4.2
IL_0010: ldstr ""f""
IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_001a: brfalse.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""Literal""
IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.0
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_02(string expression)
{
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(() => " + expression + @");
class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
";
// Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string,
// so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec).
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) });
var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal");
// No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", !expression.Contains('+') ? @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldstr ""{0,2:f}Literal""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ret
}
"
: @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldstr ""{0,2:f}""
IL_0005: ldc.i4.1
IL_0006: box ""int""
IL_000b: call ""string string.Format(string, object)""
IL_0010: ldstr ""Literal""
IL_0015: call ""string string.Concat(string, string)""
IL_001a: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_03(string expression)
{
// Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct
// when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to
// fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>.
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => throw null;
public static void M(Func<CustomHandler> f) => Console.WriteLine(f());
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
public ref struct S
{
public string Field { get; set; }
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 35 (0x23)
.maxstack 4
.locals init (S V_0)
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldloca.s V_0
IL_000a: initobj ""S""
IL_0010: ldloca.s V_0
IL_0012: ldstr ""Field""
IL_0017: call ""void S.Field.set""
IL_001c: ldloc.0
IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)""
IL_0022: ret
}
");
}
[Theory]
[InlineData(@"$""{new S { Field = ""Field"" }}""")]
[InlineData(@"$""{new S { Field = ""Field"" }}"" + $""""")]
public void LambdaReturnInference_04(string expression)
{
// Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type)
var code = @"
using System;
C.M(() => " + expression + @");
static class C
{
public static void M(Func<string> f) => Console.WriteLine(f());
public static void M(Func<CustomHandler> f) => throw null;
}
public partial class CustomHandler
{
public void AppendFormatted(S value) => throw null;
}
public ref struct S
{
public string Field { get; set; }
}
namespace System.Runtime.CompilerServices
{
public ref partial struct DefaultInterpolatedStringHandler
{
public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field);
}
}
";
string[] source = new[] {
code,
GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false),
GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, expression).WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11),
// (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater.
// C.M(() => $"{new S { Field = "Field" }}");
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0()", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0,
S V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldloca.s V_1
IL_000d: initobj ""S""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""Field""
IL_001a: call ""void S.Field.set""
IL_001f: ldloc.1
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)""
IL_0025: ldloca.s V_0
IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_05(string expression)
{
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => throw null;
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_06(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion
// means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec)
// and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type
// has an identity conversion to the return type of Func<bool, string>, that is preferred.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", !expression.Contains('+') ? @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ret
}
"
: @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0012
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0011: ret
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_07(string expression)
{
// Same as 5, but with an implicit conversion from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false));
}
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL(@"Program.<>c.<<Main>$>b__0_0(bool)", @"
{
// Code size 55 (0x37)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000d
IL_0003: ldloca.s V_0
IL_0005: initobj ""CustomHandler""
IL_000b: ldloc.0
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void LambdaReturnInference_08(string expression)
{
// Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type.
var code = @"
using System;
C.M(b =>
{
if (b) return default(CustomHandler);
else return " + expression + @";
});
static class C
{
public static void M(Func<bool, string> f) => Console.WriteLine(f(false));
public static void M(Func<bool, CustomHandler> f) => throw null;
}
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)'
// C.M(b =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""{2}""")]
public void LambdaInference_AmbiguousInOlderLangVersions(string expression)
{
var code = @"
using System;
C.M(param =>
{
param = " + expression + @";
});
static class C
{
public static void M(Action<string> f) => throw null;
public static void M(Action<CustomHandler> f) => throw null;
}
";
var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) };
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
// This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04
// We should not be changing binding behavior based on LangVersion.
comp.VerifyEmitDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)'
// C.M(param =>
Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_01(string expression)
{
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_0024
IL_0012: ldstr ""{0,2:f}Literal""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: br.s IL_0032
IL_0024: ldloca.s V_0
IL_0026: initobj ""CustomHandler""
IL_002c: ldloc.0
IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
"
: @"
{
// Code size 66 (0x42)
.maxstack 2
.locals init (CustomHandler V_0)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brtrue.s IL_002e
IL_0012: ldstr ""{0,2:f}""
IL_0017: ldc.i4.1
IL_0018: box ""int""
IL_001d: call ""string string.Format(string, object)""
IL_0022: ldstr ""Literal""
IL_0027: call ""string string.Concat(string, string)""
IL_002c: br.s IL_003c
IL_002e: ldloca.s V_0
IL_0030: initobj ""CustomHandler""
IL_0036: ldloc.0
IL_0037: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_03(string expression)
{
// Same as 02, but with a target-type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("string", "CustomHandler").WithLocation(4, 19)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_04(string expression)
{
// Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: box ""CustomHandler""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_05(string expression)
{
// Same 01, but with a conversion from string to CustomHandler and CustomHandler to string.
var code = @"
using System;
var x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another
// var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal";
Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : " + expression).WithArguments("CustomHandler", "string").WithLocation(4, 9)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void TernaryTypes_06(string expression)
{
// Same 05, but with a target type
var code = @"
using System;
CustomHandler x = (bool)(object)false ? default(CustomHandler) : " + expression + @";
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brtrue.s IL_0038
IL_000d: ldloca.s V_0
IL_000f: ldc.i4.7
IL_0010: ldc.i4.1
IL_0011: call ""CustomHandler..ctor(int, int)""
IL_0016: ldloca.s V_0
IL_0018: ldc.i4.1
IL_0019: box ""int""
IL_001e: ldc.i4.2
IL_001f: ldstr ""f""
IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0029: ldloca.s V_0
IL_002b: ldstr ""Literal""
IL_0030: call ""void CustomHandler.AppendLiteral(string)""
IL_0035: ldloc.0
IL_0036: br.s IL_0041
IL_0038: ldloca.s V_0
IL_003a: initobj ""CustomHandler""
IL_0040: ldloc.0
IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0046: call ""void System.Console.WriteLine(string)""
IL_004b: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_01(string expression)
{
// Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types
// and not on expression conversions, no best type can be found for this switch expression.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_02(string expression)
{
// Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string.
var code = @"
using System;
CultureInfoNormalizer.Normalize();
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", !expression.Contains('+') ? @"
{
// Code size 59 (0x3b)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_0034
IL_0023: ldstr ""{0,2:f}Literal""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: stloc.0
IL_0034: ldloc.0
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
"
: @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (string V_0,
CustomHandler V_1)
IL_0000: call ""void CultureInfoNormalizer.Normalize()""
IL_0005: ldc.i4.0
IL_0006: box ""bool""
IL_000b: unbox.any ""bool""
IL_0010: brfalse.s IL_0023
IL_0012: ldloca.s V_1
IL_0014: initobj ""CustomHandler""
IL_001a: ldloc.1
IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0020: stloc.0
IL_0021: br.s IL_003e
IL_0023: ldstr ""{0,2:f}""
IL_0028: ldc.i4.1
IL_0029: box ""int""
IL_002e: call ""string string.Format(string, object)""
IL_0033: ldstr ""Literal""
IL_0038: call ""string string.Concat(string, string)""
IL_003d: stloc.0
IL_003e: ldloc.0
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_03(string expression)
{
// Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile).
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_04(string expression)
{
// Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: box ""CustomHandler""
IL_0049: call ""void System.Console.WriteLine(object)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_05(string expression)
{
// Same as 01, but with conversions in both directions. No best common type can be found.
var code = @"
using System;
var x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (4,29): error CS8506: No best type was found for the switch expression.
// var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" };
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void SwitchTypes_06(string expression)
{
// Same as 05, but with a target type.
var code = @"
using System;
CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => " + expression + @" };
Console.WriteLine(x);
public partial struct CustomHandler
{
public static implicit operator CustomHandler(string c) => throw null;
public static implicit operator string(CustomHandler c) => c.ToString();
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (CustomHandler V_0,
CustomHandler V_1)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: unbox.any ""bool""
IL_000b: brfalse.s IL_0019
IL_000d: ldloca.s V_1
IL_000f: initobj ""CustomHandler""
IL_0015: ldloc.1
IL_0016: stloc.0
IL_0017: br.s IL_0043
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.7
IL_001c: ldc.i4.1
IL_001d: call ""CustomHandler..ctor(int, int)""
IL_0022: ldloca.s V_1
IL_0024: ldc.i4.1
IL_0025: box ""int""
IL_002a: ldc.i4.2
IL_002b: ldstr ""f""
IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: ldloca.s V_1
IL_0037: ldstr ""Literal""
IL_003c: call ""void CustomHandler.AppendLiteral(string)""
IL_0041: ldloc.1
IL_0042: stloc.0
IL_0043: ldloc.0
IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)""
IL_0049: call ""void System.Console.WriteLine(string)""
IL_004e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_01(string expression)
{
var code = @"
M(" + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void Program.<<Main>$>g__M|0_0(ref CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_02(string expression)
{
var code = @"
M(" + expression + @");
M(ref " + expression + @");
void M(ref CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword
// M($"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("1", "ref").WithLocation(2, 3),
// (3,7): error CS1510: A ref or out value must be an assignable variable
// M(ref $"{1,2:f}Literal");
Diagnostic(ErrorCode.ERR_RefLvalueExpected, expression).WithLocation(3, 7)
);
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_03(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 45 (0x2d)
.maxstack 5
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.1
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: dup
IL_0008: ldc.i4.1
IL_0009: box ""int""
IL_000e: ldc.i4.2
IL_000f: ldstr ""f""
IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0019: dup
IL_001a: ldstr ""Literal""
IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0024: stloc.0
IL_0025: ldloca.s V_0
IL_0027: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002c: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void PassAsRefWithoutKeyword_04(string expression)
{
var code = @"
M(" + expression + @");
void M(in CustomHandler c) => System.Console.WriteLine(c);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_0
IL_002a: call ""void Program.<<Main>$>g__M|0_0(in CustomHandler)""
IL_002f: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => throw null;
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind, [CombinatorialValues(@"$""{1,2:f}Literal""", @"$""{1,2:f}"" + $""Literal""")] string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler c) => System.Console.WriteLine(c);
public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c);
}";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp);
VerifyInterpolatedStringExpression(comp);
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler)""
IL_002e: ret
}
");
}
[Theory]
[InlineData(@"$""{1,2:f}Literal""")]
[InlineData(@"$""{1,2:f}"" + $""Literal""")]
public void RefOverloadResolution_MultipleBuilderTypes(string expression)
{
var code = @"
C.M(" + expression + @");
class C
{
public static void M(CustomHandler1 c) => System.Console.WriteLine(c);
public static void M(ref CustomHandler2 c) => throw null;
}";
var comp = CreateCompilation(new[]
{
code,
GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false),
GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false)
});
VerifyInterpolatedStringExpression(comp, "CustomHandler1");
var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"
value:1
alignment:2
format:f
literal:Literal");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 47 (0x2f)
.maxstack 4
.locals init (CustomHandler1 V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler1..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.2
IL_0012: ldstr ""f""
IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)""
IL_001c: ldloca.s V_0
IL_001e: ldstr ""Literal""
IL_0023: call ""void CustomHandler1.AppendLiteral(string)""
IL_0028: ldloc.0
IL_0029: call ""void C.M(CustomHandler1)""
IL_002e: ret
}
");
}
private const string InterpolatedStringHandlerAttributesVB = @"
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerAttribute
Inherits Attribute
End Class
<AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)>
Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute
Inherits Attribute
Public Sub New(argument As String)
Arguments = { argument }
End Sub
Public Sub New(ParamArray arguments() as String)
Me.Arguments = arguments
End Sub
Public ReadOnly Property Arguments As String()
End Class
End Namespace
";
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (8,27): error CS8946: 'string' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {}
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27)
);
var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String)
End Sub
End Class
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
// Note: there is no compilation error here because the natural type of a string is still string, and
// we just bind to that method without checking the handler attribute.
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(sParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string'
// public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70)
);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'.
// public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34),
// (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8),
// (8,34): error CS8943: null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.
// public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5),
// (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5),
// (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
_ = new C(" + expression + @");
class C
{
public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11),
// (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {}
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15)
);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"{""""}")]
[InlineData(@"""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg)
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// _ = new C($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11),
// (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// _ = new C($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C<CustomHandler>.M(" + expression + @");
public class C<T>
{
public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, expression).WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20),
// (8,27): error CS8946: 'T' is not an interpolated string handler type.
// public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { }
Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27)
);
var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C");
var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler");
var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler)));
var cParam = substitutedC.GetMethod("M").Parameters.Single();
Assert.IsType<SubstitutedParameterSymbol>(cParam);
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C(Of T)
Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics(
// (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20),
// (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C<CustomHandler>.M($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20)
);
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
Assert.True(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""text""", @"$""text"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var goodCode = @"
int i = 10;
C.M(i: i, c: " + expression + @");
";
var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"
i:10
literal:text
");
verifier.VerifyDiagnostics(
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
verifyIL(verifier);
var badCode = @"C.M(" + expression + @", 1);";
comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'.
// C.M($"", 1);
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 7 + expression.Length),
// (6,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller
// to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
void verifyIL(CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloca.s V_2
IL_0007: ldc.i4.4
IL_0008: ldc.i4.0
IL_0009: ldloc.0
IL_000a: call ""CustomHandler..ctor(int, int, int)""
IL_000f: ldloca.s V_2
IL_0011: ldstr ""text""
IL_0016: call ""bool CustomHandler.AppendLiteral(string)""
IL_001b: pop
IL_001c: ldloc.2
IL_001d: ldloc.1
IL_001e: call ""void C.M(CustomHandler, int)""
IL_0023: ret
}
"
: @"
{
// Code size 43 (0x2b)
.maxstack 4
.locals init (int V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldc.i4.4
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_3
IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000f: stloc.2
IL_0010: ldloc.3
IL_0011: brfalse.s IL_0021
IL_0013: ldloca.s V_2
IL_0015: ldstr ""text""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: br.s IL_0022
IL_0021: ldc.i4.0
IL_0022: pop
IL_0023: ldloc.2
IL_0024: ldloc.1
IL_0025: call ""void C.M(CustomHandler, int)""
IL_002a: ret
}
");
}
}
[Fact]
public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Class C
Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() });
comp.VerifyEmitDiagnostics();
var customHandler = comp.GetTypeByMetadataName("CustomHandler");
Assert.True(customHandler.IsInterpolatedStringHandlerType);
var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C.M(" + expression + @");
public class C
{
public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount)
{
}
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler });
comp.VerifyDiagnostics(
// (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'.
// C.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, expression).WithArguments("i", "c").WithLocation(4, 5),
// (8,27): warning CS8947: Parameter i occurs after CustomHandler in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.
// public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { }
Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, " + expression + @");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
Assert.False(cParam.HasInterpolatedStringHandlerArgumentError);
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
private CustomHandler(int literalLength, int formattedCount, int i) : this() {}
static void InCustomHandler()
{
C.M(1, " + expression + @");
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() });
comp.VerifyDiagnostics(
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "4").WithLocation(1, 8),
// (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, expression).WithArguments("CustomHandler", "3").WithLocation(1, 8)
);
comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() });
comp.VerifyDiagnostics(
// (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadAccess, expression).WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8)
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, string expression, params DiagnosticDescription[] expectedDiagnostics)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 0;
C.M(" + mRef + @" i, " + expression + @");
public class C
{
public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// C.M(ref i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", expression,
// (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", expression,
// (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(in i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", expression,
// (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", expression,
// (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M(out i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6));
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut(string expression)
{
InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", expression,
// (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword
// C.M( i, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6));
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MismatchedType([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this()
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"C.M(1, " + expression + @");";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var expectedDiagnostics = extraConstructorArg == ""
? new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5)
}
: new DiagnosticDescription[]
{
// (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5),
// (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)'
// C.M(1, $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8)
};
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(expectedDiagnostics);
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
comp = CreateCompilation(executableCode, new[] { d });
comp.VerifyDiagnostics(expectedDiagnostics);
}
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_SingleArg([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""2""", @"$""2"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString();
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
using System;
int i = 10;
Console.WriteLine(C.M(i, " + expression + @"));
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @"
i:10
literal:2");
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single());
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == ""
? @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.1
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""CustomHandler..ctor(int, int, int)""
IL_000e: ldloca.s V_1
IL_0010: ldstr ""2""
IL_0015: call ""bool CustomHandler.AppendLiteral(string)""
IL_001a: pop
IL_001b: ldloc.1
IL_001c: call ""string C.M(int, CustomHandler)""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ret
}
"
: @"
{
// Code size 46 (0x2e)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: ldc.i4.0
IL_0006: ldloc.0
IL_0007: ldloca.s V_2
IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000e: stloc.1
IL_000f: ldloc.2
IL_0010: brfalse.s IL_0020
IL_0012: ldloca.s V_1
IL_0014: ldstr ""2""
IL_0019: call ""bool CustomHandler.AppendLiteral(string)""
IL_001e: br.s IL_0021
IL_0020: ldc.i4.0
IL_0021: pop
IL_0022: ldloc.1
IL_0023: call ""string C.M(int, CustomHandler)""
IL_0028: call ""void System.Console.WriteLine(string)""
IL_002d: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var executableCode = @"
int i = 10;
string s = ""arg"";
C.M(i, s, " + expression + @");
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler });
string expectedOutput = @"
i:10
s:arg
literal:literal
";
var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() })
{
verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput);
verifier.VerifyDiagnostics();
verifyIL(extraConstructorArg, verifier);
}
static void validator(ModuleSymbol verifier)
{
var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
static void verifyIL(string extraConstructorArg, CompilationVerifier verifier)
{
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 44 (0x2c)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldloca.s V_3
IL_000f: ldc.i4.7
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloc.2
IL_0013: call ""CustomHandler..ctor(int, int, int, string)""
IL_0018: ldloca.s V_3
IL_001a: ldstr ""literal""
IL_001f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0024: pop
IL_0025: ldloc.3
IL_0026: call ""void C.M(int, string, CustomHandler)""
IL_002b: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0, //s
int V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.s 10
IL_0002: ldstr ""arg""
IL_0007: stloc.0
IL_0008: stloc.1
IL_0009: ldloc.1
IL_000a: ldloc.0
IL_000b: stloc.2
IL_000c: ldloc.2
IL_000d: ldc.i4.7
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: ldloc.2
IL_0011: ldloca.s V_4
IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_0018: stloc.3
IL_0019: ldloc.s V_4
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_3
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.3
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
string s = null;
object o;
C.M(i, ref s, out o, " + expression + @");
Console.WriteLine(s);
Console.WriteLine(o);
public class C
{
public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c)
{
Console.WriteLine(s);
o = ""o in M"";
s = ""s in M"";
Console.Write(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
o = null;
s = ""s in constructor"";
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
s in constructor
i:1
literal:literal
s in M
o in M
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 67 (0x43)
.maxstack 8
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)""
IL_0020: stloc.s V_6
IL_0022: ldloca.s V_6
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: pop
IL_002f: ldloc.s V_6
IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_0036: ldloc.1
IL_0037: call ""void System.Console.WriteLine(string)""
IL_003c: ldloc.2
IL_003d: call ""void System.Console.WriteLine(object)""
IL_0042: ret
}
"
: @"
{
// Code size 76 (0x4c)
.maxstack 9
.locals init (int V_0, //i
string V_1, //s
object V_2, //o
int& V_3,
string& V_4,
object& V_5,
CustomHandler V_6,
bool V_7)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: ldloca.s V_1
IL_000a: stloc.s V_4
IL_000c: ldloc.s V_4
IL_000e: ldloca.s V_2
IL_0010: stloc.s V_5
IL_0012: ldloc.s V_5
IL_0014: ldc.i4.7
IL_0015: ldc.i4.0
IL_0016: ldloc.3
IL_0017: ldloc.s V_4
IL_0019: ldloc.s V_5
IL_001b: ldloca.s V_7
IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)""
IL_0022: stloc.s V_6
IL_0024: ldloc.s V_7
IL_0026: brfalse.s IL_0036
IL_0028: ldloca.s V_6
IL_002a: ldstr ""literal""
IL_002f: call ""bool CustomHandler.AppendLiteral(string)""
IL_0034: br.s IL_0037
IL_0036: ldc.i4.0
IL_0037: pop
IL_0038: ldloc.s V_6
IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)""
IL_003f: ldloc.1
IL_0040: call ""void System.Console.WriteLine(string)""
IL_0045: ldloc.2
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), GetString(), " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
GetString
s:str
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 45 (0x2d)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldloca.s V_2
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: call ""CustomHandler..ctor(int, int, string, int)""
IL_0019: ldloca.s V_2
IL_001b: ldstr ""literal""
IL_0020: call ""bool CustomHandler.AppendLiteral(string)""
IL_0025: pop
IL_0026: ldloc.2
IL_0027: call ""void C.M(int, string, CustomHandler)""
IL_002c: ret
}
"
: @"
{
// Code size 52 (0x34)
.maxstack 7
.locals init (string V_0,
int V_1,
CustomHandler V_2,
bool V_3)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_1()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_3
IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)""
IL_0019: stloc.2
IL_001a: ldloc.3
IL_001b: brfalse.s IL_002b
IL_001d: ldloca.s V_2
IL_001f: ldstr ""literal""
IL_0024: call ""bool CustomHandler.AppendLiteral(string)""
IL_0029: br.s IL_002c
IL_002b: ldc.i4.0
IL_002c: pop
IL_002d: ldloc.2
IL_002e: call ""void C.M(int, string, CustomHandler)""
IL_0033: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetC().M(s: GetString(), i: GetInt(), c: " + expression + @");
C GetC()
{
Console.WriteLine(""GetC"");
return new C { Field = 5 };
}
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
string GetString()
{
Console.WriteLine(""GetString"");
return ""str"";
}
public class C
{
public int Field;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""s:"" + s);
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
_builder.AppendLine(""i:"" + i.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetC
GetString
GetInt
s:str
c.Field:5
i:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 56 (0x38)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4)
IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldloca.s V_4
IL_0019: ldc.i4.7
IL_001a: ldc.i4.0
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: ldloc.2
IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)""
IL_0023: ldloca.s V_4
IL_0025: ldstr ""literal""
IL_002a: call ""bool CustomHandler.AppendLiteral(string)""
IL_002f: pop
IL_0030: ldloc.s V_4
IL_0032: callvirt ""void C.M(int, string, CustomHandler)""
IL_0037: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 9
.locals init (string V_0,
C V_1,
int V_2,
string V_3,
CustomHandler V_4,
bool V_5)
IL_0000: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: call ""string Program.<<Main>$>g__GetString|0_2()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: stloc.3
IL_000f: call ""int Program.<<Main>$>g__GetInt|0_1()""
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldloc.3
IL_0017: ldc.i4.7
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: ldloca.s V_5
IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)""
IL_0023: stloc.s V_4
IL_0025: ldloc.s V_5
IL_0027: brfalse.s IL_0037
IL_0029: ldloca.s V_4
IL_002b: ldstr ""literal""
IL_0030: call ""bool CustomHandler.AppendLiteral(string)""
IL_0035: br.s IL_0038
IL_0037: ldc.i4.0
IL_0038: pop
IL_0039: ldloc.s V_4
IL_003b: callvirt ""void C.M(int, string, CustomHandler)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_Duplicated([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(GetInt(), """", " + expression + @");
int GetInt()
{
Console.WriteLine(""GetInt"");
return 10;
}
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""i2:"" + i2.ToString());
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
GetInt
i1:10
i2:10
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 43 (0x2b)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldloca.s V_1
IL_000e: ldc.i4.7
IL_000f: ldc.i4.0
IL_0010: ldloc.0
IL_0011: ldloc.0
IL_0012: call ""CustomHandler..ctor(int, int, int, int)""
IL_0017: ldloca.s V_1
IL_0019: ldstr ""literal""
IL_001e: call ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: ldloc.1
IL_0025: call ""void C.M(int, string, CustomHandler)""
IL_002a: ret
}
"
: @"
{
// Code size 50 (0x32)
.maxstack 7
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: call ""int Program.<<Main>$>g__GetInt|0_0()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr """"
IL_000c: ldc.i4.7
IL_000d: ldc.i4.0
IL_000e: ldloc.0
IL_000f: ldloc.0
IL_0010: ldloca.s V_2
IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)""
IL_0017: stloc.1
IL_0018: ldloc.2
IL_0019: brfalse.s IL_0029
IL_001b: ldloca.s V_1
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: br.s IL_002a
IL_0029: ldc.i4.0
IL_002a: pop
IL_002b: ldloc.1
IL_002c: call ""void C.M(int, string, CustomHandler)""
IL_0031: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, """", " + expression + @");
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 19 (0x13)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: newobj ""CustomHandler..ctor(int, int)""
IL_000d: call ""void C.M(int, string, CustomHandler)""
IL_0012: ret
}
"
: @"
{
// Code size 21 (0x15)
.maxstack 5
.locals init (bool V_0)
IL_0000: ldc.i4.1
IL_0001: ldstr """"
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldloca.s V_0
IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)""
IL_000f: call ""void C.M(int, string, CustomHandler)""
IL_0014: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
public class C
{
public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { }
}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @")
{
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute });
// https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback.
CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics();
CreateCompilation(@"C.M(1, """", " + expression + @");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics(
(extraConstructorArg == "")
? new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12),
// (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "out").WithLocation(1, 12)
}
: new[]
{
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12),
// (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)'
// C.M(1, "", $"");
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, expression).WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12)
}
);
static void validate(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
Console.WriteLine(c[10, ""str"", " + expression + @"]);
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: callvirt ""string C.this[int, string, CustomHandler].get""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""string C.this[int, string, CustomHandler].get""
IL_0035: call ""void System.Console.WriteLine(string)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue([CombinatorialValues("", ", out bool success")] string extraConstructorArg,
[CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var c = new C();
c[10, ""str"", " + expression + @"] = """";
public class C
{
public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 52 (0x34)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldloca.s V_2
IL_0012: ldc.i4.7
IL_0013: ldc.i4.0
IL_0014: ldloc.0
IL_0015: ldloc.1
IL_0016: call ""CustomHandler..ctor(int, int, int, string)""
IL_001b: ldloca.s V_2
IL_001d: ldstr ""literal""
IL_0022: call ""bool CustomHandler.AppendLiteral(string)""
IL_0027: pop
IL_0028: ldloc.2
IL_0029: ldstr """"
IL_002e: callvirt ""void C.this[int, string, CustomHandler].set""
IL_0033: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (int V_0,
string V_1,
CustomHandler V_2,
bool V_3)
IL_0000: newobj ""C..ctor()""
IL_0005: ldc.i4.s 10
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldstr ""str""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldc.i4.7
IL_0011: ldc.i4.0
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: ldstr """"
IL_0035: callvirt ""void C.this[int, string, CustomHandler].set""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_ThisParameter([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
(new C(5)).M((int)10, ""str"", " + expression + @");
public class C
{
public int Prop { get; }
public C(int i) => Prop = i;
public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i1:"" + i1.ToString());
_builder.AppendLine(""c.Prop:"" + c.Prop.ToString());
_builder.AppendLine(""s:"" + s);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
i1:10
c.Prop:5
s:str
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 51 (0x33)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldloca.s V_3
IL_0015: ldc.i4.7
IL_0016: ldc.i4.0
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: ldloc.2
IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)""
IL_001f: ldloca.s V_3
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: pop
IL_002c: ldloc.3
IL_002d: callvirt ""void C.M(int, string, CustomHandler)""
IL_0032: ret
}
"
: @"
{
// Code size 59 (0x3b)
.maxstack 9
.locals init (int V_0,
C V_1,
string V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.5
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.s 10
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldstr ""str""
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: ldc.i4.7
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldloc.2
IL_0018: ldloca.s V_4
IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)""
IL_001f: stloc.3
IL_0020: ldloc.s V_4
IL_0022: brfalse.s IL_0032
IL_0024: ldloca.s V_3
IL_0026: ldstr ""literal""
IL_002b: call ""bool CustomHandler.AppendLiteral(string)""
IL_0030: br.s IL_0033
IL_0032: ldc.i4.0
IL_0033: pop
IL_0034: ldloc.3
IL_0035: callvirt ""void C.M(int, string, CustomHandler)""
IL_003a: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentAttribute_OnConstructor(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
_ = new C(5, " + expression + @");
public class C
{
public int Prop { get; }
public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
i:5
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 34 (0x22)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.5
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldloca.s V_1
IL_0005: ldc.i4.7
IL_0006: ldc.i4.0
IL_0007: ldloc.0
IL_0008: call ""CustomHandler..ctor(int, int, int)""
IL_000d: ldloca.s V_1
IL_000f: ldstr ""literal""
IL_0014: call ""bool CustomHandler.AppendLiteral(string)""
IL_0019: pop
IL_001a: ldloc.1
IL_001b: newobj ""C..ctor(int, CustomHandler)""
IL_0020: pop
IL_0021: ret
}
");
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public class C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: callvirt ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: ldind.ref
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: callvirt ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_Success_StructReceiver([CombinatorialValues("", ", out bool success")] string extraConstructorArg, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
Console.WriteLine(c.I);
ref C GetC(ref C c)
{
Console.WriteLine(""GetC"");
return ref c;
}
public struct C
{
public int I;
public C(int i)
{
I = i;
}
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount)
{
c = new C(2);
" + (extraConstructorArg != "" ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @"
GetC
literal:literal
2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "")
? @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)""
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: ldstr ""literal""
IL_0021: call ""bool CustomHandler.AppendLiteral(string)""
IL_0026: pop
IL_0027: ldloc.2
IL_0028: call ""void C.M(CustomHandler)""
IL_002d: ldloc.0
IL_002e: ldfld ""int C.I""
IL_0033: call ""void System.Console.WriteLine(int)""
IL_0038: ret
}
"
: @"
{
// Code size 65 (0x41)
.maxstack 5
.locals init (C V_0, //c
C& V_1,
CustomHandler V_2,
bool V_3)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""C..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref C Program.<<Main>$>g__GetC|0_0(ref C)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.0
IL_0013: ldloc.1
IL_0014: ldloca.s V_3
IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)""
IL_001b: stloc.2
IL_001c: ldloc.3
IL_001d: brfalse.s IL_002d
IL_001f: ldloca.s V_2
IL_0021: ldstr ""literal""
IL_0026: call ""bool CustomHandler.AppendLiteral(string)""
IL_002b: br.s IL_002e
IL_002d: ldc.i4.0
IL_002e: pop
IL_002f: ldloc.2
IL_0030: call ""void C.M(CustomHandler)""
IL_0035: ldloc.0
IL_0036: ldfld ""int C.I""
IL_003b: call ""void System.Console.WriteLine(int)""
IL_0040: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_01([CombinatorialValues("ref readonly", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC().M(" + expression + @");
" + refness + @" C GetC() => throw null;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword
// GetC().M($"literal");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(5, 10)
);
}
[Theory]
[CombinatorialData]
public void RefReturningMethodAsReceiver_MismatchedRefness_02([CombinatorialValues("in", "")] string refness, [CombinatorialValues(@"$""literal""", @"$""literal"" + $""""")] string expression)
{
var code = @"
using System.Runtime.CompilerServices;
C c = new C(1);
GetC(ref c).M(" + expression + @");
ref C GetC(ref C c) => ref c;
public class C
{
public C(int i) { }
public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { }
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword
// GetC(ref c).M($"literal");
Diagnostic(ErrorCode.ERR_BadArgExtraRef, expression).WithArguments("3", "ref").WithLocation(5, 15)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Rvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(s2, " + expression + @");
public struct S
{
public int I;
public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
s1.I:1
s2.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 6
.locals init (S V_0, //s2
S V_1,
S V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: ldloca.s V_1
IL_0013: initobj ""S""
IL_0019: ldloca.s V_1
IL_001b: ldc.i4.2
IL_001c: stfld ""int S.I""
IL_0021: ldloc.1
IL_0022: stloc.0
IL_0023: stloc.1
IL_0024: ldloca.s V_1
IL_0026: ldloc.0
IL_0027: stloc.2
IL_0028: ldloc.2
IL_0029: ldc.i4.0
IL_002a: ldc.i4.0
IL_002b: ldloc.1
IL_002c: ldloc.2
IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)""
IL_0032: call ""void S.M(S, CustomHandler)""
IL_0037: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructReceiver_Lvalue(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s1 = new S { I = 1 };
S s2 = new S { I = 2 };
s1.M(ref s2, " + expression + @");
public struct S
{
public int I;
public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler)
{
Console.WriteLine(""s1.I:"" + this.I.ToString());
Console.WriteLine(""s2.I:"" + s2.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount)
{
s1.I = 3;
s2.I = 4;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
comp.VerifyDiagnostics(
// (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword
// s1.M(ref s2, $"");
Diagnostic(ErrorCode.ERR_BadArgRef, expression).WithArguments("3", "ref").WithLocation(8, 14)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByVal(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(s, " + expression + @");
public struct S
{
public int I;
public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 33 (0x21)
.maxstack 4
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.0
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: ldc.i4.0
IL_0014: ldc.i4.0
IL_0015: ldloc.0
IL_0016: newobj ""CustomHandler..ctor(int, int, S)""
IL_001b: call ""void S.M(S, CustomHandler)""
IL_0020: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void StructParameter_ByRef(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
S s = new S { I = 1 };
S.M(ref s, " + expression + @");
public struct S
{
public int I;
public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler)
{
Console.WriteLine(""s.I:"" + s.I.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount)
{
s.I = 2;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init (S V_0, //s
S V_1,
S& V_2)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.1
IL_000b: stfld ""int S.I""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: ldloca.s V_0
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldc.i4.0
IL_0017: ldc.i4.0
IL_0018: ldloc.2
IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)""
IL_001e: call ""void S.M(ref S, CustomHandler)""
IL_0023: ret
}
");
}
[Theory]
[CombinatorialData]
public void SideEffects(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal""", @"$"""" + $""literal""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
GetReceiver().M(
GetArg(""Unrelated parameter 1""),
GetArg(""Second value""),
GetArg(""Unrelated parameter 2""),
GetArg(""First value""),
" + expression + @",
GetArg(""Unrelated parameter 4""));
C GetReceiver()
{
Console.WriteLine(""GetReceiver"");
return new C() { Prop = ""Prop"" };
}
string GetArg(string s)
{
Console.WriteLine(s);
return s;
}
public class C
{
public string Prop { get; set; }
public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6)
=> Console.WriteLine(c.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @")
: this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""s1:"" + s1);
_builder.AppendLine(""c.Prop:"" + c.Prop);
_builder.AppendLine(""s2:"" + s2);
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns);
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @"
GetReceiver
Unrelated parameter 1
Second value
Unrelated parameter 2
First value
Handler constructor
Unrelated parameter 4
s1:First value
c.Prop:Prop
s2:Second value
literal:literal
");
verifier.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$""literal"" + $""""")]
public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType(string expression)
{
var code = @"
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
int i = 1;
C.M(i, " + expression + @");
public class C
{
public static implicit operator C(int i) => throw null;
public static implicit operator C(double d)
{
Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture));
return new C();
}
public override string ToString() => ""C"";
public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString());
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { }
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"
1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 39 (0x27)
.maxstack 5
.locals init (double V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: conv.r8
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldloca.s V_1
IL_0006: ldc.i4.7
IL_0007: ldc.i4.0
IL_0008: ldloc.0
IL_0009: call ""C C.op_Implicit(double)""
IL_000e: call ""CustomHandler..ctor(int, int, C)""
IL_0013: ldloca.s V_1
IL_0015: ldstr ""literal""
IL_001a: call ""bool CustomHandler.AppendLiteral(string)""
IL_001f: pop
IL_0020: ldloc.1
IL_0021: call ""void C.M(double, CustomHandler)""
IL_0026: ret
}
");
static void validator(ModuleSymbol module)
{
var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single();
AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString());
Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes);
}
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
public int Prop { get; set; }
public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
return 0;
}
set
{
Console.WriteLine(""Indexer setter"");
Console.WriteLine(c.ToString());
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
GetInt2
Indexer setter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 85 (0x55)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_5
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.s V_5
IL_0039: stloc.s V_4
IL_003b: ldloc.2
IL_003c: ldloc.3
IL_003d: ldloc.s V_4
IL_003f: ldloc.2
IL_0040: ldloc.3
IL_0041: ldloc.s V_4
IL_0043: callvirt ""int C.this[int, CustomHandler].get""
IL_0048: ldc.i4.2
IL_0049: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004e: add
IL_004f: callvirt ""void C.this[int, CustomHandler].set""
IL_0054: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 96 (0x60)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0040
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""void CustomHandler.AppendLiteral(string)""
IL_002e: ldloca.s V_5
IL_0030: ldloc.0
IL_0031: box ""int""
IL_0036: ldc.i4.0
IL_0037: ldnull
IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003d: ldc.i4.1
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.s V_5
IL_0044: stloc.s V_4
IL_0046: ldloc.2
IL_0047: ldloc.3
IL_0048: ldloc.s V_4
IL_004a: ldloc.2
IL_004b: ldloc.3
IL_004c: ldloc.s V_4
IL_004e: callvirt ""int C.this[int, CustomHandler].get""
IL_0053: ldc.i4.2
IL_0054: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0059: add
IL_005a: callvirt ""void C.this[int, CustomHandler].set""
IL_005f: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 91 (0x5b)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldloca.s V_5
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_5
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_5
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.s V_5
IL_003f: stloc.s V_4
IL_0041: ldloc.2
IL_0042: ldloc.3
IL_0043: ldloc.s V_4
IL_0045: ldloc.2
IL_0046: ldloc.3
IL_0047: ldloc.s V_4
IL_0049: callvirt ""int C.this[int, CustomHandler].get""
IL_004e: ldc.i4.2
IL_004f: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0054: add
IL_0055: callvirt ""void C.this[int, CustomHandler].set""
IL_005a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 97 (0x61)
.maxstack 6
.locals init (int V_0, //i
int V_1,
C V_2,
int V_3,
CustomHandler V_4,
CustomHandler V_5,
bool V_6)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: stloc.3
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_6
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.s V_5
IL_001e: ldloc.s V_6
IL_0020: brfalse.s IL_0041
IL_0022: ldloca.s V_5
IL_0024: ldstr ""literal""
IL_0029: call ""bool CustomHandler.AppendLiteral(string)""
IL_002e: brfalse.s IL_0041
IL_0030: ldloca.s V_5
IL_0032: ldloc.0
IL_0033: box ""int""
IL_0038: ldc.i4.0
IL_0039: ldnull
IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003f: br.s IL_0042
IL_0041: ldc.i4.0
IL_0042: pop
IL_0043: ldloc.s V_5
IL_0045: stloc.s V_4
IL_0047: ldloc.2
IL_0048: ldloc.3
IL_0049: ldloc.s V_4
IL_004b: ldloc.2
IL_004c: ldloc.3
IL_004d: ldloc.s V_4
IL_004f: callvirt ""int C.this[int, CustomHandler].get""
IL_0054: ldc.i4.2
IL_0055: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_005a: add
IL_005b: callvirt ""void C.this[int, CustomHandler].set""
IL_0060: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC()[GetInt(1), " + expression + @"] += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c]
{
get
{
Console.WriteLine(""Indexer getter"");
Console.WriteLine(c.ToString());
return ref field;
}
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
Indexer getter
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.this[int, CustomHandler].get""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.this[int, CustomHandler].get""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""literal{i}""", @"$""literal"" + $""{i}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 3;
GetC().M(GetInt(1), " + expression + @") += GetInt(2);
static C GetC()
{
Console.WriteLine(""GetC"");
return new C() { Prop = 2 };
}
static int GetInt(int i)
{
Console.WriteLine(""GetInt"" + i.ToString());
return 1;
}
public class C
{
private int field;
public int Prop { get; set; }
public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c)
{
Console.WriteLine(""M"");
Console.WriteLine(c.ToString());
return ref field;
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""Handler constructor"");
_builder.AppendLine(""arg1:"" + arg1);
_builder.AppendLine(""C.Prop:"" + c.Prop.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
GetC
GetInt1
Handler constructor
M
arg1:1
C.Prop:2
literal:literal
value:3
alignment:0
format:
GetInt2
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 72 (0x48)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""void CustomHandler.AppendLiteral(string)""
IL_0028: ldloca.s V_3
IL_002a: ldloc.0
IL_002b: box ""int""
IL_0030: ldc.i4.0
IL_0031: ldnull
IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0037: ldloc.3
IL_0038: callvirt ""ref int C.M(int, CustomHandler)""
IL_003d: dup
IL_003e: ldind.i4
IL_003f: ldc.i4.2
IL_0040: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0045: add
IL_0046: stind.i4
IL_0047: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 82 (0x52)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_003f
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""void CustomHandler.AppendLiteral(string)""
IL_002d: ldloca.s V_3
IL_002f: ldloc.0
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldc.i4.1
IL_003d: br.s IL_0040
IL_003f: ldc.i4.0
IL_0040: pop
IL_0041: ldloc.3
IL_0042: callvirt ""ref int C.M(int, CustomHandler)""
IL_0047: dup
IL_0048: ldind.i4
IL_0049: ldc.i4.2
IL_004a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004f: add
IL_0050: stind.i4
IL_0051: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 78 (0x4e)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldloca.s V_3
IL_0013: ldc.i4.7
IL_0014: ldc.i4.1
IL_0015: ldloc.1
IL_0016: ldloc.2
IL_0017: call ""CustomHandler..ctor(int, int, int, C)""
IL_001c: ldloca.s V_3
IL_001e: ldstr ""literal""
IL_0023: call ""bool CustomHandler.AppendLiteral(string)""
IL_0028: brfalse.s IL_003b
IL_002a: ldloca.s V_3
IL_002c: ldloc.0
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.3
IL_003e: callvirt ""ref int C.M(int, CustomHandler)""
IL_0043: dup
IL_0044: ldind.i4
IL_0045: ldc.i4.2
IL_0046: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_004b: add
IL_004c: stind.i4
IL_004d: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 83 (0x53)
.maxstack 7
.locals init (int V_0, //i
int V_1,
C V_2,
CustomHandler V_3,
bool V_4)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: call ""C Program.<<Main>$>g__GetC|0_0()""
IL_0007: stloc.2
IL_0008: ldloc.2
IL_0009: ldc.i4.1
IL_000a: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.7
IL_0012: ldc.i4.1
IL_0013: ldloc.1
IL_0014: ldloc.2
IL_0015: ldloca.s V_4
IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)""
IL_001c: stloc.3
IL_001d: ldloc.s V_4
IL_001f: brfalse.s IL_0040
IL_0021: ldloca.s V_3
IL_0023: ldstr ""literal""
IL_0028: call ""bool CustomHandler.AppendLiteral(string)""
IL_002d: brfalse.s IL_0040
IL_002f: ldloca.s V_3
IL_0031: ldloc.0
IL_0032: box ""int""
IL_0037: ldc.i4.0
IL_0038: ldnull
IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_003e: br.s IL_0041
IL_0040: ldc.i4.0
IL_0041: pop
IL_0042: ldloc.3
IL_0043: callvirt ""ref int C.M(int, CustomHandler)""
IL_0048: dup
IL_0049: ldind.i4
IL_004a: ldc.i4.2
IL_004b: call ""int Program.<<Main>$>g__GetInt|0_1(int)""
IL_0050: add
IL_0051: stind.i4
IL_0052: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd(string expression)
{
var code = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
_ = new C(1) { " + expression + @" };
public class C : IEnumerable<int>
{
public int Field;
public C(int i)
{
Field = i;
}
public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c)
{
Console.WriteLine(c.ToString());
}
public IEnumerator<int> GetEnumerator() => throw null;
IEnumerator IEnumerable.GetEnumerator() => throw null;
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
c.Field:1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 37 (0x25)
.maxstack 5
.locals init (C V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.7
IL_000b: ldc.i4.0
IL_000c: ldloc.0
IL_000d: call ""CustomHandler..ctor(int, int, C)""
IL_0012: ldloca.s V_1
IL_0014: ldstr ""literal""
IL_0019: call ""void CustomHandler.AppendLiteral(string)""
IL_001e: ldloc.1
IL_001f: callvirt ""void C.Add(CustomHandler)""
IL_0024: ret
}
");
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void InterpolatedStringHandlerArgumentsAttribute_DictionaryInitializer(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
_ = new C(1) { [" + expression + @"] = 1 };
public class C
{
public int Field;
public C(int i)
{
Field = i;
}
public int this[[InterpolatedStringHandlerArgument("""")] CustomHandler c]
{
set => Console.WriteLine(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.Field:"" + c.Field.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
c.Field:1
literal:literal
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 40 (0x28)
.maxstack 4
.locals init (C V_0,
CustomHandler V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""C..ctor(int)""
IL_0006: stloc.0
IL_0007: ldloca.s V_2
IL_0009: ldc.i4.7
IL_000a: ldc.i4.0
IL_000b: ldloc.0
IL_000c: call ""CustomHandler..ctor(int, int, C)""
IL_0011: ldloca.s V_2
IL_0013: ldstr ""literal""
IL_0018: call ""void CustomHandler.AppendLiteral(string)""
IL_001d: ldloc.2
IL_001e: stloc.1
IL_001f: ldloc.0
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: callvirt ""void C.this[CustomHandler].set""
IL_0027: ret
}
");
}
[Theory]
[CombinatorialData]
public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter,
[CombinatorialValues(@"$""{$""Inner string""}{2}""", @"$""{$""Inner string""}"" + $""{2}""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler)
{
Console.WriteLine(handler.ToString());
}
}
public partial class CustomHandler
{
private int I = 0;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""int constructor"");
I = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
Console.WriteLine(""CustomHandler constructor"");
_builder.AppendLine(""c.I:"" + c.I.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c)
{
_builder.AppendLine(""CustomHandler AppendFormatted"");
_builder.Append(c.ToString());
" + (useBoolReturns ? "return true;" : "") + @"
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"
int constructor
CustomHandler constructor
CustomHandler AppendFormatted
c.I:1
literal:Inner string
value:2
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 59 (0x3b)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: dup
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldc.i4.s 12
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0017: dup
IL_0018: ldstr ""Inner string""
IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: box ""int""
IL_002e: ldc.i4.0
IL_002f: ldnull
IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0035: call ""void C.M(int, CustomHandler)""
IL_003a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0034
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)""
IL_0031: ldc.i4.1
IL_0032: br.s IL_0035
IL_0034: ldc.i4.0
IL_0035: pop
IL_0036: ldloc.s V_4
IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)""
IL_003d: ldloc.1
IL_003e: ldc.i4.2
IL_003f: box ""int""
IL_0044: ldc.i4.0
IL_0045: ldnull
IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)""
IL_004b: ldc.i4.1
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 68 (0x44)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1,
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: stloc.2
IL_000e: ldloc.2
IL_000f: ldc.i4.s 12
IL_0011: ldc.i4.0
IL_0012: ldloc.2
IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0018: dup
IL_0019: ldstr ""Inner string""
IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0023: pop
IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_0029: brfalse.s IL_003b
IL_002b: ldloc.1
IL_002c: ldc.i4.2
IL_002d: box ""int""
IL_0032: ldc.i4.0
IL_0033: ldnull
IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_0039: br.s IL_003c
IL_003b: ldc.i4.0
IL_003c: pop
IL_003d: ldloc.1
IL_003e: call ""void C.M(int, CustomHandler)""
IL_0043: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 87 (0x57)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2,
CustomHandler V_3,
CustomHandler V_4,
bool V_5)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.2
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.2
IL_000f: brfalse.s IL_004e
IL_0011: ldloc.1
IL_0012: stloc.3
IL_0013: ldloc.3
IL_0014: ldc.i4.s 12
IL_0016: ldc.i4.0
IL_0017: ldloc.3
IL_0018: ldloca.s V_5
IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_001f: stloc.s V_4
IL_0021: ldloc.s V_5
IL_0023: brfalse.s IL_0033
IL_0025: ldloc.s V_4
IL_0027: ldstr ""Inner string""
IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)""
IL_0031: br.s IL_0034
IL_0033: ldc.i4.0
IL_0034: pop
IL_0035: ldloc.s V_4
IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)""
IL_003c: brfalse.s IL_004e
IL_003e: ldloc.1
IL_003f: ldc.i4.2
IL_0040: box ""int""
IL_0045: ldc.i4.0
IL_0046: ldnull
IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)""
IL_004c: br.s IL_004f
IL_004e: ldc.i4.0
IL_004f: pop
IL_0050: ldloc.1
IL_0051: call ""void C.M(int, CustomHandler)""
IL_0056: ret
}
",
};
}
[Theory]
[InlineData(@"$""literal""")]
[InlineData(@"$"""" + $""literal""")]
public void DiscardsUsedAsParameters(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(out _, " + expression + @");
public class C
{
public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c)
{
i = 0;
Console.WriteLine(c.ToString());
}
}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount)
{
i = 1;
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 31 (0x1f)
.maxstack 4
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: ldstr ""literal""
IL_0013: call ""void CustomHandler.AppendLiteral(string)""
IL_0018: ldloc.1
IL_0019: call ""void C.M(out int, CustomHandler)""
IL_001e: ret
}
");
}
[Fact]
public void DiscardsUsedAsParameters_DefinedInVB()
{
var vb = @"
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Public Class C
Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler)
Console.WriteLine(i)
End Sub
End Class
<InterpolatedStringHandler>
Public Structure CustomHandler
Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer)
i = 1
End Sub
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var code = @"C.M(out _, $"""");";
var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() });
var verifier = CompileAndVerify(comp, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldloca.s V_0
IL_0006: newobj ""CustomHandler..ctor(int, int, out int)""
IL_000b: call ""void C.M(out int, CustomHandler)""
IL_0010: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DisallowedInExpressionTrees(string expression)
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<CustomHandler>> expr = () => " + expression + @";
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler });
comp.VerifyDiagnostics(
// (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion.
// Expression<Func<CustomHandler>> expr = () => $"";
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, expression).WithLocation(5, 46)
);
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_01()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_02()
{
var code = @"
using System.Linq.Expressions;
Expression e = (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 127 (0x7f)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: pop
IL_007e: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_03()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_04()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression e = Func<string, string> () => (string o) => $""{o.Length}"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 137 (0x89)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldc.i4.1
IL_006f: newarr ""System.Linq.Expressions.ParameterExpression""
IL_0074: dup
IL_0075: ldc.i4.0
IL_0076: ldloc.0
IL_0077: stelem.ref
IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()""
IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_0087: pop
IL_0088: ret
}
");
}
[Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")]
public void AsStringInExpressionTrees_05()
{
var code = @"
using System;
using System.Linq.Expressions;
Expression<Func<string, string>> e = o => $""{o.Length}"" + $""literal"";";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp);
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 167 (0xa7)
.maxstack 7
.locals init (System.Linq.Expressions.ParameterExpression V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)""
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: ldtoken ""string string.Format(string, object)""
IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_0020: castclass ""System.Reflection.MethodInfo""
IL_0025: ldc.i4.2
IL_0026: newarr ""System.Linq.Expressions.Expression""
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldstr ""{0}""
IL_0032: ldtoken ""string""
IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.1
IL_0044: ldloc.0
IL_0045: ldtoken ""int string.Length.get""
IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_004f: castclass ""System.Reflection.MethodInfo""
IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0059: ldtoken ""object""
IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)""
IL_0068: stelem.ref
IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])""
IL_006e: ldstr ""literal""
IL_0073: ldtoken ""string""
IL_0078: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_007d: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)""
IL_0082: ldtoken ""string string.Concat(string, string)""
IL_0087: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)""
IL_008c: castclass ""System.Reflection.MethodInfo""
IL_0091: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression, System.Reflection.MethodInfo)""
IL_0096: ldc.i4.1
IL_0097: newarr ""System.Linq.Expressions.ParameterExpression""
IL_009c: dup
IL_009d: ldc.i4.0
IL_009e: ldloc.0
IL_009f: stelem.ref
IL_00a0: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])""
IL_00a5: pop
IL_00a6: ret
}
");
}
[Theory]
[CombinatorialData]
public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, " + expression + @", " + expression + @");
public class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString());
}
public partial class CustomHandler
{
private int i;
public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""i:"" + i.ToString());
this.i = i;
" + (validityParameter ? "success = true;" : "") + @"
}
public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount)
{
_builder.AppendLine(""c.i:"" + c.i.ToString());
" + (validityParameter ? "success = true;" : "") + @"
}
}";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns);
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler });
var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", getIl());
string getIl() => (useBoolReturns, validityParameter) switch
{
(useBoolReturns: false, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: false, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
(useBoolReturns: true, validityParameter: false) => @"
{
// Code size 27 (0x1b)
.maxstack 5
.locals init (int V_0,
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.0
IL_000e: ldc.i4.0
IL_000f: ldloc.1
IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)""
IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001a: ret
}
",
(useBoolReturns: true, validityParameter: true) => @"
{
// Code size 31 (0x1f)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldc.i4.0
IL_0010: ldc.i4.0
IL_0011: ldloc.1
IL_0012: ldloca.s V_2
IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)""
IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)""
IL_001e: ret
}
",
};
}
[Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")]
public void AsFormattableString()
{
var code = @"
M($""{1}"" + $""literal"");
System.FormattableString s = $""{1}"" + $""literal"";
void M(System.FormattableString s)
{
}
";
var comp = CreateCompilation(code);
comp.VerifyDiagnostics(
// (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.FormattableString'
// M($"{1}" + $"literal");
Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.FormattableString").WithLocation(2, 3),
// (3,30): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString'
// System.FormattableString s = $"{1}" + $"literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.FormattableString").WithLocation(3, 30)
);
}
[Fact, WorkItem(1370647, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1370647")]
public void AsIFormattable()
{
var code = @"
M($""{1}"" + $""literal"");
System.IFormattable s = $""{1}"" + $""literal"";
void M(System.IFormattable s)
{
}
";
var comp = CreateCompilation(code);
comp.VerifyDiagnostics(
// (2,3): error CS1503: Argument 1: cannot convert from 'string' to 'System.IFormattable'
// M($"{1}" + $"literal");
Diagnostic(ErrorCode.ERR_BadArgType, @"$""{1}"" + $""literal""").WithArguments("1", "string", "System.IFormattable").WithLocation(2, 3),
// (3,25): error CS0029: Cannot implicitly convert type 'string' to 'System.IFormattable'
// System.IFormattable s = $"{1}" + $"literal";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{1}"" + $""literal""").WithArguments("string", "System.IFormattable").WithLocation(3, 25)
);
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter,
[CombinatorialValues(@"$""{i = 1}{M(out var o)}{s = o.ToString()}""", @"$""{i = 1}"" + $""{M(out var o)}"" + $""{s = o.ToString()}""")] string expression)
{
var code = @"
int i;
string s;
CustomHandler c = " + expression + @";
_ = i.ToString();
_ = o.ToString();
_ = s.ToString();
string M(out object o)
{
o = null;
return null;
}
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (6,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5),
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else if (useBoolReturns)
{
comp.VerifyDiagnostics(
// (7,5): error CS0165: Use of unassigned local variable 'o'
// _ = o.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5),
// (8,5): error CS0165: Use of unassigned local variable 's'
// _ = s.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[CombinatorialData]
public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter, [CombinatorialValues(@"$""{i = 1}""", @"$"""" + $""{i = 1}""", @"$""{i = 1}"" + $""""")] string expression)
{
var code = @"
int i;
CustomHandler c = " + expression + @";
_ = i.ToString();
";
var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter);
var comp = CreateCompilation(new[] { code, customHandler });
if (trailingOutParameter)
{
comp.VerifyDiagnostics(
// (5,5): error CS0165: Use of unassigned local variable 'i'
// _ = i.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5)
);
}
else
{
comp.VerifyDiagnostics();
}
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_01(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
dynamic d = 1;
M(d, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_02(string expression)
{
var code = @"
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute });
comp.VerifyDiagnostics(
// (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'.
// M(d, $"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, expression).WithArguments("CustomHandler").WithLocation(4, 6)
);
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
int i = 1;
M(i, " + expression + @");
void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {}
public partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount)
{
Console.WriteLine(""d:"" + d.ToString());
}
}
";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false);
var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "d:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 22 (0x16)
.maxstack 4
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: box ""int""
IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)""
IL_0010: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)""
IL_0015: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(dynamic literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: box ""int""
IL_0006: ldc.i4.0
IL_0007: newobj ""CustomHandler..ctor(dynamic, int)""
IL_000c: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_0011: ret
}
");
}
[Theory]
[InlineData(@"$""""")]
[InlineData(@"$"""" + $""""")]
public void DynamicConstruction_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
Console.WriteLine(""ctor"");
}
public CustomHandler(dynamic literalLength, int formattedCount)
{
throw null;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "ctor");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: newobj ""CustomHandler..ctor(int, int)""
IL_0007: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_000c: ret
}
");
}
[Theory]
[InlineData(@"$""Literal""")]
[InlineData(@"$"""" + $""Literal""")]
public void DynamicConstruction_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 28 (0x1c)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.7
IL_0003: ldc.i4.0
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldstr ""Literal""
IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_0015: ldloc.0
IL_0016: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_001b: ret
}
");
}
[Theory]
[InlineData(@"$""{1}""")]
[InlineData(@"$""{1}"" + $""""")]
public void DynamicConstruction_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (CustomHandler V_0)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_0
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)""
IL_0016: ldloc.0
IL_0017: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_001c: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_08(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public void AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
}
public void AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 128 (0x80)
.maxstack 9
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)""
IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0021: brtrue.s IL_0062
IL_0023: ldc.i4 0x100
IL_0028: ldstr ""AppendFormatted""
IL_002d: ldnull
IL_002e: ldtoken ""Program""
IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0038: ldc.i4.2
IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_003e: dup
IL_003f: ldc.i4.0
IL_0040: ldc.i4.s 9
IL_0042: ldnull
IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0048: stelem.ref
IL_0049: dup
IL_004a: ldc.i4.1
IL_004b: ldc.i4.0
IL_004c: ldnull
IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0052: stelem.ref
IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0067: ldfld ""<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target""
IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> Program.<>o__0.<>p__0""
IL_0071: ldloca.s V_1
IL_0073: ldloc.0
IL_0074: callvirt ""void <>A{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_0079: ldloc.1
IL_007a: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_007f: ret
}
");
}
[Theory]
[InlineData(@"$""literal{d}""")]
[InlineData(@"$""literal"" + $""{d}""")]
public void DynamicConstruction_09(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
dynamic d = 1;
M(" + expression + @");
void M(CustomHandler c) {}
[InterpolatedStringHandler]
public struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount)
{
}
public bool AppendLiteral(dynamic d)
{
Console.WriteLine(""AppendLiteral"");
return true;
}
public bool AppendFormatted(dynamic d)
{
Console.WriteLine(""AppendFormatted"");
return true;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp);
var verifier = CompileAndVerify(comp, expectedOutput: @"
AppendLiteral
AppendFormatted");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 196 (0xc4)
.maxstack 11
.locals init (object V_0, //d
CustomHandler V_1)
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: stloc.0
IL_0007: ldloca.s V_1
IL_0009: ldc.i4.7
IL_000a: ldc.i4.1
IL_000b: call ""CustomHandler..ctor(int, int)""
IL_0010: ldloca.s V_1
IL_0012: ldstr ""literal""
IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)""
IL_001c: brfalse IL_00bb
IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_0026: brtrue.s IL_004c
IL_0028: ldc.i4.0
IL_0029: ldtoken ""bool""
IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0033: ldtoken ""Program""
IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target""
IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> Program.<>o__0.<>p__1""
IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_0060: brtrue.s IL_009d
IL_0062: ldc.i4.0
IL_0063: ldstr ""AppendFormatted""
IL_0068: ldnull
IL_0069: ldtoken ""Program""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: ldc.i4.2
IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0079: dup
IL_007a: ldc.i4.0
IL_007b: ldc.i4.s 9
IL_007d: ldnull
IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0083: stelem.ref
IL_0084: dup
IL_0085: ldc.i4.1
IL_0086: ldc.i4.0
IL_0087: ldnull
IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_008d: stelem.ref
IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_00a2: ldfld ""<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target""
IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> Program.<>o__0.<>p__0""
IL_00ac: ldloca.s V_1
IL_00ae: ldloc.0
IL_00af: callvirt ""dynamic <>F{00000004}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)""
IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_00b9: br.s IL_00bc
IL_00bb: ldc.i4.0
IL_00bc: pop
IL_00bd: ldloc.1
IL_00be: call ""void Program.<<Main>$>g__M|0_0(CustomHandler)""
IL_00c3: ret
}
");
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_01(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// return $"{s}";
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_02(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8150: By-value returns may only be used in methods that return by value
// return $"{s}";
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_03(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount) : this() {}
public void AppendFormatted(Span<char> s) => this.s = s;
public static ref CustomHandler M()
{
Span<char> s = stackalloc char[10];
return ref " + expression + @";
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference
// return ref $"{s}";
Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, expression).WithLocation(17, 20)
);
}
[Theory]
[InlineData(@"$""{s}""")]
[InlineData(@"$""{s}"" + $""""")]
public void RefEscape_04(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
S1 s1;
public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; }
public void AppendFormatted(Span<char> s) => this.s1.s = s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s1, " + expression + @");
}
public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, " + expression + @")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9),
// (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope
// M2(ref s1, $"{s}");
Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23)
);
}
[Theory]
[InlineData(@"$""{s1}""")]
[InlineData(@"$""{s1}"" + $""""")]
public void RefEscape_05(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; }
public void AppendFormatted(S1 s1) => s1.s = this.s;
public static void M(ref S1 s1)
{
Span<char> s = stackalloc char[10];
M2(ref s, " + expression + @");
}
public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {}
}
public ref struct S1
{
public Span<char> s;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_06(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Theory]
[InlineData(@"$""{s2}""")]
[InlineData(@"$""{s2}"" + $""""")]
public void RefEscape_07(string expression)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
Span<char> s = stackalloc char[5];
Span<char> s2 = stackalloc char[10];
s.TryWrite(" + expression + @");
public static class MemoryExtensions
{
public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true;
}
[InterpolatedStringHandler]
public ref struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { }
public bool AppendFormatted(Span<char> s) => true;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics();
}
[Fact]
public void RefEscape_08()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; }
public static CustomHandler M()
{
Span<char> s = stackalloc char[10];
ref CustomHandler c = ref M2(ref s, $"""");
return c;
}
public static ref CustomHandler M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] ref CustomHandler handler)
{
return ref handler;
}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (16,16): error CS8352: Cannot use local 'c' in this context because it may expose referenced variables outside of their declaration scope
// return c;
Diagnostic(ErrorCode.ERR_EscapeLocal, "c").WithArguments("c").WithLocation(16, 16)
);
}
[Fact]
public void RefEscape_09()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
[InterpolatedStringHandler]
public ref struct CustomHandler
{
Span<char> s;
public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { s1.Handler = this; }
public static void M(ref S1 s1)
{
Span<char> s2 = stackalloc char[10];
M2(ref s1, $""{s2}"");
}
public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler handler) { }
public void AppendFormatted(Span<char> s) { this.s = s; }
}
public ref struct S1
{
public CustomHandler Handler;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp);
comp.VerifyDiagnostics(
// (15,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope
// M2(ref s1, $"{s2}");
Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s2}"")").WithArguments("CustomHandler.M2(ref S1, CustomHandler)", "handler").WithLocation(15, 9),
// (15,23): error CS8352: Cannot use local 's2' in this context because it may expose referenced variables outside of their declaration scope
// M2(ref s1, $"{s2}");
Diagnostic(ErrorCode.ERR_EscapeLocal, "s2").WithArguments("s2").WithLocation(15, 23)
);
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_01(string expression)
{
var code = @"
int i = 1;
System.Console.WriteLine(" + expression + @");";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
{
value:1
}");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 56 (0x38)
.maxstack 3
.locals init (int V_0, //i
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldstr ""{ ""
IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_1
IL_0019: ldloc.0
IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_001f: ldloca.s V_1
IL_0021: ldstr "" }""
IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)""
IL_002b: ldloca.s V_1
IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
}
");
}
[Theory, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")]
[InlineData(@"$""{{ {i} }}""")]
[InlineData(@"$""{{ "" + $""{i}"" + $"" }}""")]
public void BracesAreEscaped_02(string expression)
{
var code = @"
int i = 1;
CustomHandler c = " + expression + @";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
literal:{
value:1
alignment:0
format:
literal: }");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 71 (0x47)
.maxstack 4
.locals init (int V_0, //i
CustomHandler V_1, //c
CustomHandler V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_2
IL_0004: ldc.i4.4
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_2
IL_000d: ldstr ""{ ""
IL_0012: call ""void CustomHandler.AppendLiteral(string)""
IL_0017: ldloca.s V_2
IL_0019: ldloc.0
IL_001a: box ""int""
IL_001f: ldc.i4.0
IL_0020: ldnull
IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0026: ldloca.s V_2
IL_0028: ldstr "" }""
IL_002d: call ""void CustomHandler.AppendLiteral(string)""
IL_0032: ldloc.2
IL_0033: stloc.1
IL_0034: ldloca.s V_1
IL_0036: constrained. ""CustomHandler""
IL_003c: callvirt ""string object.ToString()""
IL_0041: call ""void System.Console.WriteLine(string)""
IL_0046: ret
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
int i4 = 4;
System.Console.WriteLine($""{i1}"" + $""{i2}"" + $""{i3}"" + i4);";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
value:2
value:3
4
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 66 (0x42)
.maxstack 3
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
int V_3, //i4
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldc.i4.4
IL_0007: stloc.3
IL_0008: ldloca.s V_4
IL_000a: ldc.i4.0
IL_000b: ldc.i4.3
IL_000c: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_0011: ldloca.s V_4
IL_0013: ldloc.0
IL_0014: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0019: ldloca.s V_4
IL_001b: ldloc.1
IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0021: ldloca.s V_4
IL_0023: ldloc.2
IL_0024: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0029: ldloca.s V_4
IL_002b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_0030: ldloca.s V_3
IL_0032: call ""string int.ToString()""
IL_0037: call ""string string.Concat(string, string)""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}
");
}
[Theory]
[InlineData(@"$""({i1}),"" + $""[{i2}],"" + $""{{{i3}}}""")]
[InlineData(@"($""({i1}),"" + $""[{i2}],"") + $""{{{i3}}}""")]
[InlineData(@"$""({i1}),"" + ($""[{i2}],"" + $""{{{i3}}}"")")]
public void InterpolatedStringsAddedUnderObjectAddition2(string expression)
{
var code = $@"
int i1 = 1;
int i2 = 2;
int i3 = 3;
System.Console.WriteLine({expression});";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
CompileAndVerify(comp, expectedOutput: @"
(
value:1
),
[
value:2
],
{
value:3
}
");
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition3()
{
var code = @"
#nullable enable
using System;
try
{
var s = string.Empty;
Console.WriteLine($""{s = null}{s.Length}"" + $"""");
}
catch (NullReferenceException)
{
Console.WriteLine(""Null reference exception caught."");
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) });
CompileAndVerify(comp, expectedOutput: "Null reference exception caught.").VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (string V_0, //s
System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1)
.try
{
IL_0000: ldsfld ""string string.Empty""
IL_0005: stloc.0
IL_0006: ldc.i4.0
IL_0007: ldc.i4.2
IL_0008: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)""
IL_000d: stloc.1
IL_000e: ldloca.s V_1
IL_0010: ldnull
IL_0011: dup
IL_0012: stloc.0
IL_0013: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)""
IL_0018: ldloca.s V_1
IL_001a: ldloc.0
IL_001b: callvirt ""int string.Length.get""
IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)""
IL_0025: ldloca.s V_1
IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()""
IL_002c: call ""void System.Console.WriteLine(string)""
IL_0031: leave.s IL_0040
}
catch System.NullReferenceException
{
IL_0033: pop
IL_0034: ldstr ""Null reference exception caught.""
IL_0039: call ""void System.Console.WriteLine(string)""
IL_003e: leave.s IL_0040
}
IL_0040: ret
}
").VerifyDiagnostics(
// (9,36): warning CS8602: Dereference of a possibly null reference.
// Console.WriteLine($"{s = null}{s.Length}" + $"");
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 36)
);
}
[Fact]
public void InterpolatedStringsAddedUnderObjectAddition_DefiniteAssignment()
{
var code = @"
object o1;
object o2;
object o3;
_ = $""{o1 = null}"" + $""{o2 = null}"" + $""{o3 = null}"" + 1;
o1.ToString();
o2.ToString();
o3.ToString();
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true) });
comp.VerifyDiagnostics(
// (7,1): error CS0165: Use of unassigned local variable 'o2'
// o2.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o2").WithArguments("o2").WithLocation(7, 1),
// (8,1): error CS0165: Use of unassigned local variable 'o3'
// o3.ToString();
Diagnostic(ErrorCode.ERR_UseDefViolation, "o3").WithArguments("o3").WithLocation(8, 1)
);
}
[Fact]
public void ParenthesizedAdditiveExpression_01()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = ($""{i1}"" + $""{i2}"") + $""{i3}"";
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
value:3
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 82 (0x52)
.maxstack 4
.locals init (int V_0, //i1
int V_1, //i2
int V_2, //i3
CustomHandler V_3, //c
CustomHandler V_4)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldloca.s V_4
IL_0008: ldc.i4.0
IL_0009: ldc.i4.3
IL_000a: call ""CustomHandler..ctor(int, int)""
IL_000f: ldloca.s V_4
IL_0011: ldloc.0
IL_0012: box ""int""
IL_0017: ldc.i4.0
IL_0018: ldnull
IL_0019: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001e: ldloca.s V_4
IL_0020: ldloc.1
IL_0021: box ""int""
IL_0026: ldc.i4.0
IL_0027: ldnull
IL_0028: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_002d: ldloca.s V_4
IL_002f: ldloc.2
IL_0030: box ""int""
IL_0035: ldc.i4.0
IL_0036: ldnull
IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_003c: ldloc.s V_4
IL_003e: stloc.3
IL_003f: ldloca.s V_3
IL_0041: constrained. ""CustomHandler""
IL_0047: callvirt ""string object.ToString()""
IL_004c: call ""void System.Console.WriteLine(string)""
IL_0051: ret
}");
}
[Fact]
public void ParenthesizedAdditiveExpression_02()
{
var code = @"
int i1 = 1;
int i2 = 2;
int i3 = 3;
CustomHandler c = $""{i1}"" + ($""{i2}"" + $""{i3}"");
System.Console.WriteLine(c.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (6,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler'
// CustomHandler c = $"{i1}" + ($"{i2}" + $"{i3}");
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{i1}"" + ($""{i2}"" + $""{i3}"")").WithArguments("string", "CustomHandler").WithLocation(6, 19)
);
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_01(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) = (" + initializer + @");
System.Console.Write(c1.ToString());
System.Console.WriteLine(c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 91 (0x5b)
.maxstack 4
.locals init (CustomHandler V_0, //c1
CustomHandler V_1, //c2
CustomHandler V_2,
CustomHandler V_3)
IL_0000: ldloca.s V_3
IL_0002: ldc.i4.0
IL_0003: ldc.i4.1
IL_0004: call ""CustomHandler..ctor(int, int)""
IL_0009: ldloca.s V_3
IL_000b: ldc.i4.1
IL_000c: box ""int""
IL_0011: ldc.i4.0
IL_0012: ldnull
IL_0013: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0018: ldloc.3
IL_0019: stloc.2
IL_001a: ldloca.s V_3
IL_001c: ldc.i4.0
IL_001d: ldc.i4.1
IL_001e: call ""CustomHandler..ctor(int, int)""
IL_0023: ldloca.s V_3
IL_0025: ldc.i4.2
IL_0026: box ""int""
IL_002b: ldc.i4.0
IL_002c: ldnull
IL_002d: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0032: ldloc.3
IL_0033: ldloc.2
IL_0034: stloc.0
IL_0035: stloc.1
IL_0036: ldloca.s V_0
IL_0038: constrained. ""CustomHandler""
IL_003e: callvirt ""string object.ToString()""
IL_0043: call ""void System.Console.Write(string)""
IL_0048: ldloca.s V_1
IL_004a: constrained. ""CustomHandler""
IL_0050: callvirt ""string object.ToString()""
IL_0055: call ""void System.Console.WriteLine(string)""
IL_005a: ret
}
");
}
[Theory]
[InlineData(@"$""{1}"", $""{2}""")]
[InlineData(@"$""{1}"" + $"""", $""{2}"" + $""""")]
public void TupleDeclaration_02(string initializer)
{
var code = @"
(CustomHandler c1, CustomHandler c2) t = (" + initializer + @");
System.Console.Write(t.c1.ToString());
System.Console.WriteLine(t.c2.ToString());";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
var verifier = CompileAndVerify(comp, expectedOutput: @"
value:1
alignment:0
format:
value:2
alignment:0
format:
");
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 104 (0x68)
.maxstack 6
.locals init (System.ValueTuple<CustomHandler, CustomHandler> V_0, //t
CustomHandler V_1)
IL_0000: ldloca.s V_0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: call ""CustomHandler..ctor(int, int)""
IL_000b: ldloca.s V_1
IL_000d: ldc.i4.1
IL_000e: box ""int""
IL_0013: ldc.i4.0
IL_0014: ldnull
IL_0015: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_001a: ldloc.1
IL_001b: ldloca.s V_1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.1
IL_001f: call ""CustomHandler..ctor(int, int)""
IL_0024: ldloca.s V_1
IL_0026: ldc.i4.2
IL_0027: box ""int""
IL_002c: ldc.i4.0
IL_002d: ldnull
IL_002e: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0033: ldloc.1
IL_0034: call ""System.ValueTuple<CustomHandler, CustomHandler>..ctor(CustomHandler, CustomHandler)""
IL_0039: ldloca.s V_0
IL_003b: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item1""
IL_0040: constrained. ""CustomHandler""
IL_0046: callvirt ""string object.ToString()""
IL_004b: call ""void System.Console.Write(string)""
IL_0050: ldloca.s V_0
IL_0052: ldflda ""CustomHandler System.ValueTuple<CustomHandler, CustomHandler>.Item2""
IL_0057: constrained. ""CustomHandler""
IL_005d: callvirt ""string object.ToString()""
IL_0062: call ""void System.Console.WriteLine(string)""
IL_0067: ret
}
");
}
[Theory, WorkItem(55609, "https://github.com/dotnet/roslyn/issues/55609")]
[InlineData(@"$""{h1}{h2}""")]
[InlineData(@"$""{h1}"" + $""{h2}""")]
public void RefStructHandler_DynamicInHole(string expression)
{
var code = @"
dynamic h1 = 1;
dynamic h2 = 2;
CustomHandler c = " + expression + ";";
var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "ref struct", useBoolReturns: false);
var comp = CreateCompilationWithCSharp(new[] { code, handler });
// Note: We don't give any errors when mixing dynamic and ref structs today. If that ever changes, we should get an
// error here. This will crash at runtime because of this.
comp.VerifyEmitDiagnostics();
}
[Theory]
[InlineData(@"$""Literal{1}""")]
[InlineData(@"$""Literal"" + $""{1}""")]
public void ConversionInParamsArguments(string expression)
{
var code = @"
using System;
using System.Linq;
M(" + expression + ", " + expression + @");
void M(params CustomHandler[] handlers)
{
Console.WriteLine(string.Join(Environment.NewLine, handlers.Select(h => h.ToString())));
}
";
var verifier = CompileAndVerify(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, expectedOutput: @"
literal:Literal
value:1
alignment:0
format:
literal:Literal
value:1
alignment:0
format:
");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 100 (0x64)
.maxstack 7
.locals init (CustomHandler V_0)
IL_0000: ldc.i4.2
IL_0001: newarr ""CustomHandler""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.7
IL_000b: ldc.i4.1
IL_000c: call ""CustomHandler..ctor(int, int)""
IL_0011: ldloca.s V_0
IL_0013: ldstr ""Literal""
IL_0018: call ""void CustomHandler.AppendLiteral(string)""
IL_001d: ldloca.s V_0
IL_001f: ldc.i4.1
IL_0020: box ""int""
IL_0025: ldc.i4.0
IL_0026: ldnull
IL_0027: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_002c: ldloc.0
IL_002d: stelem ""CustomHandler""
IL_0032: dup
IL_0033: ldc.i4.1
IL_0034: ldloca.s V_0
IL_0036: ldc.i4.7
IL_0037: ldc.i4.1
IL_0038: call ""CustomHandler..ctor(int, int)""
IL_003d: ldloca.s V_0
IL_003f: ldstr ""Literal""
IL_0044: call ""void CustomHandler.AppendLiteral(string)""
IL_0049: ldloca.s V_0
IL_004b: ldc.i4.1
IL_004c: box ""int""
IL_0051: ldc.i4.0
IL_0052: ldnull
IL_0053: call ""void CustomHandler.AppendFormatted(object, int, string)""
IL_0058: ldloc.0
IL_0059: stelem ""CustomHandler""
IL_005e: call ""void Program.<<Main>$>g__M|0_0(CustomHandler[])""
IL_0063: ret
}
");
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLocalFunctions_01(string mod)
{
var code = @"
using System.Runtime.CompilerServices;
M($"""");
" + mod + @" void M([InterpolatedStringHandlerArgument("""")] CustomHandler c) { }
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3),
// (6,10): error CS8944: 'M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// void M([InterpolatedStringHandlerArgument("")] CustomHandler c) { }
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M(CustomHandler)").WithLocation(6, 10 + mod.Length)
);
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLocalFunctions_02(string mod)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M(1, $"""");
" + mod + @" void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString());
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 17 (0x11)
.maxstack 4
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: newobj ""CustomHandler..ctor(int, int, int)""
IL_000b: call ""void Program.<<Main>$>g__M|0_0(int, CustomHandler)""
IL_0010: ret
}
");
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLambdas_01(string mod)
{
var code = @"
using System.Runtime.CompilerServices;
var a = " + mod + @" ([InterpolatedStringHandlerArgument("""")] CustomHandler c) => { };
a($"""");
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (4,12): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.
// var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { };
Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument("""")").WithLocation(4, 12 + mod.Length),
// (4,12): error CS8944: 'lambda expression' is not an instance method, the receiver cannot be an interpolated string handler argument.
// var a = ([InterpolatedStringHandlerArgument("")] CustomHandler c) => { };
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("lambda expression").WithLocation(4, 12 + mod.Length)
);
}
[Theory]
[InlineData("static")]
[InlineData("")]
public void ArgumentsOnLambdas_02(string mod)
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var a = " + mod + @" (int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
a(1, $"""");
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) => throw null;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"");
verifier.VerifyDiagnostics(
// (5,19): warning CS8971: InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.
// var a = (int i, [InterpolatedStringHandlerArgument("i")] CustomHandler c) => Console.WriteLine(c.ToString());
Diagnostic(ErrorCode.WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters, @"InterpolatedStringHandlerArgument(""i"")").WithLocation(5, 19 + mod.Length)
);
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 45 (0x2d)
.maxstack 4
IL_0000: ldsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0""
IL_0005: dup
IL_0006: brtrue.s IL_001f
IL_0008: pop
IL_0009: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)""
IL_0014: newobj ""System.Action<int, CustomHandler>..ctor(object, System.IntPtr)""
IL_0019: dup
IL_001a: stsfld ""System.Action<int, CustomHandler> Program.<>c.<>9__0_0""
IL_001f: ldc.i4.1
IL_0020: ldc.i4.0
IL_0021: ldc.i4.0
IL_0022: newobj ""CustomHandler..ctor(int, int)""
IL_0027: callvirt ""void System.Action<int, CustomHandler>.Invoke(int, CustomHandler)""
IL_002c: ret
}
");
}
[Fact]
public void ArgumentsOnDelegateTypes_01()
{
var code = @"
using System.Runtime.CompilerServices;
M m = null;
m($"""");
delegate void M([InterpolatedStringHandlerArgument("""")] CustomHandler c);
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (6,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// m($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(6, 3),
// (8,18): error CS8944: 'M.Invoke(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// delegate void M([InterpolatedStringHandlerArgument("")] CustomHandler c);
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("M.Invoke(CustomHandler)").WithLocation(8, 18)
);
}
[Fact]
public void ArgumentsOnDelegateTypes_02()
{
var vbCode = @"
Imports System.Runtime.CompilerServices
Public Delegate Sub M(<InterpolatedStringHandlerArgument("""")> c As CustomHandler)
<InterpolatedStringHandler>
Public Structure CustomHandler
End Structure
";
var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB });
vbComp.VerifyDiagnostics();
var code = @"
M m = null;
m($"""");
";
var comp = CreateCompilation(code, references: new[] { vbComp.EmitToImageReference() });
comp.VerifyDiagnostics(
// (4,3): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// m($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 3),
// (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments
// m($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(4, 3),
// (4,3): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments
// m($"");
Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(4, 3)
);
}
[Fact]
public void ArgumentsOnDelegateTypes_03()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
M m = (i, c) => Console.WriteLine(c.ToString());
m(1, $"""");
delegate void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c);
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) => _builder.Append(""i:"" + i.ToString());
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: @"i:1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 48 (0x30)
.maxstack 5
.locals init (int V_0)
IL_0000: ldsfld ""M Program.<>c.<>9__0_0""
IL_0005: dup
IL_0006: brtrue.s IL_001f
IL_0008: pop
IL_0009: ldsfld ""Program.<>c Program.<>c.<>9""
IL_000e: ldftn ""void Program.<>c.<<Main>$>b__0_0(int, CustomHandler)""
IL_0014: newobj ""M..ctor(object, System.IntPtr)""
IL_0019: dup
IL_001a: stsfld ""M Program.<>c.<>9__0_0""
IL_001f: ldc.i4.1
IL_0020: stloc.0
IL_0021: ldloc.0
IL_0022: ldc.i4.0
IL_0023: ldc.i4.0
IL_0024: ldloc.0
IL_0025: newobj ""CustomHandler..ctor(int, int, int)""
IL_002a: callvirt ""void M.Invoke(int, CustomHandler)""
IL_002f: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_01()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M($"""");
class C
{
public static void M(CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private int _i = 0;
public CustomHandler(int literalLength, int formattedCount, int i = 1) => _i = i;
public override string ToString() => _i.ToString();
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 14 (0xe)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.0
IL_0002: ldc.i4.1
IL_0003: newobj ""CustomHandler..ctor(int, int, int)""
IL_0008: call ""void C.M(CustomHandler)""
IL_000d: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_02()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M($""Literal"");
class C
{
public static void M(CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private string _s = null;
public CustomHandler(int literalLength, int formattedCount, out bool isValid, int i = 1) { _s = i.ToString(); isValid = false; }
public void AppendLiteral(string s) => _s += s;
public override string ToString() => _s;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"1");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 38 (0x26)
.maxstack 4
.locals init (CustomHandler V_0,
bool V_1)
IL_0000: ldc.i4.7
IL_0001: ldc.i4.0
IL_0002: ldloca.s V_1
IL_0004: ldc.i4.1
IL_0005: newobj ""CustomHandler..ctor(int, int, out bool, int)""
IL_000a: stloc.0
IL_000b: ldloc.1
IL_000c: brfalse.s IL_001d
IL_000e: ldloca.s V_0
IL_0010: ldstr ""Literal""
IL_0015: call ""void CustomHandler.AppendLiteral(string)""
IL_001a: ldc.i4.1
IL_001b: br.s IL_001e
IL_001d: ldc.i4.0
IL_001e: pop
IL_001f: ldloc.0
IL_0020: call ""void C.M(CustomHandler)""
IL_0025: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_03()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, $"""");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private string _s = null;
public CustomHandler(int literalLength, int formattedCount, int i1, int i2 = 2) { _s = i1.ToString() + i2.ToString(); }
public void AppendLiteral(string s) => _s += s;
public override string ToString() => _s;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 18 (0x12)
.maxstack 5
.locals init (int V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldc.i4.2
IL_0007: newobj ""CustomHandler..ctor(int, int, int, int)""
IL_000c: call ""void C.M(int, CustomHandler)""
IL_0011: ret
}
");
}
[Fact]
public void HandlerConstructorWithDefaultArgument_04()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
C.M(1, $""Literal"");
class C
{
public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
[InterpolatedStringHandler]
partial struct CustomHandler
{
private string _s = null;
public CustomHandler(int literalLength, int formattedCount, int i1, out bool isValid, int i2 = 2) { _s = i1.ToString() + i2.ToString(); isValid = false; }
public void AppendLiteral(string s) => _s += s;
public override string ToString() => _s;
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, expectedOutput: @"12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("<top-level-statements-entry-point>", @"
{
// Code size 42 (0x2a)
.maxstack 6
.locals init (int V_0,
CustomHandler V_1,
bool V_2)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.7
IL_0004: ldc.i4.0
IL_0005: ldloc.0
IL_0006: ldloca.s V_2
IL_0008: ldc.i4.2
IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool, int)""
IL_000e: stloc.1
IL_000f: ldloc.2
IL_0010: brfalse.s IL_0021
IL_0012: ldloca.s V_1
IL_0014: ldstr ""Literal""
IL_0019: call ""void CustomHandler.AppendLiteral(string)""
IL_001e: ldc.i4.1
IL_001f: br.s IL_0022
IL_0021: ldc.i4.0
IL_0022: pop
IL_0023: ldloc.1
IL_0024: call ""void C.M(int, CustomHandler)""
IL_0029: ret
}
");
}
[Fact]
public void HandlerExtensionMethod_01()
{
var code = @"
$""Test"".M();
public static class StringExt
{
public static void M(this CustomHandler handler) => throw null;
}
";
var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (2,1): error CS1929: 'string' does not contain a definition for 'M' and the best extension method overload 'StringExt.M(CustomHandler)' requires a receiver of type 'CustomHandler'
// $"Test".M();
Diagnostic(ErrorCode.ERR_BadInstanceArgType, @"$""Test""").WithArguments("string", "M", "StringExt.M(CustomHandler)", "CustomHandler").WithLocation(2, 1)
);
}
[Fact]
public void HandlerExtensionMethod_02()
{
var code = @"
using System.Runtime.CompilerServices;
var s = new S1();
s.M($"""");
public struct S1
{
public int Field = 1;
}
public static class S1Ext
{
public static void M(this S1 s, [InterpolatedStringHandlerArgument("""")] CustomHandler c) => throw null;
}
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S1 s) => throw null;
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) });
comp.VerifyDiagnostics(
// (5,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually.
// s.M($"");
Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(5, 5),
// (14,38): error CS8944: 'S1Ext.M(S1, CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument.
// public static void M(this S1 s, [InterpolatedStringHandlerArgument("")] CustomHandler c) => throw null;
Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgument("""")").WithArguments("S1Ext.M(S1, CustomHandler)").WithLocation(14, 38)
);
}
[Fact]
public void HandlerExtensionMethod_03()
{
var code = @"
using System;
using System.Runtime.CompilerServices;
var s = new S1();
s.M($"""");
public struct S1
{
public int Field = 1;
}
public static class S1Ext
{
public static void M(this S1 s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler c) => Console.WriteLine(c.ToString());
}
partial struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, S1 s) : this(literalLength, formattedCount) => _builder.Append(""s.Field:"" + s.Field);
}
";
var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, expectedOutput: "s.Field:1");
verifier.VerifyDiagnostics();
}
[Fact]
public void NoStandaloneConstructor()
{
var code = @"
using System.Runtime.CompilerServices;
CustomHandler c = $"""";
[InterpolatedStringHandler]
struct CustomHandler
{
public CustomHandler(int literalLength, int formattedCount, string s) {}
}
";
var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute });
comp.VerifyDiagnostics(
// (4,19): error CS7036: There is no argument given that corresponds to the required formal parameter 's' of 'CustomHandler.CustomHandler(int, int, string)'
// CustomHandler c = $"";
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("s", "CustomHandler.CustomHandler(int, int, string)").WithLocation(4, 19),
// (4,19): error CS1615: Argument 3 may not be passed with the 'out' keyword
// CustomHandler c = $"";
Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(4, 19)
);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
/// <summary>
/// Provides information about a project that has been loaded from disk and
/// built with MSBuild. If the project is multi-targeting, this represents
/// the information from a single target framework.
/// </summary>
internal sealed class ProjectFileInfo
{
public bool IsEmpty { get; }
/// <summary>
/// The language of this project.
/// </summary>
public string Language { get; }
/// <summary>
/// The path to the project file for this project.
/// </summary>
public string? FilePath { get; }
/// <summary>
/// The path to the output file this project generates.
/// </summary>
public string? OutputFilePath { get; }
/// <summary>
/// The path to the reference assembly output file this project generates.
/// </summary>
public string? OutputRefFilePath { get; }
/// <summary>
/// The default namespace of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
/// by assigning the value of the project's root namespace to it. So various feature can choose to
/// use it for their own purpose.
/// In the future, we might consider officially exposing "default namespace" for VB project
/// (e.g. through a "defaultnamespace" msbuild property)
/// </remarks>
public string? DefaultNamespace { get; }
/// <summary>
/// The target framework of this project.
/// This takes the form of the 'short name' form used by NuGet (e.g. net46, netcoreapp2.0, etc.)
/// </summary>
public string? TargetFramework { get; }
/// <summary>
/// The command line args used to compile the project.
/// </summary>
public ImmutableArray<string> CommandLineArgs { get; }
/// <summary>
/// The source documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> Documents { get; }
/// <summary>
/// The additional documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AdditionalDocuments { get; }
/// <summary>
/// The analyzer config documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AnalyzerConfigDocuments { get; }
/// <summary>
/// References to other projects.
/// </summary>
public ImmutableArray<ProjectFileReference> ProjectReferences { get; }
/// <summary>
/// The error message produced when a failure occurred attempting to get the info.
/// If a failure occurred some or all of the information may be inaccurate or incomplete.
/// </summary>
public DiagnosticLog Log { get; }
public override string ToString()
=> RoslynString.IsNullOrWhiteSpace(TargetFramework)
? FilePath ?? string.Empty
: $"{FilePath} ({TargetFramework})";
private ProjectFileInfo(
bool isEmpty,
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
{
RoslynDebug.Assert(filePath != null);
this.IsEmpty = isEmpty;
this.Language = language;
this.FilePath = filePath;
this.OutputFilePath = outputFilePath;
this.OutputRefFilePath = outputRefFilePath;
this.DefaultNamespace = defaultNamespace;
this.TargetFramework = targetFramework;
this.CommandLineArgs = commandLineArgs;
this.Documents = documents;
this.AdditionalDocuments = additionalDocuments;
this.AnalyzerConfigDocuments = analyzerConfigDocuments;
this.ProjectReferences = projectReferences;
this.Log = log;
}
public static ProjectFileInfo Create(
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
=> new(
isEmpty: false,
language,
filePath,
outputFilePath,
outputRefFilePath,
defaultNamespace,
targetFramework,
commandLineArgs,
documents,
additionalDocuments,
analyzerConfigDocuments,
projectReferences,
log);
public static ProjectFileInfo CreateEmpty(string language, string? filePath, DiagnosticLog log)
=> new(
isEmpty: true,
language,
filePath,
outputFilePath: null,
outputRefFilePath: null,
defaultNamespace: null,
targetFramework: null,
commandLineArgs: ImmutableArray<string>.Empty,
documents: ImmutableArray<DocumentFileInfo>.Empty,
additionalDocuments: ImmutableArray<DocumentFileInfo>.Empty,
analyzerConfigDocuments: ImmutableArray<DocumentFileInfo>.Empty,
projectReferences: ImmutableArray<ProjectFileReference>.Empty,
log);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
/// <summary>
/// Provides information about a project that has been loaded from disk and
/// built with MSBuild. If the project is multi-targeting, this represents
/// the information from a single target framework.
/// </summary>
internal sealed class ProjectFileInfo
{
public bool IsEmpty { get; }
/// <summary>
/// The language of this project.
/// </summary>
public string Language { get; }
/// <summary>
/// The path to the project file for this project.
/// </summary>
public string? FilePath { get; }
/// <summary>
/// The path to the output file this project generates.
/// </summary>
public string? OutputFilePath { get; }
/// <summary>
/// The path to the reference assembly output file this project generates.
/// </summary>
public string? OutputRefFilePath { get; }
/// <summary>
/// The default namespace of the project ("" if not defined, which means global namespace),
/// or null if it is unknown or not applicable.
/// </summary>
/// <remarks>
/// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace
/// by assigning the value of the project's root namespace to it. So various feature can choose to
/// use it for their own purpose.
/// In the future, we might consider officially exposing "default namespace" for VB project
/// (e.g. through a "defaultnamespace" msbuild property)
/// </remarks>
public string? DefaultNamespace { get; }
/// <summary>
/// The target framework of this project.
/// This takes the form of the 'short name' form used by NuGet (e.g. net46, netcoreapp2.0, etc.)
/// </summary>
public string? TargetFramework { get; }
/// <summary>
/// The command line args used to compile the project.
/// </summary>
public ImmutableArray<string> CommandLineArgs { get; }
/// <summary>
/// The source documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> Documents { get; }
/// <summary>
/// The additional documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AdditionalDocuments { get; }
/// <summary>
/// The analyzer config documents.
/// </summary>
public ImmutableArray<DocumentFileInfo> AnalyzerConfigDocuments { get; }
/// <summary>
/// References to other projects.
/// </summary>
public ImmutableArray<ProjectFileReference> ProjectReferences { get; }
/// <summary>
/// The error message produced when a failure occurred attempting to get the info.
/// If a failure occurred some or all of the information may be inaccurate or incomplete.
/// </summary>
public DiagnosticLog Log { get; }
public override string ToString()
=> RoslynString.IsNullOrWhiteSpace(TargetFramework)
? FilePath ?? string.Empty
: $"{FilePath} ({TargetFramework})";
private ProjectFileInfo(
bool isEmpty,
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
{
RoslynDebug.Assert(filePath != null);
this.IsEmpty = isEmpty;
this.Language = language;
this.FilePath = filePath;
this.OutputFilePath = outputFilePath;
this.OutputRefFilePath = outputRefFilePath;
this.DefaultNamespace = defaultNamespace;
this.TargetFramework = targetFramework;
this.CommandLineArgs = commandLineArgs;
this.Documents = documents;
this.AdditionalDocuments = additionalDocuments;
this.AnalyzerConfigDocuments = analyzerConfigDocuments;
this.ProjectReferences = projectReferences;
this.Log = log;
}
public static ProjectFileInfo Create(
string language,
string? filePath,
string? outputFilePath,
string? outputRefFilePath,
string? defaultNamespace,
string? targetFramework,
ImmutableArray<string> commandLineArgs,
ImmutableArray<DocumentFileInfo> documents,
ImmutableArray<DocumentFileInfo> additionalDocuments,
ImmutableArray<DocumentFileInfo> analyzerConfigDocuments,
ImmutableArray<ProjectFileReference> projectReferences,
DiagnosticLog log)
=> new(
isEmpty: false,
language,
filePath,
outputFilePath,
outputRefFilePath,
defaultNamespace,
targetFramework,
commandLineArgs,
documents,
additionalDocuments,
analyzerConfigDocuments,
projectReferences,
log);
public static ProjectFileInfo CreateEmpty(string language, string? filePath, DiagnosticLog log)
=> new(
isEmpty: true,
language,
filePath,
outputFilePath: null,
outputRefFilePath: null,
defaultNamespace: null,
targetFramework: null,
commandLineArgs: ImmutableArray<string>.Empty,
documents: ImmutableArray<DocumentFileInfo>.Empty,
additionalDocuments: ImmutableArray<DocumentFileInfo>.Empty,
analyzerConfigDocuments: ImmutableArray<DocumentFileInfo>.Empty,
projectReferences: ImmutableArray<ProjectFileReference>.Empty,
log);
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/TestUtilities/EditAndContinue/MockManagedEditAndContinueDebuggerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal class MockManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService
{
public Func<Guid, ManagedEditAndContinueAvailability>? IsEditAndContinueAvailable;
public Dictionary<Guid, ManagedEditAndContinueAvailability>? LoadedModules;
public Func<ImmutableArray<ManagedActiveStatementDebugInfo>>? GetActiveStatementsImpl;
public Func<ImmutableArray<string>>? GetCapabilitiesImpl;
public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken)
=> Task.FromResult(GetActiveStatementsImpl?.Invoke() ?? ImmutableArray<ManagedActiveStatementDebugInfo>.Empty);
public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken)
{
if (IsEditAndContinueAvailable != null)
{
return Task.FromResult(IsEditAndContinueAvailable(mvid));
}
if (LoadedModules != null)
{
return Task.FromResult(LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded));
}
throw new NotImplementedException();
}
public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken)
=> Task.FromResult(GetCapabilitiesImpl?.Invoke() ?? ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"));
public Task PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken)
=> Task.CompletedTask;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal class MockManagedEditAndContinueDebuggerService : IManagedEditAndContinueDebuggerService
{
public Func<Guid, ManagedEditAndContinueAvailability>? IsEditAndContinueAvailable;
public Dictionary<Guid, ManagedEditAndContinueAvailability>? LoadedModules;
public Func<ImmutableArray<ManagedActiveStatementDebugInfo>>? GetActiveStatementsImpl;
public Func<ImmutableArray<string>>? GetCapabilitiesImpl;
public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken)
=> Task.FromResult(GetActiveStatementsImpl?.Invoke() ?? ImmutableArray<ManagedActiveStatementDebugInfo>.Empty);
public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid mvid, CancellationToken cancellationToken)
{
if (IsEditAndContinueAvailable != null)
{
return Task.FromResult(IsEditAndContinueAvailable(mvid));
}
if (LoadedModules != null)
{
return Task.FromResult(LoadedModules.TryGetValue(mvid, out var result) ? result : new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded));
}
throw new NotImplementedException();
}
public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken)
=> Task.FromResult(GetCapabilitiesImpl?.Invoke() ?? ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"));
public Task PrepareModuleForUpdateAsync(Guid mvid, CancellationToken cancellationToken)
=> Task.CompletedTask;
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/Test/Core/Diagnostics/DescriptorFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
/// <summary>
/// Factory for creating different kinds of <see cref="DiagnosticDescriptor"/>s for use in tests.
/// </summary>
public static class DescriptorFactory
{
/// <summary>
/// Creates a <see cref="DiagnosticDescriptor"/> with specified <see cref="DiagnosticDescriptor.Id"/>.
/// </summary>
/// <remarks>
/// Returned <see cref="DiagnosticDescriptor"/> has
/// - empty <see cref="DiagnosticDescriptor.Title"/> and <see cref="DiagnosticDescriptor.Category"/>
/// - <see cref="DiagnosticDescriptor.MessageFormat"/> set to <paramref name="id"/>
/// - <see cref="DiagnosticDescriptor.DefaultSeverity"/> set to <see cref="DiagnosticSeverity.Hidden"/>
/// - <see cref="WellKnownDiagnosticTags.NotConfigurable"/> custom tag added in <see cref="DiagnosticDescriptor.CustomTags"/>.
/// </remarks>
/// <param name="id">The value for <see cref="DiagnosticDescriptor.Id"/>.</param>
/// <param name="additionalCustomTags">Additional custom tags</param>
/// <returns>A <see cref="DiagnosticDescriptor"/> with specified <see cref="DiagnosticDescriptor.Id"/>.</returns>
public static DiagnosticDescriptor CreateSimpleDescriptor(string id, params string[] additionalCustomTags)
{
var customTags = additionalCustomTags.Concat(WellKnownDiagnosticTags.NotConfigurable).AsArray();
return new DiagnosticDescriptor(id, title: "", messageFormat: id, category: "",
defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true,
customTags: customTags);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
/// <summary>
/// Factory for creating different kinds of <see cref="DiagnosticDescriptor"/>s for use in tests.
/// </summary>
public static class DescriptorFactory
{
/// <summary>
/// Creates a <see cref="DiagnosticDescriptor"/> with specified <see cref="DiagnosticDescriptor.Id"/>.
/// </summary>
/// <remarks>
/// Returned <see cref="DiagnosticDescriptor"/> has
/// - empty <see cref="DiagnosticDescriptor.Title"/> and <see cref="DiagnosticDescriptor.Category"/>
/// - <see cref="DiagnosticDescriptor.MessageFormat"/> set to <paramref name="id"/>
/// - <see cref="DiagnosticDescriptor.DefaultSeverity"/> set to <see cref="DiagnosticSeverity.Hidden"/>
/// - <see cref="WellKnownDiagnosticTags.NotConfigurable"/> custom tag added in <see cref="DiagnosticDescriptor.CustomTags"/>.
/// </remarks>
/// <param name="id">The value for <see cref="DiagnosticDescriptor.Id"/>.</param>
/// <param name="additionalCustomTags">Additional custom tags</param>
/// <returns>A <see cref="DiagnosticDescriptor"/> with specified <see cref="DiagnosticDescriptor.Id"/>.</returns>
public static DiagnosticDescriptor CreateSimpleDescriptor(string id, params string[] additionalCustomTags)
{
var customTags = additionalCustomTags.Concat(WellKnownDiagnosticTags.NotConfigurable).AsArray();
return new DiagnosticDescriptor(id, title: "", messageFormat: id, category: "",
defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true,
customTags: customTags);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Statements_Tests.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.Reflection
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' This class tests binding of various statements; i.e., the code in Binder_Statements.vb
'
' Tests should be added here for every construct that can be bound
' correctly, with a test that compiles, verifies, and runs code for that construct.
' Tests should also be added here for every diagnostic that can be generated.
Public Class Binder_Statements_Tests
Inherits BasicTestBase
<Fact>
Public Sub HelloWorld1()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Module M
Sub Main()
System.Console.WriteLine("Hello, world!")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world!")
End Sub
<Fact>
Public Sub HelloWorld2()
CompileAndVerify(
<compilation name="HelloWorld2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim x as object
x = 42
Console.WriteLine("Hello, world {0} {1}", 135.2.ToString(System.Globalization.CultureInfo.InvariantCulture), x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world 135.2 42")
End Sub
<Fact>
Public Sub LocalWithSimpleInitialization()
CompileAndVerify(
<compilation name="LocalWithSimpleInitialization">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String = "Hello world"
Console.WriteLine(s)
s = nothing
Console.WriteLine(s)
Dim i As Integer = 1
Console.WriteLine(i)
Dim d As Double = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
]]>)
End Sub
<Fact>
Public Sub LocalAsNew()
CompileAndVerify(
<compilation name="LocalAsNew">
<file name="a.vb">
Imports System
Class C
Sub New (msg as string)
Me.msg = msg
End Sub
Sub Report()
Console.WriteLine(msg)
End Sub
private msg as string
End Class
Module M1
Sub Main()
dim myC as New C("hello")
myC.Report()
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello")
End Sub
<Fact>
Public Sub LocalAsNewArrayError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class C
Sub New()
End Sub
End Class
Module M1
Sub Main()
' Arrays cannot be declared with 'New'.
dim c1() as new C()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
dim c1() as new C()
~~~
</expected>)
End Sub
<Fact>
Public Sub LocalAsNewArrayError001()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class X
Dim a(), b As New S
End Class
Class X1
Dim a, b() As New S
End Class
Class X2
Dim a, b(3) As New S
End Class
Class X3
Dim a, b As New S(){}
End Class
Structure S
End Structure
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
Dim a(), b As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b() As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b(3) As New S
~~~~
BC30205: End of statement expected.
Dim a, b As New S(){}
~
</expected>)
End Sub
<WorkItem(545766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545766")>
<Fact>
Public Sub LocalSameNameAsOperatorAllowed()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalSameNameAsOperatorAllowed">
<file name="a.vb">
Imports System
Class C
Public Shared Operator IsTrue(ByVal w As C) As Boolean
Dim IsTrue As Boolean = True
Return IsTrue
End Operator
Public Shared Operator IsFalse(ByVal w As C) As Boolean
Dim IsFalse As Boolean = True
Return IsFalse
End Operator
End Class
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub ParameterlessSub()
CompileAndVerify(
<compilation name="ParameterlessSub">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Hello, world")
Console.WriteLine()
Console.WriteLine("Goodbye, world")
End Sub
Sub Main()
Goo
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello, world
Goodbye, world
]]>)
End Sub
<Fact>
Public Sub CallStatement()
CompileAndVerify(
<compilation name="CallStatement">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Call without parameters")
End Sub
Sub Goo(s as string)
Console.WriteLine(s)
End Sub
Function SayHi as string
return "Hi"
End Function
Function One as integer
return 1
End Function
Sub Main()
Goo(SayHi)
goo
call goo
call goo("call with parameters")
dim i = One + One
Console.WriteLine(i)
i = One
Console.WriteLine(i)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hi
Call without parameters
Call without parameters
call with parameters
2
1
]]>)
End Sub
<Fact>
Public Sub CallStatementMethodNotFound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodNotFound">
<file name="a.vb">
Imports System
Module M1
Sub Main()
call goo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'goo' is not declared. It may be inaccessible due to its protection level.
call goo
~~~
</expected>)
End Sub
<WorkItem(538590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538590")>
<Fact>
Public Sub CallStatementNothingAsInvocationExpression_Bug_4247()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Module M1
Sub Main()
Dim myLocalArr as Integer()
Dim myLocalVar as Integer = 42
call myLocalArr(0)
call myLocalVar
call Nothing
call 911
call new Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30454: Expression is not a method.
call myLocalArr(0)
~~~~~~~~~~
BC42104: Variable 'myLocalArr' is used before it has been assigned a value. A null reference exception could result at runtime.
call myLocalArr(0)
~~~~~~~~~~
BC30454: Expression is not a method.
call myLocalVar
~~~~~~~~~~
BC30454: Expression is not a method.
call Nothing
~~~~~~~
BC30454: Expression is not a method.
call 911
~~~
BC30454: Expression is not a method.
call new Integer
~~~~~~~~~~~
</expected>)
End Sub
' related to bug 4247
<Fact>
Public Sub CallStatementNamespaceAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Namespace N1.N2
Module M1
Sub Main()
call N1
call N1.N2
End Sub
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30112: 'N1' is a namespace and cannot be used as an expression.
call N1
~~
BC30112: 'N1.N2' is a namespace and cannot be used as an expression.
call N1.N2
~~~~~
</expected>)
End Sub
' related to bug 4247
<WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
<Fact>
Public Sub CallStatementTypeAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Class Class1
End Class
Module M1
Sub Main()
call Class1
call Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30109: 'Class1' is a class type and cannot be used as an expression.
call Class1
~~~~~~
BC30110: 'Integer' is a structure type and cannot be used as an expression.
call Integer
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AssignmentStatement()
CompileAndVerify(
<compilation name="AssignmentStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String
s = "Hello world"
Console.WriteLine(s)
Dim i As Integer
i = 1
Console.WriteLine(i)
Dim d As Double
d = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
d = i
Console.WriteLine(d)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
1
]]>)
End Sub
<Fact>
Public Sub FieldAssignmentStatement()
CompileAndVerify(
<compilation name="FieldAssignmentStatement">
<file name="a.vb">
Imports System
Class C1
public i as integer
End class
Structure S1
public s as string
End Structure
Module M1
Sub Main()
dim myC as C1 = new C1
myC.i = 10
Console.WriteLine(myC.i)
dim myS as S1 = new S1
myS.s = "a"
Console.WriteLine(MyS.s)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
10
a
]]>)
End Sub
<Fact>
Public Sub AssignmentWithBadLValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AssignmentWithBadLValue">
<file name="a.vb">
Imports System
Module M1
Function f as integer
return 0
End function
Sub s
End Sub
Sub Main()
f = 0
s = 1
dim i as integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
f = 0
~
BC30068: Expression is a value and therefore cannot be the target of an assignment.
s = 1
~
BC42024: Unused local variable: 'i'.
dim i as integer
~
</expected>)
End Sub
<Fact>
Public Sub MultilineIfStatement1()
CompileAndVerify(
<compilation name="MultilineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
Dim cond2 As Boolean
Dim cond3 As Boolean
cond = True
cond2 = True
cond3 = True
If cond Then
Console.WriteLine("1. ThenPart")
End If
If cond Then
Console.WriteLine("2. ThenPart")
Else
Console.WriteLine("2. ElsePart")
End If
If cond Then
Console.WriteLine("3. ThenPart")
Else If cond2
Console.WriteLine("3. ElseIfPart")
End If
If cond Then
Console.WriteLine("4. ThenPart")
Else If cond2
Console.WriteLine("4. ElseIf1Part")
Else If cond3
Console.WriteLine("4. ElseIf2Part")
Else
Console.WriteLine("4. ElsePart")
End If
cond = False
If cond Then
Console.WriteLine("5. ThenPart")
End If
If cond Then
Console.WriteLine("6. ThenPart")
Else
Console.WriteLine("6. ElsePart")
End If
If cond Then
Console.WriteLine("7. ThenPart")
Else If cond2
Console.WriteLine("7. ElseIfPart")
End If
If cond Then
Console.WriteLine("8. ThenPart")
Else If cond2
Console.WriteLine("8. ElseIf1Part")
Else If cond3
Console.WriteLine("8. ElseIf2Part")
Else
Console.WriteLine("8. ElsePart")
End If
cond2 = false
If cond Then
Console.WriteLine("9. ThenPart")
Else If cond2
Console.WriteLine("9. ElseIfPart")
End If
If cond Then
Console.WriteLine("10. ThenPart")
Else If cond2
Console.WriteLine("10. ElseIf1Part")
Else If cond3
Console.WriteLine("10. ElseIf2Part")
Else
Console.WriteLine("10. ElsePart")
End If
cond3 = false
If cond Then
Console.WriteLine("11. ThenPart")
Else If cond2
Console.WriteLine("11. ElseIf1Part")
Else If cond3
Console.WriteLine("11. ElseIf2Part")
Else
Console.WriteLine("11. ElsePart")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPart
3. ThenPart
4. ThenPart
6. ElsePart
7. ElseIfPart
8. ElseIf1Part
10. ElseIf2Part
11. ElsePart
]]>)
End Sub
<Fact>
Public Sub SingleLineIfStatement1()
CompileAndVerify(
<compilation name="SingleLineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
cond = True
If cond Then Console.WriteLine("1. ThenPart")
If cond Then Console.WriteLine("2. ThenPartA"): COnsole.WriteLine("2. ThenPartB")
If cond Then Console.WriteLine("3. ThenPartA"): COnsole.WriteLine("3. ThenPartB") Else Console.WriteLine("3. ElsePartA"): Console.WriteLine("3. ElsePartB")
If cond Then Console.WriteLine("4. ThenPart") Else Console.WriteLine("4. ElsePartA"): Console.WriteLine("4. ElsePartB")
If cond Then Console.WriteLine("5. ThenPartA"): Console.WriteLine("5. ThenPartB") Else Console.WriteLine("5. ElsePart")
If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart")
cond = false
If cond Then Console.WriteLine("7. ThenPart")
If cond Then Console.WriteLine("8. ThenPartA"): COnsole.WriteLine("8. ThenPartB")
If cond Then Console.WriteLine("9. ThenPart"): COnsole.WriteLine("9. ThenPartB") Else Console.WriteLine("9. ElsePartA"): Console.WriteLine("9. ElsePartB")
If cond Then Console.WriteLine("10. ThenPart") Else Console.WriteLine("10. ElsePartA"): Console.WriteLine("10. ElsePartB")
If cond Then Console.WriteLine("11. ThenPartA"): Console.WriteLine("11. ThenPartB") Else Console.WriteLine("11. ElsePart")
If cond Then Console.WriteLine("12. ThenPart") Else Console.WriteLine("12. ElsePart")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPartA
2. ThenPartB
3. ThenPartA
3. ThenPartB
4. ThenPart
5. ThenPartA
5. ThenPartB
6. ThenPart
9. ElsePartA
9. ElsePartB
10. ElsePartA
10. ElsePartB
11. ElsePart
12. ElsePart
]]>)
End Sub
<Fact>
Public Sub DoLoop1()
CompileAndVerify(
<compilation name="DoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do While breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop2()
CompileAndVerify(
<compilation name="DoLoop2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do Until breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop3()
CompileAndVerify(
<compilation name="DoLoop3">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop While breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop4()
CompileAndVerify(
<compilation name="DoLoop4">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop Until breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub WhileLoop1()
CompileAndVerify(
<compilation name="WhileLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
While not breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
End While
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub ExitContinueDoLoop1()
CompileAndVerify(
<compilation name="ExitContinueDoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
dim continueLoop as Boolean
breakLoop = True: continueLoop = true
Do While breakLoop
Console.WriteLine("Stmt1")
If continueLoop Then
Console.WriteLine("Continuing")
continueLoop = false
Continue Do
End If
Console.WriteLine("Exiting")
Exit Do
Console.WriteLine("Stmt2")
Loop
Console.WriteLine("After Loop")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Continuing
Stmt1
Exiting
After Loop
]]>)
End Sub
<Fact>
Public Sub ExitSub()
CompileAndVerify(
<compilation name="ExitSub">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = True
Do While breakLoop
Console.WriteLine("Stmt1")
Console.WriteLine("Exiting")
Exit Sub
Console.WriteLine("Stmt2") 'should not output
Loop
Console.WriteLine("After Loop") 'should not output
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Exiting
]]>)
End Sub
<Fact>
Public Sub ExitFunction()
CompileAndVerify(
<compilation name="ExitFunction">
<file name="a.vb">
Imports System
Module M1
Function Fact(i as integer) as integer
fact = 1
do
if i <= 0 then
exit function
else
fact = i * fact
i = i - 1
end if
loop
End Function
Sub Main()
Console.WriteLine(Fact(0))
Console.WriteLine(Fact(3))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
6
]]>)
End Sub
<Fact>
Public Sub BadExit()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadExit">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Exit Do ' ok
Exit For
Exit Try
Exit Select
Exit While
Loop
Exit Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30096: 'Exit For' can only appear inside a 'For' statement.
Exit For
~~~~~~~~
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
BC30099: 'Exit Select' can only appear inside a 'Select' statement.
Exit Select
~~~~~~~~~~~
BC30097: 'Exit While' can only appear inside a 'While' statement.
Exit While
~~~~~~~~~~
BC30089: 'Exit Do' can only appear inside a 'Do' statement.
Exit Do ' outside loop
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadContinue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadContinue">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Continue Do ' ok
Continue For
Continue While
Loop
Continue Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30783: 'Continue For' can only appear inside a 'For' statement.
Continue For
~~~~~~~~~~~~
BC30784: 'Continue While' can only appear inside a 'While' statement.
Continue While
~~~~~~~~~~~~~~
BC30782: 'Continue Do' can only appear inside a 'Do' statement.
Continue Do ' outside loop
~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Return1()
CompileAndVerify(
<compilation name="Return1">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
F1 = 1
End Function
Function F2 as Integer
if true then
F2 = 2
else
return 3
end if
End Function
Function F3 as Integer
return 3
End Function
Sub S1
return
End Sub
Sub Main()
dim result as integer
result = F1()
Console.WriteLine(result)
result = F2()
Console.WriteLine(result)
result = F3()
Console.WriteLine(result)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
2
3
]]>)
End Sub
<Fact>
Public Sub BadReturn()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadReturn">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
return
End Function
Sub S1
return 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30654: 'Return' statement in a Function, Get, or Operator must return a value.
return
~~~~~~
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NoReturnUnreachableEnd()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoReturnUnreachableEnd">
<file name="a.vb">
Imports System
Module M1
Function goo() As Boolean
While True
End While
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadArrayInitWithExplicitArraySize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(3) as integer = 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
dim a(3) as integer = 1
~~~~
BC30311: Value of type 'Integer' cannot be converted to 'Integer()'.
dim a(3) as integer = 1
~
</expected>)
End Sub
<Fact>
Public Sub BadArrayWithNegativeSize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-3) as integer
dim b = new integer(-3){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30611: Array dimensions cannot have a negative size.
dim a(-3) as integer
~~
BC30611: Array dimensions cannot have a negative size.
dim b = new integer(-3){}
~~
</expected>)
End Sub
<Fact>
Public Sub ArrayWithMinusOneUpperBound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-1) as integer
dim b = new integer(-1){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(542987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542987")>
<Fact()>
Public Sub MultiDimensionalArrayWithTooFewInitializers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MultiDimensionalArrayWithTooFewInitializers">
<file name="Program.vb">
Module Program
Sub Main()
Dim x = New Integer(0, 1) {{}}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30567: Array initializer is missing 2 elements.
Dim x = New Integer(0, 1) {{}}
~~
</expected>)
End Sub
<WorkItem(542988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542988")>
<Fact()>
Public Sub Max32ArrayDimensionsAreAllowed()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Max32ArrayDimensionsAreAllowed">
<file name="Program.vb">
Module Program
Sub Main()
Dim z1(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim z2(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim x1 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim x2 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim y1 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
Dim y2 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
End Sub
End Module
</file>
</compilation>).
VerifyDiagnostics(
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"))
End Sub
<Fact>
Public Sub GotoIf()
CompileAndVerify(
<compilation name="GotoIf">
<file name="a.vb">
Imports System
Module M1
Sub GotoIf()
GoTo l1
If False Then
l1:
Console.WriteLine("Jump into If")
End If
End Sub
Sub GotoWhile()
GoTo l1
While False
l1:
Console.WriteLine("Jump into While")
End While
End Sub
Sub GotoDo()
GoTo l1
Do While False
l1:
Console.WriteLine("Jump into Do")
Loop
End Sub
Sub GotoSelect()
Dim i As Integer = 0
GoTo l1
Select Case i
Case 0
l1:
Console.WriteLine("Jump into Select")
End Select
End Sub
Sub Main()
GotoIf()
GotoWhile()
GotoDo()
GotoSelect()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Jump into If
Jump into While
Jump into Do
Jump into Select
]]>)
End Sub
<Fact()>
Public Sub GotoIntoBlockErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoIntoBlockErrors">
<file name="a.vb">
Imports System
Module M1
Sub GotoFor()
For i as Integer = 0 To 10
l1:
Console.WriteLine()
Next
GoTo l1
End Sub
Sub GotoWith()
Dim c1 = New C()
With c1
l1:
Console.WriteLine()
End With
GoTo l1
End Sub
Sub GotoUsing()
Using c1 as IDisposable = nothing
l1:
Console.WriteLine()
End Using
GoTo l1
End Sub
Sub GotoTry()
Try
l1:
Console.WriteLine()
Finally
End Try
GoTo l1
End Sub
Sub GotoLambda()
Dim x = Sub()
l1:
End Sub
GoTo l1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30757: 'GoTo l1' is not valid because 'l1' is inside a 'For' or 'For Each' statement that does not contain this statement.
GoTo l1
~~
BC30002: Type 'C' is not defined.
Dim c1 = New C()
~
BC30756: 'GoTo l1' is not valid because 'l1' is inside a 'With' statement that does not contain this statement.
GoTo l1
~~
BC36009: 'GoTo l1' is not valid because 'l1' is inside a 'Using' statement that does not contain this statement.
GoTo l1
~~
BC30754: 'GoTo l1' is not valid because 'l1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo l1
~~
BC30132: Label 'l1' is not defined.
GoTo l1
~~
</expected>)
End Sub
<Fact()>
Public Sub GotoDecimalLabels()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoDecimalLabels">
<file name="a.vb">
Imports System
Module M
Sub Main()
1 : Goto &H2
2 : Goto 01
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(543381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543381")>
<Fact()>
Public Sub GotoUndefinedLabel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoUndefinedLabel">
<file name="a.vb">
Imports System
Class c1
Shared Sub Main()
GoTo lab1
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30132: Label 'lab1' is not defined.
GoTo lab1
~~~~
</expected>)
End Sub
<WorkItem(538574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538574")>
<Fact()>
Public Sub ArrayModifiersOnVariableAndType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayModifiersOnVariableAndType">
<file name="a.vb">
Imports System
Module M1
public a() as integer()
public b(1) as integer()
Sub S1
dim a() as integer() = nothing
dim b(1) as string()
End Sub
Sub S2(x() as integer())
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors>
BC31087: Array modifiers cannot be specified on both a variable and its type.
public a() as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
public b(1) as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim a() as integer() = nothing
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim b(1) as string()
~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
Sub S2(x() as integer())
~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Bug6663()
' Test dependent on referenced mscorlib, but NOT system.dll.
Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="Bug6663">
<file name="a.vb">
Imports System
Module Program
Sub Main()
Console.WriteLine("".ToString() = "".ToString())
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe)
CompileAndVerify(comp, expectedOutput:="True")
End Sub
<WorkItem(540390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540390")>
<Fact()>
Public Sub Bug6637()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Imports System
Module M1
Sub Main()
Dim a(3) As Integer
For i = 0 To 3
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = 0 To 3
~
</expected>)
End Sub
<WorkItem(540412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540412")>
<Fact()>
Public Sub Bug6662()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Class C
Shared Sub M()
For i = Nothing To 10
Dim d as System.Action = Sub() i = i + 1
Next
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = Nothing To 10
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
</expected>)
End Sub
<WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")>
<Fact()>
Public Sub ExtTryFromFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Class BaseClass
Function Method() As String
Dim x = New Integer() {}
Try
Exit Try
Catch ex1 As Exception When True
Exit Try
Finally
Exit Try
End Try
Return "x"
End Function
End Class
Class DerivedClass
Inherits BaseClass
Shared Sub Main()
End Sub
End Class
</file>
</compilation>, {SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotLocal">
<file name="goo.vb">
Module M1
Private ex as System.Exception
Sub Main()
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact(), WorkItem(651622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651622")>
Public Sub Bug651622()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="goo.vb">
Module Module1
Sub Main()
Try
Catch Main
Catch x as System.Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Main' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Main
~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchStatic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchStatic">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Static ex as exception = nothing
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchUndeclared()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchUndeclared">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Try
' Explicit off does not have effect on Catch - ex is still undefined.
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'ex' is not declared. It may be inaccessible due to its protection level.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Dim ex as String = "qq"
Try
Catch ex
End Try
Try
Catch ex1 as String
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex
~~
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex1 as String
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotVariableOrParameter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotVariableOrParameter">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Goo
End Sub
Sub Main()
Try
Catch Goo
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Goo' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch ex
Catch ex1 as Exception
Catch
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch
Catch ex
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex
~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When true
Catch ex
' filter does NOT make this reachable.
Catch ex1 as Exception When true
' implicitly this is a "Catch ex As Exception When true" so still unreachable
Catch When true
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception When true
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch When true
~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchOverlapped()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex As SystemException = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When True
Catch ex
' filter does NOT make this reachable.
Catch ex1 As ArgumentException When True
' implicitly this is a "Catch ex As Exception When true"
Catch When True
' this is ok since it is not derived from SystemException
' and catch above has a filter
Catch ex1 As ApplicationException
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'SystemException'.
Catch ex1 As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchShadowing()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Dim field As String
Function Goo(Of T)(ex As Exception) As Exception
Dim ex1 As SystemException = Nothing
Try
Dim ex2 As Exception = nothing
Catch ex As Exception
Catch ex1 As Exception
Catch Goo As ArgumentException When True
' this is ok
Catch ex2 As exception
Dim ex3 As exception = nothing
'this is ok
Catch ex3 As ApplicationException
' this is ok
Catch field As Exception
End Try
return nothing
End Function
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30734: 'ex' is already declared as a parameter of this method.
Catch ex As Exception
~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 As Exception
~~~~~~~~~~~~~~~~~~~~~~
BC30616: Variable 'ex1' hides a variable in an enclosing block.
Catch ex1 As Exception
~~~
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'Exception'.
Catch Goo As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30290: Local variable cannot have the same name as the function containing it.
Catch Goo As ArgumentException When True
~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex2 As exception
~~~~~~~~~~~~~~~~~~~~~~
BC42029: 'Catch' block never reached, because 'ApplicationException' inherits from 'Exception'.
Catch ex3 As ApplicationException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch field As Exception
~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(837820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837820")>
<Fact()>
Public Sub CatchShadowingGeneric()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Class cls3(Of T As NullReferenceException)
Sub scen3()
Try
Catch ex As T
Catch ex As NullReferenceException
End Try
End Sub
Sub scen4()
Try
Catch ex As NullReferenceException
'COMPILEWarning: BC42029 ,"Catch ex As T"
Catch ex As T
End Try
End Sub
End Class
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'T' inherits from 'NullReferenceException'.
Catch ex As T
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoOutOfFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoOutOfFinally">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
l1:
Try
Finally
try
goto l1
catch
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
goto l1
~~
</expected>)
End Sub
<Fact()>
Public Sub BranchOutOfFinally1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BranchOutOfFinally1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
for i as integer = 1 to 10
Try
Finally
continue for
End Try
Next
End Sub
Function Goo() as integer
l1:
Try
Finally
try
return 1
catch
return 1
End Try
End Try
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
continue for
~~~~~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
Catch ex As Exception
l1:
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
l1:
Catch ex As Exception
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInLateAddressOf()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Option Strict Off
Imports System
Module Program
Delegate Sub d1(ByRef x As Integer, y As Integer)
Sub Main()
Dim obj As Object '= New cls1
Dim o As d1 = AddressOf obj.goo
Dim l As Integer = 0
o(l, 2)
Console.WriteLine(l)
End Sub
Class cls1
Shared Sub goo(ByRef x As Integer, y As Integer)
x = 42
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim o As d1 = AddressOf obj.goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Dim B as StackOverflowException
Dim C as Exception
Try
A = new ApplicationException
B = new StackOverflowException
C = new Exception
Console.Writeline(A) 'this is ok
Catch ex as NullReferenceException When A.Message isnot nothing
Catch ex as DivideByZeroException
Console.Writeline(B)
Finally
Console.Writeline(C)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Catch ex as NullReferenceException When A.Message isnot nothing
~
BC42104: Variable 'B' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(B)
~
BC42104: Variable 'C' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(C)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
' ok , A is assigned in the filter and in the catch
Catch A When A.Message isnot nothing
Console.Writeline(A)
Catch ex as Exception
A = new ApplicationException
Finally
'error
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter2">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter3">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter4">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
Finally
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Exception
Get
Return New Exception
End Get
End Property
WriteOnly Property Boo As Exception
Set(value As Exception)
End Set
End Property
Sub Main()
Throw Moo
Throw Boo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30524: Property 'Boo' is 'WriteOnly'.
Throw Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly e as new Exception
ReadOnly s as string = "qq"
Sub Main()
Throw e
Throw s
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30665: 'Throw' operand must derive from 'System.Exception'.
Throw s
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RethrowNotInCatch()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RethrowNotInCatch">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Throw
Try
Throw
Catch ex As Exception
Throw
Dim a As Action = Sub()
ex.ToString()
Throw
End Sub
Try
Throw
Catch
Throw
Finally
Throw
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ForNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Integer
Get
Return 1
End Get
End Property
WriteOnly Property Boo As integer
Set(value As integer)
End Set
End Property
Sub Main()
For Moo = 1 to Moo step Moo
Next
For Boo = 1 to Boo step Boo
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Moo = 1 to Moo step Moo
~~~
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CustomDatatypeForLoop()
Dim source =
<compilation>
<file name="goo.vb"><![CDATA[
Imports System
Module Module1
Public Sub Main()
Dim x As New c1
For x = 1 To 3
Console.WriteLine("hi")
Next
End Sub
End Module
Public Class c1
Public val As Integer
Public Shared Widening Operator CType(ByVal arg1 As Integer) As c1
Console.WriteLine("c1::CType(Integer) As c1")
Dim c As New c1
c.val = arg1 'what happens if this is last statement?
Return c
End Operator
Public Shared Widening Operator CType(ByVal arg1 As c1) As Integer
Console.WriteLine("c1::CType(c1) As Integer")
Dim x As Integer
x = arg1.val
Return x
End Operator
Public Shared Operator +(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::+(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val + arg2.val
Return c
End Operator
Public Shared Operator -(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::-(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val - arg2.val
Return c
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::>=(c1, Integer) As Boolean")
If arg1.val >= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::<=(c1, Integer) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::<=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::>=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::<=(c1, c1) As Boolean")
If arg1.val <= arg2.val Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::>=(c1, c1) As Boolean")
If arg1.val >= arg2.val Then
Return True
Else
Return False
End If
End Operator
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, <![CDATA[c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::-(c1, c1) As c1
c1::>=(c1, c1) As Boolean
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
]]>)
End Sub
<Fact()>
Public Sub SelectCase1_SwitchTable()
CompileAndVerify(
<compilation name="SelectCase1">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case 0
Console.WriteLine("Equal to 0")
Case 1, 2, 3, 4, 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9, 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<Fact()>
Public Sub SelectCase2_IfList()
CompileAndVerify(
<compilation name="SelectCase2">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Less than 1
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<WorkItem(542156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542156")>
<Fact()>
Public Sub ImplicitVarInRedim()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Option Explicit Off
Module M
Sub Main()
Redim x(10)
System.Console.WriteLine("OK")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="OK")
End Sub
<Fact()>
Public Sub EndStatementsInMethodBodyShouldNotThrowNYI()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EndStatementsInMethodBodyShouldNotThrowNYI">
<file name="a.vb">
Namespace N1
Public Class C1
Public Sub S1()
for i as integer = 23 to 42
next
next
do
loop while true
loop
end if
end select
end try
end using
end while
end with
end synclock
Try
Catch ex As System.Exception
End Try
catch
Try
Catch ex As System.Exception
finally
finally
End Try
finally
End Sub
Public Sub S2
end namespace
end module
end class
end structure
end interface
end enum
end function
end operator
end property
end get
end set
end event
end addhandler
end removehandler
end raiseevent
End Sub
end Class
end Namespace
Namespace N2
Class C2
function F1() as integer
end sub
return 42
end function
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30481: 'Class' statement must end with a matching 'End Class'.
Public Class C1
~~~~~~~~~~~~~~~
BC30092: 'Next' must be preceded by a matching 'For'.
next
~~~~
BC30091: 'Loop' must be preceded by a matching 'Do'.
loop
~~~~
BC30087: 'End If' must be preceded by a matching 'If'.
end if
~~~~~~
BC30088: 'End Select' must be preceded by a matching 'Select Case'.
end select
~~~~~~~~~~
BC30383: 'End Try' must be preceded by a matching 'Try'.
end try
~~~~~~~
BC36007: 'End Using' must be preceded by a matching 'Using'.
end using
~~~~~~~~~
BC30090: 'End While' must be preceded by a matching 'While'.
end while
~~~~~~~~~
BC30093: 'End With' must be preceded by a matching 'With'.
end with
~~~~~~~~
BC30674: 'End SyncLock' must be preceded by a matching 'SyncLock'.
end synclock
~~~~~~~~~~~~
BC30380: 'Catch' cannot appear outside a 'Try' statement.
catch
~~~~~
BC30381: 'Finally' can only appear once in a 'Try' statement.
finally
~~~~~~~
BC30382: 'Finally' cannot appear outside a 'Try' statement.
finally
~~~~~~~
BC30026: 'End Sub' expected.
Public Sub S2
~~~~~~~~~~~~~
BC30622: 'End Module' must be preceded by a matching 'Module'.
end module
~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end class
~~~~~~~~~
BC30621: 'End Structure' must be preceded by a matching 'Structure'.
end structure
~~~~~~~~~~~~~
BC30252: 'End Interface' must be preceded by a matching 'Interface'.
end interface
~~~~~~~~~~~~~
BC30184: 'End Enum' must be preceded by a matching 'Enum'.
end enum
~~~~~~~~
BC30430: 'End Function' must be preceded by a matching 'Function'.
end function
~~~~~~~~~~~~
BC33007: 'End Operator' must be preceded by a matching 'Operator'.
end operator
~~~~~~~~~~~~
BC30431: 'End Property' must be preceded by a matching 'Property'.
end property
~~~~~~~~~~~~
BC30630: 'End Get' must be preceded by a matching 'Get'.
end get
~~~~~~~
BC30632: 'End Set' must be preceded by a matching 'Set'.
end set
~~~~~~~
BC31123: 'End Event' must be preceded by a matching 'Custom Event'.
end event
~~~~~~~~~
BC31124: 'End AddHandler' must be preceded by a matching 'AddHandler' declaration.
end addhandler
~~~~~~~~~~~~~~
BC31125: 'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.
end removehandler
~~~~~~~~~~~~~~~~~
BC31126: 'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.
end raiseevent
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End Sub
~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end Class
~~~~~~~~~
BC30623: 'End Namespace' must be preceded by a matching 'Namespace'.
end Namespace
~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
end sub
~~~~~~~
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub AddHandlerMissingStuff()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload,
AddHandler , del
AddHandler
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30201: Expression expected.
AddHandler v.DomainUnload,
~
BC30201: Expression expected.
AddHandler , del
~
BC30196: Comma expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerUninitialized()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
' no warnings here, variable is used
Dim del As System.EventHandler
' warning here
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'del' is used before it has been assigned a value. A null reference exception could result at runtime.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNotSimple()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' real event with arg list
AddHandler (v.DomainUnload()), del
' not an event
AddHandler (v.GetType()), del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.DomainUnload()), del
~~~~~~~~~~~~~~~~
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.GetType()), del
~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerLambda()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim v = AppDomain.CreateDomain("qq")
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
AppDomain.Unload(v)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42326: Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerNotEvent()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' not an event
AddHandler (v.GetType), del
' not anything
AddHandler v.GetTyp, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30676: 'GetType' is not an event of 'AppDomain'.
AddHandler (v.GetType), del
~~~~~~~
BC30456: 'GetTyp' is not a member of 'AppDomain'.
AddHandler v.GetTyp, del
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNoConversion()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim v = AppDomain.CreateDomain("qq")
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
AddHandler v.DomainUnload, AddressOf H
Dim del as Action(of Object, EventArgs) = Sub(sender As Object, a As EventArgs) Console.Write("unload")
AddHandler v.DomainUnload, del
End Sub
Sub H(i as integer)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36670: Nested sub does not have a signature that is compatible with delegate 'EventHandler'.
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31143: Method 'Public Sub H(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As EventArgs)'.
AddHandler v.DomainUnload, AddressOf H
~
BC30311: Value of type 'Action(Of Object, EventArgs)' cannot be converted to 'EventHandler'.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub LegalGotoCasesTryCatchFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Module M1
Sub Main()
dim x1 = function()
labelOK6:
goto labelok7
if true then
goto labelok6
labelok7:
end if
return 23
end function
dim x2 = sub()
labelOK8:
goto labelok9
if true then
goto labelok8
labelok9:
end if
end sub
Try
Goto LabelOK1
LabelOK1:
Catch
Goto LabelOK2
LabelOK2:
Try
goto LabelOK1
goto LabelOK2:
LabelOK5:
Catch
goto LabelOK1
goto LabelOK5
goto LabelOK2
Finally
End Try
Finally
Goto LabelOK3
LabelOK3:
End Try
Exit Sub
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")>
<Fact()>
Public Sub Bug10583()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Try
GoTo label
GoTo label5
Catch ex As Exception
label:
Finally
label5:
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label
~~~~~
BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label5
~~~~~~
</expected>)
End Sub
<WorkItem(543060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543060")>
<Fact()>
Public Sub SelectCase_ImplicitOperator()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Class X
Public Shared Operator =(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Operator <>(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Widening Operator CType(expandedName As String) As X
Return New X()
End Operator
End Class
Sub Main()
End Sub
Sub Test(x As X)
Select Case x
Case "a"
Console.WriteLine("Equal to a")
Case "s"
Console.WriteLine("Equal to A")
Case "3"
Console.WriteLine("Error")
Case "5"
Console.WriteLine("Error")
Case "6"
Console.WriteLine("Error")
Case "9"
Console.WriteLine("Error")
Case "11"
Console.WriteLine("Error")
Case "12"
Console.WriteLine("Error")
Case "13"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
</expected>)
End Sub
<WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")>
<Fact()>
Public Sub Binding_Return_As_Declaration()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Class Program
Shared Main()
Return Nothing
End sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30689: Statement cannot appear outside of a method body.
Return Nothing
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End sub
~~~~~~~
</expected>)
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
While (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
While (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
If (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
If (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Try
Catch
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Try
Catch
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Do
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Do
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Else
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Else
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(544465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544465")>
<Fact()>
Public Sub DuplicateNullableLocals()
Dim source =
<compilation>
<file name="a.vb">
Option Explicit Off
Module M
Sub S()
Dim A? As Integer = 1
Dim A? As Integer? = 1
End Sub
End Module
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_CantSpecifyNullableOnBoth, "As Integer?"),
Diagnostic(ERRID.ERR_DuplicateLocals1, "A?").WithArguments("A"))
End Sub
<WorkItem(544431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544431")>
<Fact()>
Public Sub IllegalModifiers()
Dim source =
<compilation>
<file name="a.vb">
Class C
Public Custom E
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfCustomModifier, "Custom"))
End Sub
<Fact()>
Public Sub InvalidCode_ConstInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Const Interface
</file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors>
BC30397: 'Const' is not valid on an Interface declaration.
Const Interface
~~~~~
BC30253: 'Interface' must end with a matching 'End Interface'.
Const Interface
~~~~~~~~~~~~~~~
BC30203: Identifier expected.
Const Interface
~
</errors>)
End Sub
<WorkItem(545196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545196")>
<Fact()>
Public Sub InvalidCode_Event()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Event
</file>
</compilation>)
compilation.AssertTheseParseDiagnostics(<errors>
BC30203: Identifier expected.
Event
~
</errors>)
End Sub
<Fact>
Public Sub StopAndEnd_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim m = GetType(Module1)
System.Console.WriteLine(m.GetMethod("TestEnd").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("TestStop").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("Dummy").GetMethodImplementationFlags)
Try
System.Console.WriteLine("Before End")
TestEnd()
System.Console.WriteLine("After End")
Finally
System.Console.WriteLine("In Finally")
End Try
System.Console.WriteLine("After Try")
End Sub
Sub TestEnd()
End
End Sub
Sub TestStop()
Stop
End Sub
Sub Dummy()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation,
symbolValidator:=Sub(m As ModuleSymbol)
Dim m1 = m.ContainingAssembly.GetTypeByMetadataName("Module1")
Assert.Equal(MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization,
DirectCast(m1.GetMembers("TestEnd").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("TestStop").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("Dummy").Single(), PEMethodSymbol).ImplementationAttributes)
End Sub)
compilationVerifier.VerifyIL("Module1.TestEnd",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp()"
IL_0005: ret
}
]]>)
compilationVerifier.VerifyIL("Module1.TestStop",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub System.Diagnostics.Debugger.Break()"
IL_0005: ret
}
]]>)
compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary))
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
End
~~~
</expected>)
End Sub
<Fact>
Public Sub StopAndEnd_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim x As Object
Dim y As Object
Stop
x.ToString()
End
y.ToString()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
x.ToString()
~
</expected>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub StopAndEnd_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public state As Integer = 0
Public Sub Main()
On Error GoTo handler
Throw New NullReferenceException()
Stop
Console.WriteLine("Done")
Return
handler:
Console.WriteLine(Microsoft.VisualBasic.Information.Err.GetException().GetType())
If state = 1 Then
Resume
End If
Resume Next
End Sub
End Module
Namespace System.Diagnostics
Public Class Debugger
Public Shared Sub Break()
Console.WriteLine("In Break")
Select Case Module1.state
Case 0, 1
Module1.state += 1
Case Else
Console.WriteLine("Test issue!!!")
Return
End Select
Throw New NotSupportedException()
End Sub
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
System.NullReferenceException
In Break
System.NotSupportedException
In Break
System.NotSupportedException
Done
]]>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIfWithDll()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
If True Then End Else Console.WriteLine("Test")
~~~
</expected>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithMultiLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then
End
Else
Console.WriteLine("Test")
End If
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(660010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/660010")>
<Fact>
Public Sub Regress660010()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Inherits value
End C
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=XmlReferences)
AssertTheseDiagnostics(compilation,
<expected>
BC30481: 'Class' statement must end with a matching 'End Class'.
Class C
~~~~~~~
BC30002: Type 'value' is not defined.
Inherits value
~~~~~
BC30678: 'End' statement not valid.
End C
~~~
</expected>)
End Sub
<WorkItem(718436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718436")>
<Fact>
Public Sub NotYetImplementedStatement()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Sub M()
Inherits A
Implements I
Imports X
Option Strict On
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source)
AssertTheseDiagnostics(compilation,
<expected>
BC30024: Statement is not valid inside a method.
Inherits A
~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Implements I
~~~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Imports X
~~~~~~~~~
BC30024: Statement is not valid inside a method.
Option Strict On
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleRemoveAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method family specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected RemoveHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleAddAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method family specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected AddHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
AddHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub EventTypeIsNotADelegate()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::remove_Test
.event E1 Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC37223: 'Public Event Test As E1' is an unsupported event.
AddHandler e.Test, e
~~~~~~
BC37223: 'Public Event Test As E1' is an unsupported event.
RemoveHandler e.Test, e
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test() cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test()
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action, class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test() cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test()
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action, class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub NonVoidAccessors()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance int32
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance int32
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance int32 E1::add_Test(class [mscorlib]System.Action)
.removeon instance int32 E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation1, expectedOutput:="add_Test
remove_Test")
End Sub
''' <summary>
''' Tests that FULLWIDTH COLON (U+FF1A) is never parsed as part of XML name,
''' but is instead parsed as a statement separator when it immediately follows an XML name.
''' If the next token is an identifier or keyword, it should be parsed as a separate statement.
''' An XML name should never include more than one colon.
''' See also: http://fileformat.info/info/unicode/char/FF1A
''' </summary>
<Fact>
<WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")>
Public Sub FullWidthColonInXmlNames()
' FULLWIDTH COLON is represented by "~" below
Dim source = <![CDATA[
Imports System
Module M
Sub Main()
Test1()
Test2()
Test3()
Test4()
Test5()
Test6()
Test7()
Test8()
End Sub
Sub Test1()
Console.WriteLine(">1")
Dim x = <a/>.@xml:goo
Console.WriteLine("<1")
End Sub
Sub Test2()
Console.WriteLine(">2")
Dim x = <a/>.@xml:goo:goo
Console.WriteLine("<2")
End Sub
Sub Test3()
Console.WriteLine(">3")
Dim x = <a/>.@xml:return
Console.WriteLine("<3")
End Sub
Sub Test4()
Console.WriteLine(">4")
Dim x = <a/>.@xml:return:return
Console.WriteLine("<4")
End Sub
Sub Test5()
Console.WriteLine(">5")
Dim x = <a/>.@xml~goo
Console.WriteLine("<5")
End Sub
Sub Test6()
Console.WriteLine(">6")
Dim x = <a/>.@xml~return
Console.WriteLine("<6")
End Sub
Sub Test7()
Console.WriteLine(">7")
Dim x = <a/>.@xml~goo~return
Console.WriteLine("<7")
End Sub
Sub Test8()
Console.WriteLine(">8")
Dim x = <a/>.@xml~REM
Console.WriteLine("<8")
End Sub
Sub goo
Console.WriteLine("goo")
End Sub
Sub [return]
Console.WriteLine("return")
End Sub
Sub [REM]
Console.WriteLine("REM")
End Sub
End Module]]>.Value.Replace("~"c, SyntaxFacts.FULLWIDTH_COLON)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="FullWidthColonInXmlNames">
<file name="M.vb"><%= source %></file>
</compilation>,
XmlReferences,
TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
>1
<1
>2
goo
<2
>3
<3
>4
>5
goo
<5
>6
>7
goo
>8
<8]]>.Value.Replace(vbLf, Environment.NewLine))
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Reflection
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' This class tests binding of various statements; i.e., the code in Binder_Statements.vb
'
' Tests should be added here for every construct that can be bound
' correctly, with a test that compiles, verifies, and runs code for that construct.
' Tests should also be added here for every diagnostic that can be generated.
Public Class Binder_Statements_Tests
Inherits BasicTestBase
<Fact>
Public Sub HelloWorld1()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Module M
Sub Main()
System.Console.WriteLine("Hello, world!")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world!")
End Sub
<Fact>
Public Sub HelloWorld2()
CompileAndVerify(
<compilation name="HelloWorld2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim x as object
x = 42
Console.WriteLine("Hello, world {0} {1}", 135.2.ToString(System.Globalization.CultureInfo.InvariantCulture), x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Hello, world 135.2 42")
End Sub
<Fact>
Public Sub LocalWithSimpleInitialization()
CompileAndVerify(
<compilation name="LocalWithSimpleInitialization">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String = "Hello world"
Console.WriteLine(s)
s = nothing
Console.WriteLine(s)
Dim i As Integer = 1
Console.WriteLine(i)
Dim d As Double = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
]]>)
End Sub
<Fact>
Public Sub LocalAsNew()
CompileAndVerify(
<compilation name="LocalAsNew">
<file name="a.vb">
Imports System
Class C
Sub New (msg as string)
Me.msg = msg
End Sub
Sub Report()
Console.WriteLine(msg)
End Sub
private msg as string
End Class
Module M1
Sub Main()
dim myC as New C("hello")
myC.Report()
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello")
End Sub
<Fact>
Public Sub LocalAsNewArrayError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class C
Sub New()
End Sub
End Class
Module M1
Sub Main()
' Arrays cannot be declared with 'New'.
dim c1() as new C()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
dim c1() as new C()
~~~
</expected>)
End Sub
<Fact>
Public Sub LocalAsNewArrayError001()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalAsNewArrayError">
<file name="a.vb">
Imports System
Class X
Dim a(), b As New S
End Class
Class X1
Dim a, b() As New S
End Class
Class X2
Dim a, b(3) As New S
End Class
Class X3
Dim a, b As New S(){}
End Class
Structure S
End Structure
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30053: Arrays cannot be declared with 'New'.
Dim a(), b As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b() As New S
~~~
BC30053: Arrays cannot be declared with 'New'.
Dim a, b(3) As New S
~~~~
BC30205: End of statement expected.
Dim a, b As New S(){}
~
</expected>)
End Sub
<WorkItem(545766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545766")>
<Fact>
Public Sub LocalSameNameAsOperatorAllowed()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalSameNameAsOperatorAllowed">
<file name="a.vb">
Imports System
Class C
Public Shared Operator IsTrue(ByVal w As C) As Boolean
Dim IsTrue As Boolean = True
Return IsTrue
End Operator
Public Shared Operator IsFalse(ByVal w As C) As Boolean
Dim IsFalse As Boolean = True
Return IsFalse
End Operator
End Class
Module M1
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub ParameterlessSub()
CompileAndVerify(
<compilation name="ParameterlessSub">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Hello, world")
Console.WriteLine()
Console.WriteLine("Goodbye, world")
End Sub
Sub Main()
Goo
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello, world
Goodbye, world
]]>)
End Sub
<Fact>
Public Sub CallStatement()
CompileAndVerify(
<compilation name="CallStatement">
<file name="a.vb">
Imports System
Module M1
Sub Goo()
Console.WriteLine("Call without parameters")
End Sub
Sub Goo(s as string)
Console.WriteLine(s)
End Sub
Function SayHi as string
return "Hi"
End Function
Function One as integer
return 1
End Function
Sub Main()
Goo(SayHi)
goo
call goo
call goo("call with parameters")
dim i = One + One
Console.WriteLine(i)
i = One
Console.WriteLine(i)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hi
Call without parameters
Call without parameters
call with parameters
2
1
]]>)
End Sub
<Fact>
Public Sub CallStatementMethodNotFound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodNotFound">
<file name="a.vb">
Imports System
Module M1
Sub Main()
call goo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'goo' is not declared. It may be inaccessible due to its protection level.
call goo
~~~
</expected>)
End Sub
<WorkItem(538590, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538590")>
<Fact>
Public Sub CallStatementNothingAsInvocationExpression_Bug_4247()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Module M1
Sub Main()
Dim myLocalArr as Integer()
Dim myLocalVar as Integer = 42
call myLocalArr(0)
call myLocalVar
call Nothing
call 911
call new Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30454: Expression is not a method.
call myLocalArr(0)
~~~~~~~~~~
BC42104: Variable 'myLocalArr' is used before it has been assigned a value. A null reference exception could result at runtime.
call myLocalArr(0)
~~~~~~~~~~
BC30454: Expression is not a method.
call myLocalVar
~~~~~~~~~~
BC30454: Expression is not a method.
call Nothing
~~~~~~~
BC30454: Expression is not a method.
call 911
~~~
BC30454: Expression is not a method.
call new Integer
~~~~~~~~~~~
</expected>)
End Sub
' related to bug 4247
<Fact>
Public Sub CallStatementNamespaceAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Namespace N1.N2
Module M1
Sub Main()
call N1
call N1.N2
End Sub
End Module
End Namespace
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30112: 'N1' is a namespace and cannot be used as an expression.
call N1
~~
BC30112: 'N1.N2' is a namespace and cannot be used as an expression.
call N1.N2
~~~~~
</expected>)
End Sub
' related to bug 4247
<WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")>
<Fact>
Public Sub CallStatementTypeAsInvocationExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CallStatementMethodIsNothing">
<file name="goo.vb">
Class Class1
End Class
Module M1
Sub Main()
call Class1
call Integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30109: 'Class1' is a class type and cannot be used as an expression.
call Class1
~~~~~~
BC30110: 'Integer' is a structure type and cannot be used as an expression.
call Integer
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub AssignmentStatement()
CompileAndVerify(
<compilation name="AssignmentStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim s As String
s = "Hello world"
Console.WriteLine(s)
Dim i As Integer
i = 1
Console.WriteLine(i)
Dim d As Double
d = 1.5
Console.WriteLine(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
d = i
Console.WriteLine(d)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Hello world
1
1.5
1
]]>)
End Sub
<Fact>
Public Sub FieldAssignmentStatement()
CompileAndVerify(
<compilation name="FieldAssignmentStatement">
<file name="a.vb">
Imports System
Class C1
public i as integer
End class
Structure S1
public s as string
End Structure
Module M1
Sub Main()
dim myC as C1 = new C1
myC.i = 10
Console.WriteLine(myC.i)
dim myS as S1 = new S1
myS.s = "a"
Console.WriteLine(MyS.s)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
10
a
]]>)
End Sub
<Fact>
Public Sub AssignmentWithBadLValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AssignmentWithBadLValue">
<file name="a.vb">
Imports System
Module M1
Function f as integer
return 0
End function
Sub s
End Sub
Sub Main()
f = 0
s = 1
dim i as integer
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
f = 0
~
BC30068: Expression is a value and therefore cannot be the target of an assignment.
s = 1
~
BC42024: Unused local variable: 'i'.
dim i as integer
~
</expected>)
End Sub
<Fact>
Public Sub MultilineIfStatement1()
CompileAndVerify(
<compilation name="MultilineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
Dim cond2 As Boolean
Dim cond3 As Boolean
cond = True
cond2 = True
cond3 = True
If cond Then
Console.WriteLine("1. ThenPart")
End If
If cond Then
Console.WriteLine("2. ThenPart")
Else
Console.WriteLine("2. ElsePart")
End If
If cond Then
Console.WriteLine("3. ThenPart")
Else If cond2
Console.WriteLine("3. ElseIfPart")
End If
If cond Then
Console.WriteLine("4. ThenPart")
Else If cond2
Console.WriteLine("4. ElseIf1Part")
Else If cond3
Console.WriteLine("4. ElseIf2Part")
Else
Console.WriteLine("4. ElsePart")
End If
cond = False
If cond Then
Console.WriteLine("5. ThenPart")
End If
If cond Then
Console.WriteLine("6. ThenPart")
Else
Console.WriteLine("6. ElsePart")
End If
If cond Then
Console.WriteLine("7. ThenPart")
Else If cond2
Console.WriteLine("7. ElseIfPart")
End If
If cond Then
Console.WriteLine("8. ThenPart")
Else If cond2
Console.WriteLine("8. ElseIf1Part")
Else If cond3
Console.WriteLine("8. ElseIf2Part")
Else
Console.WriteLine("8. ElsePart")
End If
cond2 = false
If cond Then
Console.WriteLine("9. ThenPart")
Else If cond2
Console.WriteLine("9. ElseIfPart")
End If
If cond Then
Console.WriteLine("10. ThenPart")
Else If cond2
Console.WriteLine("10. ElseIf1Part")
Else If cond3
Console.WriteLine("10. ElseIf2Part")
Else
Console.WriteLine("10. ElsePart")
End If
cond3 = false
If cond Then
Console.WriteLine("11. ThenPart")
Else If cond2
Console.WriteLine("11. ElseIf1Part")
Else If cond3
Console.WriteLine("11. ElseIf2Part")
Else
Console.WriteLine("11. ElsePart")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPart
3. ThenPart
4. ThenPart
6. ElsePart
7. ElseIfPart
8. ElseIf1Part
10. ElseIf2Part
11. ElsePart
]]>)
End Sub
<Fact>
Public Sub SingleLineIfStatement1()
CompileAndVerify(
<compilation name="SingleLineIfStatement1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim cond As Boolean
cond = True
If cond Then Console.WriteLine("1. ThenPart")
If cond Then Console.WriteLine("2. ThenPartA"): COnsole.WriteLine("2. ThenPartB")
If cond Then Console.WriteLine("3. ThenPartA"): COnsole.WriteLine("3. ThenPartB") Else Console.WriteLine("3. ElsePartA"): Console.WriteLine("3. ElsePartB")
If cond Then Console.WriteLine("4. ThenPart") Else Console.WriteLine("4. ElsePartA"): Console.WriteLine("4. ElsePartB")
If cond Then Console.WriteLine("5. ThenPartA"): Console.WriteLine("5. ThenPartB") Else Console.WriteLine("5. ElsePart")
If cond Then Console.WriteLine("6. ThenPart") Else Console.WriteLine("6. ElsePart")
cond = false
If cond Then Console.WriteLine("7. ThenPart")
If cond Then Console.WriteLine("8. ThenPartA"): COnsole.WriteLine("8. ThenPartB")
If cond Then Console.WriteLine("9. ThenPart"): COnsole.WriteLine("9. ThenPartB") Else Console.WriteLine("9. ElsePartA"): Console.WriteLine("9. ElsePartB")
If cond Then Console.WriteLine("10. ThenPart") Else Console.WriteLine("10. ElsePartA"): Console.WriteLine("10. ElsePartB")
If cond Then Console.WriteLine("11. ThenPartA"): Console.WriteLine("11. ThenPartB") Else Console.WriteLine("11. ElsePart")
If cond Then Console.WriteLine("12. ThenPart") Else Console.WriteLine("12. ElsePart")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1. ThenPart
2. ThenPartA
2. ThenPartB
3. ThenPartA
3. ThenPartB
4. ThenPart
5. ThenPartA
5. ThenPartB
6. ThenPart
9. ElsePartA
9. ElsePartB
10. ElsePartA
10. ElsePartB
11. ElsePart
12. ElsePart
]]>)
End Sub
<Fact>
Public Sub DoLoop1()
CompileAndVerify(
<compilation name="DoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do While breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop2()
CompileAndVerify(
<compilation name="DoLoop2">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do Until breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop3()
CompileAndVerify(
<compilation name="DoLoop3">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = true
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = false
Loop While breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub DoLoop4()
CompileAndVerify(
<compilation name="DoLoop4">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
Do
Console.WriteLine("Iterate {0}", x)
breakLoop = true
Loop Until breakLoop
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub WhileLoop1()
CompileAndVerify(
<compilation name="WhileLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x As Integer
dim breakLoop as Boolean
x = 1
breakLoop = false
While not breakLoop
Console.WriteLine("Iterate {0}", x)
breakLoop = true
End While
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Iterate 1")
End Sub
<Fact>
Public Sub ExitContinueDoLoop1()
CompileAndVerify(
<compilation name="ExitContinueDoLoop1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
dim continueLoop as Boolean
breakLoop = True: continueLoop = true
Do While breakLoop
Console.WriteLine("Stmt1")
If continueLoop Then
Console.WriteLine("Continuing")
continueLoop = false
Continue Do
End If
Console.WriteLine("Exiting")
Exit Do
Console.WriteLine("Stmt2")
Loop
Console.WriteLine("After Loop")
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Continuing
Stmt1
Exiting
After Loop
]]>)
End Sub
<Fact>
Public Sub ExitSub()
CompileAndVerify(
<compilation name="ExitSub">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim breakLoop as Boolean
breakLoop = True
Do While breakLoop
Console.WriteLine("Stmt1")
Console.WriteLine("Exiting")
Exit Sub
Console.WriteLine("Stmt2") 'should not output
Loop
Console.WriteLine("After Loop") 'should not output
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Stmt1
Exiting
]]>)
End Sub
<Fact>
Public Sub ExitFunction()
CompileAndVerify(
<compilation name="ExitFunction">
<file name="a.vb">
Imports System
Module M1
Function Fact(i as integer) as integer
fact = 1
do
if i <= 0 then
exit function
else
fact = i * fact
i = i - 1
end if
loop
End Function
Sub Main()
Console.WriteLine(Fact(0))
Console.WriteLine(Fact(3))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
6
]]>)
End Sub
<Fact>
Public Sub BadExit()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadExit">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Exit Do ' ok
Exit For
Exit Try
Exit Select
Exit While
Loop
Exit Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30096: 'Exit For' can only appear inside a 'For' statement.
Exit For
~~~~~~~~
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
BC30099: 'Exit Select' can only appear inside a 'Select' statement.
Exit Select
~~~~~~~~~~~
BC30097: 'Exit While' can only appear inside a 'While' statement.
Exit While
~~~~~~~~~~
BC30089: 'Exit Do' can only appear inside a 'Do' statement.
Exit Do ' outside loop
~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadContinue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadContinue">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Do
Continue Do ' ok
Continue For
Continue While
Loop
Continue Do ' outside loop
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30783: 'Continue For' can only appear inside a 'For' statement.
Continue For
~~~~~~~~~~~~
BC30784: 'Continue While' can only appear inside a 'While' statement.
Continue While
~~~~~~~~~~~~~~
BC30782: 'Continue Do' can only appear inside a 'Do' statement.
Continue Do ' outside loop
~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Return1()
CompileAndVerify(
<compilation name="Return1">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
F1 = 1
End Function
Function F2 as Integer
if true then
F2 = 2
else
return 3
end if
End Function
Function F3 as Integer
return 3
End Function
Sub S1
return
End Sub
Sub Main()
dim result as integer
result = F1()
Console.WriteLine(result)
result = F2()
Console.WriteLine(result)
result = F3()
Console.WriteLine(result)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
1
2
3
]]>)
End Sub
<Fact>
Public Sub BadReturn()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadReturn">
<file name="a.vb">
Imports System
Module M1
Function F1 as Integer
return
End Function
Sub S1
return 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30654: 'Return' statement in a Function, Get, or Operator must return a value.
return
~~~~~~
BC30647: 'Return' statement in a Sub or a Set cannot return a value.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub NoReturnUnreachableEnd()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NoReturnUnreachableEnd">
<file name="a.vb">
Imports System
Module M1
Function goo() As Boolean
While True
End While
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub BadArrayInitWithExplicitArraySize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(3) as integer = 1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
dim a(3) as integer = 1
~~~~
BC30311: Value of type 'Integer' cannot be converted to 'Integer()'.
dim a(3) as integer = 1
~
</expected>)
End Sub
<Fact>
Public Sub BadArrayWithNegativeSize()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-3) as integer
dim b = new integer(-3){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30611: Array dimensions cannot have a negative size.
dim a(-3) as integer
~~
BC30611: Array dimensions cannot have a negative size.
dim b = new integer(-3){}
~~
</expected>)
End Sub
<Fact>
Public Sub ArrayWithMinusOneUpperBound()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayWithNegativeSize">
<file name="a.vb">
Imports System
Module M1
Sub S1
dim a(-1) as integer
dim b = new integer(-1){}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(542987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542987")>
<Fact()>
Public Sub MultiDimensionalArrayWithTooFewInitializers()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MultiDimensionalArrayWithTooFewInitializers">
<file name="Program.vb">
Module Program
Sub Main()
Dim x = New Integer(0, 1) {{}}
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30567: Array initializer is missing 2 elements.
Dim x = New Integer(0, 1) {{}}
~~
</expected>)
End Sub
<WorkItem(542988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542988")>
<Fact()>
Public Sub Max32ArrayDimensionsAreAllowed()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Max32ArrayDimensionsAreAllowed">
<file name="Program.vb">
Module Program
Sub Main()
Dim z1(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim z2(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) As Integer = Nothing
Dim x1 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim x2 = New Integer(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) {}
Dim y1 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
Dim y2 = New Integer(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,) {}
End Sub
End Module
</file>
</compilation>).
VerifyDiagnostics(
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"),
Diagnostic(ERRID.ERR_ArrayRankLimit, "(,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)"))
End Sub
<Fact>
Public Sub GotoIf()
CompileAndVerify(
<compilation name="GotoIf">
<file name="a.vb">
Imports System
Module M1
Sub GotoIf()
GoTo l1
If False Then
l1:
Console.WriteLine("Jump into If")
End If
End Sub
Sub GotoWhile()
GoTo l1
While False
l1:
Console.WriteLine("Jump into While")
End While
End Sub
Sub GotoDo()
GoTo l1
Do While False
l1:
Console.WriteLine("Jump into Do")
Loop
End Sub
Sub GotoSelect()
Dim i As Integer = 0
GoTo l1
Select Case i
Case 0
l1:
Console.WriteLine("Jump into Select")
End Select
End Sub
Sub Main()
GotoIf()
GotoWhile()
GotoDo()
GotoSelect()
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
Jump into If
Jump into While
Jump into Do
Jump into Select
]]>)
End Sub
<Fact()>
Public Sub GotoIntoBlockErrors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoIntoBlockErrors">
<file name="a.vb">
Imports System
Module M1
Sub GotoFor()
For i as Integer = 0 To 10
l1:
Console.WriteLine()
Next
GoTo l1
End Sub
Sub GotoWith()
Dim c1 = New C()
With c1
l1:
Console.WriteLine()
End With
GoTo l1
End Sub
Sub GotoUsing()
Using c1 as IDisposable = nothing
l1:
Console.WriteLine()
End Using
GoTo l1
End Sub
Sub GotoTry()
Try
l1:
Console.WriteLine()
Finally
End Try
GoTo l1
End Sub
Sub GotoLambda()
Dim x = Sub()
l1:
End Sub
GoTo l1
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30757: 'GoTo l1' is not valid because 'l1' is inside a 'For' or 'For Each' statement that does not contain this statement.
GoTo l1
~~
BC30002: Type 'C' is not defined.
Dim c1 = New C()
~
BC30756: 'GoTo l1' is not valid because 'l1' is inside a 'With' statement that does not contain this statement.
GoTo l1
~~
BC36009: 'GoTo l1' is not valid because 'l1' is inside a 'Using' statement that does not contain this statement.
GoTo l1
~~
BC30754: 'GoTo l1' is not valid because 'l1' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo l1
~~
BC30132: Label 'l1' is not defined.
GoTo l1
~~
</expected>)
End Sub
<Fact()>
Public Sub GotoDecimalLabels()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoDecimalLabels">
<file name="a.vb">
Imports System
Module M
Sub Main()
1 : Goto &H2
2 : Goto 01
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<WorkItem(543381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543381")>
<Fact()>
Public Sub GotoUndefinedLabel()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoUndefinedLabel">
<file name="a.vb">
Imports System
Class c1
Shared Sub Main()
GoTo lab1
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30132: Label 'lab1' is not defined.
GoTo lab1
~~~~
</expected>)
End Sub
<WorkItem(538574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538574")>
<Fact()>
Public Sub ArrayModifiersOnVariableAndType()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayModifiersOnVariableAndType">
<file name="a.vb">
Imports System
Module M1
public a() as integer()
public b(1) as integer()
Sub S1
dim a() as integer() = nothing
dim b(1) as string()
End Sub
Sub S2(x() as integer())
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors>
BC31087: Array modifiers cannot be specified on both a variable and its type.
public a() as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
public b(1) as integer()
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim a() as integer() = nothing
~~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
dim b(1) as string()
~~~~~~~~
BC31087: Array modifiers cannot be specified on both a variable and its type.
Sub S2(x() as integer())
~~~~~~~~~
</errors>)
End Sub
<Fact()>
Public Sub Bug6663()
' Test dependent on referenced mscorlib, but NOT system.dll.
Dim comp = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="Bug6663">
<file name="a.vb">
Imports System
Module Program
Sub Main()
Console.WriteLine("".ToString() = "".ToString())
End Sub
End Module
</file>
</compilation>, options:=TestOptions.ReleaseExe)
CompileAndVerify(comp, expectedOutput:="True")
End Sub
<WorkItem(540390, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540390")>
<Fact()>
Public Sub Bug6637()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Imports System
Module M1
Sub Main()
Dim a(3) As Integer
For i = 0 To 3
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = 0 To 3
~
</expected>)
End Sub
<WorkItem(540412, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540412")>
<Fact()>
Public Sub Bug6662()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="BadArrayInitWithExplicitArraySize">
<file name="a.vb">
Option Infer Off
Class C
Shared Sub M()
For i = Nothing To 10
Dim d as System.Action = Sub() i = i + 1
Next
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
For i = Nothing To 10
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
BC30451: 'i' is not declared. It may be inaccessible due to its protection level.
Dim d as System.Action = Sub() i = i + 1
~
</expected>)
End Sub
<WorkItem(542801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542801")>
<Fact()>
Public Sub ExtTryFromFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Class BaseClass
Function Method() As String
Dim x = New Integer() {}
Try
Exit Try
Catch ex1 As Exception When True
Exit Try
Finally
Exit Try
End Try
Return "x"
End Function
End Class
Class DerivedClass
Inherits BaseClass
Shared Sub Main()
End Sub
End Class
</file>
</compilation>, {SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30393: 'Exit Try' can only appear inside a 'Try' statement.
Exit Try
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotLocal()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotLocal">
<file name="goo.vb">
Module M1
Private ex as System.Exception
Sub Main()
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact(), WorkItem(651622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651622")>
Public Sub Bug651622()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="goo.vb">
Module Module1
Sub Main()
Try
Catch Main
Catch x as System.Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Main' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Main
~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchStatic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchStatic">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Static ex as exception = nothing
Try
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'ex' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchUndeclared()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchUndeclared">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Try
' Explicit off does not have effect on Catch - ex is still undefined.
Catch ex
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'ex' is not declared. It may be inaccessible due to its protection level.
Catch ex
~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Main()
Dim ex as String = "qq"
Try
Catch ex
End Try
Try
Catch ex1 as String
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex
~~
BC30392: 'Catch' cannot catch type 'String' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.
Catch ex1 as String
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchNotVariableOrParameter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotVariableOrParameter">
<file name="goo.vb">
Option Explicit Off
Module M1
Sub Goo
End Sub
Sub Main()
Try
Catch Goo
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31082: 'Goo' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.
Catch Goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch ex
Catch ex1 as Exception
Catch
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
Catch
Catch ex
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex
~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchDuplicate2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex as Exception = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When true
Catch ex
' filter does NOT make this reachable.
Catch ex1 as Exception When true
' implicitly this is a "Catch ex As Exception When true" so still unreachable
Catch When true
Catch ex1 as Exception
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception When true
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch When true
~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 as Exception
~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchOverlapped()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim ex As SystemException = Nothing
Try
' the following is NOT considered as catching all System.Exceptions
Catch When True
Catch ex
' filter does NOT make this reachable.
Catch ex1 As ArgumentException When True
' implicitly this is a "Catch ex As Exception When true"
Catch When True
' this is ok since it is not derived from SystemException
' and catch above has a filter
Catch ex1 As ApplicationException
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'SystemException'.
Catch ex1 As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub CatchShadowing()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Dim field As String
Function Goo(Of T)(ex As Exception) As Exception
Dim ex1 As SystemException = Nothing
Try
Dim ex2 As Exception = nothing
Catch ex As Exception
Catch ex1 As Exception
Catch Goo As ArgumentException When True
' this is ok
Catch ex2 As exception
Dim ex3 As exception = nothing
'this is ok
Catch ex3 As ApplicationException
' this is ok
Catch field As Exception
End Try
return nothing
End Function
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30734: 'ex' is already declared as a parameter of this method.
Catch ex As Exception
~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex1 As Exception
~~~~~~~~~~~~~~~~~~~~~~
BC30616: Variable 'ex1' hides a variable in an enclosing block.
Catch ex1 As Exception
~~~
BC42029: 'Catch' block never reached, because 'ArgumentException' inherits from 'Exception'.
Catch Goo As ArgumentException When True
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30290: Local variable cannot have the same name as the function containing it.
Catch Goo As ArgumentException When True
~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch ex2 As exception
~~~~~~~~~~~~~~~~~~~~~~
BC42029: 'Catch' block never reached, because 'ApplicationException' inherits from 'Exception'.
Catch ex3 As ApplicationException
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement.
Catch field As Exception
~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(837820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837820")>
<Fact()>
Public Sub CatchShadowingGeneric()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="CatchNotException">
<file name="goo.vb">
Imports System
Module M1
Class cls3(Of T As NullReferenceException)
Sub scen3()
Try
Catch ex As T
Catch ex As NullReferenceException
End Try
End Sub
Sub scen4()
Try
Catch ex As NullReferenceException
'COMPILEWarning: BC42029 ,"Catch ex As T"
Catch ex As T
End Try
End Sub
End Class
Sub Main()
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42029: 'Catch' block never reached, because 'T' inherits from 'NullReferenceException'.
Catch ex As T
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoOutOfFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoOutOfFinally">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
l1:
Try
Finally
try
goto l1
catch
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
goto l1
~~
</expected>)
End Sub
<Fact()>
Public Sub BranchOutOfFinally1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BranchOutOfFinally1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
for i as integer = 1 to 10
Try
Finally
continue for
End Try
Next
End Sub
Function Goo() as integer
l1:
Try
Finally
try
return 1
catch
return 1
End Try
End Try
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
continue for
~~~~~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
BC30101: Branching out of a 'Finally' is not valid.
return 1
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
Catch ex As Exception
l1:
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub GotoFromCatchToTry1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="GotoFromCatchToTry">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Try
l1:
Catch ex As Exception
Try
GoTo l1
Catch ex2 As Exception
GoTo l1
Finally
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInLateAddressOf()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Option Strict Off
Imports System
Module Program
Delegate Sub d1(ByRef x As Integer, y As Integer)
Sub Main()
Dim obj As Object '= New cls1
Dim o As d1 = AddressOf obj.goo
Dim l As Integer = 0
o(l, 2)
Console.WriteLine(l)
End Sub
Class cls1
Shared Sub goo(ByRef x As Integer, y As Integer)
x = 42
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim o As d1 = AddressOf obj.goo
~~~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Dim B as StackOverflowException
Dim C as Exception
Try
A = new ApplicationException
B = new StackOverflowException
C = new Exception
Console.Writeline(A) 'this is ok
Catch ex as NullReferenceException When A.Message isnot nothing
Catch ex as DivideByZeroException
Console.Writeline(B)
Finally
Console.Writeline(C)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Catch ex as NullReferenceException When A.Message isnot nothing
~
BC42104: Variable 'B' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(B)
~
BC42104: Variable 'C' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(C)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter1">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
' ok , A is assigned in the filter and in the catch
Catch A When A.Message isnot nothing
Console.Writeline(A)
Catch ex as Exception
A = new ApplicationException
Finally
'error
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter2">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter3">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
End Try
Console.Writeline(A)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
</expected>)
End Sub
<Fact()>
Public Sub UnassignedVariableInCatchFinallyFilter4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="UnassignedVariableInCatchFinallyFilter4">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim A as ApplicationException
Try
A = new ApplicationException
Catch A
Catch
try
Finally
A = new ApplicationException
End Try
Finally
Console.Writeline(A)
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'A' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.Writeline(A)
~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Exception
Get
Return New Exception
End Get
End Property
WriteOnly Property Boo As Exception
Set(value As Exception)
End Set
End Property
Sub Main()
Throw Moo
Throw Boo
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30524: Property 'Boo' is 'WriteOnly'.
Throw Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub ThrowNotException()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly e as new Exception
ReadOnly s as string = "qq"
Sub Main()
Throw e
Throw s
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30665: 'Throw' operand must derive from 'System.Exception'.
Throw s
~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RethrowNotInCatch()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="RethrowNotInCatch">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Throw
Try
Throw
Catch ex As Exception
Throw
Dim a As Action = Sub()
ex.ToString()
Throw
End Sub
Try
Throw
Catch
Throw
Finally
Throw
End Try
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
BC30666: 'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.
Throw
~~~~~
</expected>)
End Sub
<Fact()>
Public Sub ForNotValue()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ThrowNotValue">
<file name="goo.vb">
Imports System
Module M1
ReadOnly Property Moo As Integer
Get
Return 1
End Get
End Property
WriteOnly Property Boo As integer
Set(value As integer)
End Set
End Property
Sub Main()
For Moo = 1 to Moo step Moo
Next
For Boo = 1 to Boo step Boo
Next
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Moo = 1 to Moo step Moo
~~~
BC30039: Loop control variable cannot be a property or a late-bound indexed array.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
BC30524: Property 'Boo' is 'WriteOnly'.
For Boo = 1 to Boo step Boo
~~~
</expected>)
End Sub
<Fact()>
Public Sub CustomDatatypeForLoop()
Dim source =
<compilation>
<file name="goo.vb"><![CDATA[
Imports System
Module Module1
Public Sub Main()
Dim x As New c1
For x = 1 To 3
Console.WriteLine("hi")
Next
End Sub
End Module
Public Class c1
Public val As Integer
Public Shared Widening Operator CType(ByVal arg1 As Integer) As c1
Console.WriteLine("c1::CType(Integer) As c1")
Dim c As New c1
c.val = arg1 'what happens if this is last statement?
Return c
End Operator
Public Shared Widening Operator CType(ByVal arg1 As c1) As Integer
Console.WriteLine("c1::CType(c1) As Integer")
Dim x As Integer
x = arg1.val
Return x
End Operator
Public Shared Operator +(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::+(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val + arg2.val
Return c
End Operator
Public Shared Operator -(ByVal arg1 As c1, ByVal arg2 As c1) As c1
Console.WriteLine("c1::-(c1, c1) As c1")
Dim c As New c1
c.val = arg1.val - arg2.val
Return c
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::>=(c1, Integer) As Boolean")
If arg1.val >= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As Integer) As Boolean
Console.WriteLine("c1::<=(c1, Integer) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::<=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg2 As Integer, ByVal arg1 As c1) As Boolean
Console.WriteLine("c1::>=(Integer, c1) As Boolean")
If arg1.val <= arg2 Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator <=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::<=(c1, c1) As Boolean")
If arg1.val <= arg2.val Then
Return True
Else
Return False
End If
End Operator
Public Shared Operator >=(ByVal arg1 As c1, ByVal arg2 As c1) As Boolean
Console.WriteLine("c1::>=(c1, c1) As Boolean")
If arg1.val >= arg2.val Then
Return True
Else
Return False
End If
End Operator
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, <![CDATA[c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::CType(Integer) As c1
c1::-(c1, c1) As c1
c1::>=(c1, c1) As Boolean
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
hi
c1::+(c1, c1) As c1
c1::<=(c1, c1) As Boolean
]]>)
End Sub
<Fact()>
Public Sub SelectCase1_SwitchTable()
CompileAndVerify(
<compilation name="SelectCase1">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case 0
Console.WriteLine("Equal to 0")
Case 1, 2, 3, 4, 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9, 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Equal to 0
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<Fact()>
Public Sub SelectCase2_IfList()
CompileAndVerify(
<compilation name="SelectCase2">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
Select Case number
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 1 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]></file>
</compilation>,
expectedOutput:=<![CDATA[0:Less than 1
1:Between 1 and 5, inclusive
2:Between 1 and 5, inclusive
3:Between 1 and 5, inclusive
4:Between 1 and 5, inclusive
5:Between 1 and 5, inclusive
6:Between 6 and 8, inclusive
7:Between 6 and 8, inclusive
8:Between 6 and 8, inclusive
9:Equal to 9 or 10
10:Equal to 9 or 10
11:Greater than 10]]>)
End Sub
<WorkItem(542156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542156")>
<Fact()>
Public Sub ImplicitVarInRedim()
CompileAndVerify(
<compilation name="HelloWorld1">
<file name="a.vb">
Option Explicit Off
Module M
Sub Main()
Redim x(10)
System.Console.WriteLine("OK")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="OK")
End Sub
<Fact()>
Public Sub EndStatementsInMethodBodyShouldNotThrowNYI()
Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="EndStatementsInMethodBodyShouldNotThrowNYI">
<file name="a.vb">
Namespace N1
Public Class C1
Public Sub S1()
for i as integer = 23 to 42
next
next
do
loop while true
loop
end if
end select
end try
end using
end while
end with
end synclock
Try
Catch ex As System.Exception
End Try
catch
Try
Catch ex As System.Exception
finally
finally
End Try
finally
End Sub
Public Sub S2
end namespace
end module
end class
end structure
end interface
end enum
end function
end operator
end property
end get
end set
end event
end addhandler
end removehandler
end raiseevent
End Sub
end Class
end Namespace
Namespace N2
Class C2
function F1() as integer
end sub
return 42
end function
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30481: 'Class' statement must end with a matching 'End Class'.
Public Class C1
~~~~~~~~~~~~~~~
BC30092: 'Next' must be preceded by a matching 'For'.
next
~~~~
BC30091: 'Loop' must be preceded by a matching 'Do'.
loop
~~~~
BC30087: 'End If' must be preceded by a matching 'If'.
end if
~~~~~~
BC30088: 'End Select' must be preceded by a matching 'Select Case'.
end select
~~~~~~~~~~
BC30383: 'End Try' must be preceded by a matching 'Try'.
end try
~~~~~~~
BC36007: 'End Using' must be preceded by a matching 'Using'.
end using
~~~~~~~~~
BC30090: 'End While' must be preceded by a matching 'While'.
end while
~~~~~~~~~
BC30093: 'End With' must be preceded by a matching 'With'.
end with
~~~~~~~~
BC30674: 'End SyncLock' must be preceded by a matching 'SyncLock'.
end synclock
~~~~~~~~~~~~
BC30380: 'Catch' cannot appear outside a 'Try' statement.
catch
~~~~~
BC30381: 'Finally' can only appear once in a 'Try' statement.
finally
~~~~~~~
BC30382: 'Finally' cannot appear outside a 'Try' statement.
finally
~~~~~~~
BC30026: 'End Sub' expected.
Public Sub S2
~~~~~~~~~~~~~
BC30622: 'End Module' must be preceded by a matching 'Module'.
end module
~~~~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end class
~~~~~~~~~
BC30621: 'End Structure' must be preceded by a matching 'Structure'.
end structure
~~~~~~~~~~~~~
BC30252: 'End Interface' must be preceded by a matching 'Interface'.
end interface
~~~~~~~~~~~~~
BC30184: 'End Enum' must be preceded by a matching 'Enum'.
end enum
~~~~~~~~
BC30430: 'End Function' must be preceded by a matching 'Function'.
end function
~~~~~~~~~~~~
BC33007: 'End Operator' must be preceded by a matching 'Operator'.
end operator
~~~~~~~~~~~~
BC30431: 'End Property' must be preceded by a matching 'Property'.
end property
~~~~~~~~~~~~
BC30630: 'End Get' must be preceded by a matching 'Get'.
end get
~~~~~~~
BC30632: 'End Set' must be preceded by a matching 'Set'.
end set
~~~~~~~
BC31123: 'End Event' must be preceded by a matching 'Custom Event'.
end event
~~~~~~~~~
BC31124: 'End AddHandler' must be preceded by a matching 'AddHandler' declaration.
end addhandler
~~~~~~~~~~~~~~
BC31125: 'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.
end removehandler
~~~~~~~~~~~~~~~~~
BC31126: 'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.
end raiseevent
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End Sub
~~~~~~~
BC30460: 'End Class' must be preceded by a matching 'Class'.
end Class
~~~~~~~~~
BC30623: 'End Namespace' must be preceded by a matching 'Namespace'.
end Namespace
~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
end sub
~~~~~~~
</errors>
CompilationUtils.AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact()>
Public Sub AddHandlerMissingStuff()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload,
AddHandler , del
AddHandler
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30201: Expression expected.
AddHandler v.DomainUnload,
~
BC30201: Expression expected.
AddHandler , del
~
BC30196: Comma expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
BC30201: Expression expected.
AddHandler
~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerUninitialized()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
' no warnings here, variable is used
Dim del As System.EventHandler
' warning here
Dim v = AppDomain.CreateDomain("qq")
AddHandler v.DomainUnload, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'del' is used before it has been assigned a value. A null reference exception could result at runtime.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNotSimple()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' real event with arg list
AddHandler (v.DomainUnload()), del
' not an event
AddHandler (v.GetType()), del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.DomainUnload()), del
~~~~~~~~~~~~~~~~
BC30677: 'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.
AddHandler (v.GetType()), del
~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerLambda()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module MyClass1
Sub Main(args As String())
Dim v = AppDomain.CreateDomain("qq")
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
AppDomain.Unload(v)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42326: Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.
RemoveHandler v.DomainUnload, Sub(sender As Object, a As EventArgs) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub RemoveHandlerNotEvent()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim del As System.EventHandler =
Sub(sender As Object, a As EventArgs) Console.Write("unload")
Dim v = AppDomain.CreateDomain("qq")
' not an event
AddHandler (v.GetType), del
' not anything
AddHandler v.GetTyp, del
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30676: 'GetType' is not an event of 'AppDomain'.
AddHandler (v.GetType), del
~~~~~~~
BC30456: 'GetTyp' is not a member of 'AppDomain'.
AddHandler v.GetTyp, del
~~~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub AddHandlerNoConversion()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="AddHandlerNotSimple">
<file name="goo.vb">
Imports System
Module M1
Sub Main()
Dim v = AppDomain.CreateDomain("qq")
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
AddHandler v.DomainUnload, AddressOf H
Dim del as Action(of Object, EventArgs) = Sub(sender As Object, a As EventArgs) Console.Write("unload")
AddHandler v.DomainUnload, del
End Sub
Sub H(i as integer)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC36670: Nested sub does not have a signature that is compatible with delegate 'EventHandler'.
AddHandler (v.DomainUnload), Sub(sender As Object, sender1 As Object, sender2 As Object) Console.Write("unload")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31143: Method 'Public Sub H(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub EventHandler(sender As Object, e As EventArgs)'.
AddHandler v.DomainUnload, AddressOf H
~
BC30311: Value of type 'Action(Of Object, EventArgs)' cannot be converted to 'EventHandler'.
AddHandler v.DomainUnload, del
~~~
</expected>)
End Sub
<Fact()>
Public Sub LegalGotoCasesTryCatchFinally()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Module M1
Sub Main()
dim x1 = function()
labelOK6:
goto labelok7
if true then
goto labelok6
labelok7:
end if
return 23
end function
dim x2 = sub()
labelOK8:
goto labelok9
if true then
goto labelok8
labelok9:
end if
end sub
Try
Goto LabelOK1
LabelOK1:
Catch
Goto LabelOK2
LabelOK2:
Try
goto LabelOK1
goto LabelOK2:
LabelOK5:
Catch
goto LabelOK1
goto LabelOK5
goto LabelOK2
Finally
End Try
Finally
Goto LabelOK3
LabelOK3:
End Try
Exit Sub
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<WorkItem(543055, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543055")>
<Fact()>
Public Sub Bug10583()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LegalGotoCasesTryCatchFinally">
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Try
GoTo label
GoTo label5
Catch ex As Exception
label:
Finally
label5:
End Try
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30754: 'GoTo label' is not valid because 'label' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label
~~~~~
BC30754: 'GoTo label5' is not valid because 'label5' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.
GoTo label5
~~~~~~
</expected>)
End Sub
<WorkItem(543060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543060")>
<Fact()>
Public Sub SelectCase_ImplicitOperator()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Imports System
Module M1
Class X
Public Shared Operator =(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Operator <>(left As X, right As X) As Boolean
Return True
End Operator
Public Shared Widening Operator CType(expandedName As String) As X
Return New X()
End Operator
End Class
Sub Main()
End Sub
Sub Test(x As X)
Select Case x
Case "a"
Console.WriteLine("Equal to a")
Case "s"
Console.WriteLine("Equal to A")
Case "3"
Console.WriteLine("Error")
Case "5"
Console.WriteLine("Error")
Case "6"
Console.WriteLine("Error")
Case "9"
Console.WriteLine("Error")
Case "11"
Console.WriteLine("Error")
Case "12"
Console.WriteLine("Error")
Case "13"
Console.WriteLine("Error")
Case Else
Console.WriteLine("Error")
End Select
End Sub
End Module
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
</expected>)
End Sub
<WorkItem(543333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543333")>
<Fact()>
Public Sub Binding_Return_As_Declaration()
Dim compilation1 = CreateCompilationWithMscorlib40(
<compilation name="SelectCase">
<file name="a.vb"><![CDATA[
Class Program
Shared Main()
Return Nothing
End sub
End Class
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30689: Statement cannot appear outside of a method body.
Return Nothing
~~~~~~~~~~~~~~
BC30429: 'End Sub' must be preceded by a matching 'Sub'.
End sub
~~~~~~~
</expected>)
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
While (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529050")>
<Fact>
Public Sub WhileOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
While (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "While (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
If (true)
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529051, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529051")>
<Fact>
Public Sub IfOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
If (true)
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "If (true)"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Try
Catch
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529052")>
<Fact>
Public Sub TryOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Try
Catch
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Try"),
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Catch"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Do
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(529053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529053")>
<Fact>
Public Sub DoOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Do
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Do"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod()
Dim source =
<compilation>
<file name="a.vb">
Else
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(11031, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub ElseOutOfMethod_1()
Dim source =
<compilation>
<file name="a.vb">
Class c1
Else
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Else"))
End Sub
<WorkItem(544465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544465")>
<Fact()>
Public Sub DuplicateNullableLocals()
Dim source =
<compilation>
<file name="a.vb">
Option Explicit Off
Module M
Sub S()
Dim A? As Integer = 1
Dim A? As Integer? = 1
End Sub
End Module
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(
Diagnostic(ERRID.ERR_CantSpecifyNullableOnBoth, "As Integer?"),
Diagnostic(ERRID.ERR_DuplicateLocals1, "A?").WithArguments("A"))
End Sub
<WorkItem(544431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544431")>
<Fact()>
Public Sub IllegalModifiers()
Dim source =
<compilation>
<file name="a.vb">
Class C
Public Custom E
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfCustomModifier, "Custom"))
End Sub
<Fact()>
Public Sub InvalidCode_ConstInterface()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Const Interface
</file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors>
BC30397: 'Const' is not valid on an Interface declaration.
Const Interface
~~~~~
BC30253: 'Interface' must end with a matching 'End Interface'.
Const Interface
~~~~~~~~~~~~~~~
BC30203: Identifier expected.
Const Interface
~
</errors>)
End Sub
<WorkItem(545196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545196")>
<Fact()>
Public Sub InvalidCode_Event()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Event
</file>
</compilation>)
compilation.AssertTheseParseDiagnostics(<errors>
BC30203: Identifier expected.
Event
~
</errors>)
End Sub
<Fact>
Public Sub StopAndEnd_1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim m = GetType(Module1)
System.Console.WriteLine(m.GetMethod("TestEnd").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("TestStop").GetMethodImplementationFlags)
System.Console.WriteLine(m.GetMethod("Dummy").GetMethodImplementationFlags)
Try
System.Console.WriteLine("Before End")
TestEnd()
System.Console.WriteLine("After End")
Finally
System.Console.WriteLine("In Finally")
End Try
System.Console.WriteLine("After Try")
End Sub
Sub TestEnd()
End
End Sub
Sub TestStop()
Stop
End Sub
Sub Dummy()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation,
symbolValidator:=Sub(m As ModuleSymbol)
Dim m1 = m.ContainingAssembly.GetTypeByMetadataName("Module1")
Assert.Equal(MethodImplAttributes.Managed Or MethodImplAttributes.NoInlining Or MethodImplAttributes.NoOptimization,
DirectCast(m1.GetMembers("TestEnd").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("TestStop").Single(), PEMethodSymbol).ImplementationAttributes)
Assert.Equal(MethodImplAttributes.Managed,
DirectCast(m1.GetMembers("Dummy").Single(), PEMethodSymbol).ImplementationAttributes)
End Sub)
compilationVerifier.VerifyIL("Module1.TestEnd",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp()"
IL_0005: ret
}
]]>)
compilationVerifier.VerifyIL("Module1.TestStop",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 0
IL_0000: call "Sub System.Diagnostics.Debugger.Break()"
IL_0005: ret
}
]]>)
compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.DynamicallyLinkedLibrary))
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
End
~~~
</expected>)
End Sub
<Fact>
Public Sub StopAndEnd_2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Module1
Public Sub Main()
Dim x As Object
Dim y As Object
Stop
x.ToString()
End
y.ToString()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
x.ToString()
~
</expected>)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub StopAndEnd_3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public state As Integer = 0
Public Sub Main()
On Error GoTo handler
Throw New NullReferenceException()
Stop
Console.WriteLine("Done")
Return
handler:
Console.WriteLine(Microsoft.VisualBasic.Information.Err.GetException().GetType())
If state = 1 Then
Resume
End If
Resume Next
End Sub
End Module
Namespace System.Diagnostics
Public Class Debugger
Public Shared Sub Break()
Console.WriteLine("In Break")
Select Case Module1.state
Case 0, 1
Module1.state += 1
Case Else
Console.WriteLine("Test issue!!!")
Return
End Select
Throw New NotSupportedException()
End Sub
End Class
End Namespace
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim compilationVerifier = CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
System.NullReferenceException
In Break
System.NotSupportedException
In Break
System.NotSupportedException
Done
]]>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithSingleLineIfWithDll()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then End Else Console.WriteLine("Test")
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll)
AssertTheseDiagnostics(compilation,
<expected>
BC30615: 'End' statement cannot be used in class library projects.
If True Then End Else Console.WriteLine("Test")
~~~
</expected>)
End Sub
<WorkItem(45158, "https://github.com/dotnet/roslyn/issues/45158")>
<Fact>
Public Sub EndWithMultiLineIf()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Public Sub Main()
If True Then
End
Else
Console.WriteLine("Test")
End If
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(660010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/660010")>
<Fact>
Public Sub Regress660010()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Inherits value
End C
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=XmlReferences)
AssertTheseDiagnostics(compilation,
<expected>
BC30481: 'Class' statement must end with a matching 'End Class'.
Class C
~~~~~~~
BC30002: Type 'value' is not defined.
Inherits value
~~~~~
BC30678: 'End' statement not valid.
End C
~~~
</expected>)
End Sub
<WorkItem(718436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718436")>
<Fact>
Public Sub NotYetImplementedStatement()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Class C
Sub M()
Inherits A
Implements I
Imports X
Option Strict On
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source)
AssertTheseDiagnostics(compilation,
<expected>
BC30024: Statement is not valid inside a method.
Inherits A
~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Implements I
~~~~~~~~~~~~
BC30024: Statement is not valid inside a method.
Imports X
~~~~~~~~~
BC30024: Statement is not valid inside a method.
Option Strict On
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleRemoveAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method family specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected RemoveHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InaccessibleAddAccessor()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action TestEvent
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method family specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Action E1::TestEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass [mscorlib]System.Action
IL_0012: stfld class [mscorlib]System.Action E1::TestEvent
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
Class E2
Inherits E1
Sub Main()
Dim d As System.Action = Nothing
AddHandler Test, d
RemoveHandler Test, d
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30390: 'E1.Protected AddHandler Event Test(obj As Action)' is not accessible in this context because it is 'Protected'.
AddHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub EventTypeIsNotADelegate()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0017: ret
} // end of method E1::remove_Test
.event E1 Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithCustomILSource(compilationDef, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC37223: 'Public Event Test As E1' is an unsupported event.
AddHandler e.Test, e
~~~~~~
BC37223: 'Public Event Test As E1' is an unsupported event.
RemoveHandler e.Test, e
~~~~~~
</expected>)
'CompileAndVerify(compilation)
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test() cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test()
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidAddAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action, class E1)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
AddHandler e.Test, e
RemoveHandler e.Test, e
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, d
~~~~~~
BC30657: 'Public AddHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
AddHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="remove_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_01()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class E1 obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_02()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test() cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test()
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test()' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub InvalidRemoveAccessor_03()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance void
add_Test(class [mscorlib]System.Action obj1) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance void
remove_Test(class [mscorlib]System.Action obj1, class E1 obj2) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance void E1::add_Test(class [mscorlib]System.Action)
.removeon instance void E1::remove_Test(class [mscorlib]System.Action, class E1)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, e
RemoveHandler e.Test, e
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation1,
<expected>
BC30311: Value of type 'E1' cannot be converted to 'Action'.
AddHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, e
~~~~~~
BC30311: Value of type 'E1' cannot be converted to 'Action'.
RemoveHandler e.Test, e
~
BC30657: 'Public RemoveHandler Event Test(obj1 As Action, obj2 As E1)' has a return type that is not supported or parameter types that are not supported.
RemoveHandler e.Test, d
~~~~~~
</expected>)
'CompileAndVerify(compilation1)
Dim compilationDef2 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation2 = CreateCompilationWithCustomILSource(compilationDef2, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation2, expectedOutput:="add_Test")
End Sub
<Fact(), WorkItem(603290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603290")>
Public Sub NonVoidAccessors()
Dim ilSource = <![CDATA[
.class public auto ansi E1
extends [mscorlib]System.Object
{
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method E1::.ctor
.method public specialname instance int32
add_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "add_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::add_Test
.method public specialname instance int32
remove_Test(class [mscorlib]System.Action obj) cil managed synchronized
{
IL_0008: ldstr "remove_Test"
IL_000d: call void [mscorlib]System.Console::WriteLine(string)
IL_0016: ldc.i4.0
IL_0017: ret
} // end of method E1::remove_Test
.event [mscorlib]System.Action Test
{
.addon instance int32 E1::add_Test(class [mscorlib]System.Action)
.removeon instance int32 E1::remove_Test(class [mscorlib]System.Action)
} // end of event E1::Test
} // end of class E1
]]>
Dim compilationDef1 =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim e = New E1()
Dim d As System.Action = Nothing
AddHandler e.Test, d
RemoveHandler e.Test, d
End Sub
End Module
</file>
</compilation>
Dim compilation1 = CreateCompilationWithCustomILSource(compilationDef1, ilSource.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation1, expectedOutput:="add_Test
remove_Test")
End Sub
''' <summary>
''' Tests that FULLWIDTH COLON (U+FF1A) is never parsed as part of XML name,
''' but is instead parsed as a statement separator when it immediately follows an XML name.
''' If the next token is an identifier or keyword, it should be parsed as a separate statement.
''' An XML name should never include more than one colon.
''' See also: http://fileformat.info/info/unicode/char/FF1A
''' </summary>
<Fact>
<WorkItem(529880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529880")>
Public Sub FullWidthColonInXmlNames()
' FULLWIDTH COLON is represented by "~" below
Dim source = <![CDATA[
Imports System
Module M
Sub Main()
Test1()
Test2()
Test3()
Test4()
Test5()
Test6()
Test7()
Test8()
End Sub
Sub Test1()
Console.WriteLine(">1")
Dim x = <a/>.@xml:goo
Console.WriteLine("<1")
End Sub
Sub Test2()
Console.WriteLine(">2")
Dim x = <a/>.@xml:goo:goo
Console.WriteLine("<2")
End Sub
Sub Test3()
Console.WriteLine(">3")
Dim x = <a/>.@xml:return
Console.WriteLine("<3")
End Sub
Sub Test4()
Console.WriteLine(">4")
Dim x = <a/>.@xml:return:return
Console.WriteLine("<4")
End Sub
Sub Test5()
Console.WriteLine(">5")
Dim x = <a/>.@xml~goo
Console.WriteLine("<5")
End Sub
Sub Test6()
Console.WriteLine(">6")
Dim x = <a/>.@xml~return
Console.WriteLine("<6")
End Sub
Sub Test7()
Console.WriteLine(">7")
Dim x = <a/>.@xml~goo~return
Console.WriteLine("<7")
End Sub
Sub Test8()
Console.WriteLine(">8")
Dim x = <a/>.@xml~REM
Console.WriteLine("<8")
End Sub
Sub goo
Console.WriteLine("goo")
End Sub
Sub [return]
Console.WriteLine("return")
End Sub
Sub [REM]
Console.WriteLine("REM")
End Sub
End Module]]>.Value.Replace("~"c, SyntaxFacts.FULLWIDTH_COLON)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
<compilation name="FullWidthColonInXmlNames">
<file name="M.vb"><%= source %></file>
</compilation>,
XmlReferences,
TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
>1
<1
>2
goo
<2
>3
<3
>4
>5
goo
<5
>6
>7
goo
>8
<8]]>.Value.Replace(vbLf, Environment.NewLine))
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/VolatileKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class VolatileKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.StaticKeyword,
};
public VolatileKeywordRecommender()
: base(SyntaxKind.VolatileKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
(context.IsGlobalStatementContext && context.SyntaxTree.IsScript()) ||
context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: s_validMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class VolatileKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.StaticKeyword,
};
public VolatileKeywordRecommender()
: base(SyntaxKind.VolatileKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
(context.IsGlobalStatementContext && context.SyntaxTree.IsScript()) ||
context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: s_validMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
public class EditAndContinueDiagnosticDescriptorsTests
{
[Fact]
public void GetDescriptor()
{
var d = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ActiveStatementUpdate);
Assert.Equal("ENC0001", d.Id);
Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category);
Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags);
Assert.Equal("", d.Description);
Assert.Equal("", d.HelpLinkUri);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.RudeEdit), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.Updating_an_active_statement_requires_restarting_the_application),
FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat);
Assert.Equal("ENC0087", EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ComplexQueryExpression).Id);
d = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile);
Assert.Equal("ENC1001", d.Id);
Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category);
Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags);
Assert.Equal("", d.Description);
Assert.Equal("", d.HelpLinkUri);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.ErrorReadingFile),
FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat);
d = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(ManagedEditAndContinueAvailabilityStatus.Optimized);
Assert.Equal("ENC2012", d.Id);
Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category);
Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags);
Assert.Equal("", d.Description);
Assert.Equal("", d.HelpLinkUri);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat);
}
[Fact]
public void GetDescriptors()
{
var descriptors = EditAndContinueDiagnosticDescriptors.GetDescriptors();
Assert.NotEmpty(descriptors);
Assert.True(descriptors.All(d => d != null));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
public class EditAndContinueDiagnosticDescriptorsTests
{
[Fact]
public void GetDescriptor()
{
var d = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ActiveStatementUpdate);
Assert.Equal("ENC0001", d.Id);
Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category);
Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags);
Assert.Equal("", d.Description);
Assert.Equal("", d.HelpLinkUri);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.RudeEdit), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.Updating_an_active_statement_requires_restarting_the_application),
FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat);
Assert.Equal("ENC0087", EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ComplexQueryExpression).Id);
d = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile);
Assert.Equal("ENC1001", d.Id);
Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category);
Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags);
Assert.Equal("", d.Description);
Assert.Equal("", d.HelpLinkUri);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.ErrorReadingFile),
FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat);
d = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(ManagedEditAndContinueAvailabilityStatus.Optimized);
Assert.Equal("ENC2012", d.Id);
Assert.Equal(DiagnosticCategory.EditAndContinue, d.Category);
Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable", EnforceOnBuild.Never.ToCustomTag() }, d.CustomTags);
Assert.Equal("", d.Description);
Assert.Equal("", d.HelpLinkUri);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title);
Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat);
}
[Fact]
public void GetDescriptors()
{
var descriptors = EditAndContinueDiagnosticDescriptors.GetDescriptors();
Assert.NotEmpty(descriptors);
Assert.True(descriptors.All(d => d != null));
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/VisualBasicTest/AddAnonymousTypeMemberName/AddAnonymousTypeMemberNameTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.AddAnonymousTypeMemberName
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAnonymousTypeMemberName
Public Class AddAnonymousTypeMemberNameTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(Workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New VisualBasicAddAnonymousTypeMemberNameCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function Test1() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {[||]me.Equals(1)}
end sub
end class",
"
class C
sub M()
dim v = new with {.{|Rename:V|} = me.Equals(1)}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestExistingName1() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {.V = 1, [||]me.Equals(1)}
end sub
end class",
"
class C
sub M()
dim v = new with {.V = 1, .{|Rename:V1|} = me.Equals(1)}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestExistingName2() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {.v = 1, [||]me.Equals(1)}
end sub
end class",
"
class C
sub M()
dim v = new with {.v = 1, .{|Rename:V1|} = me.Equals(1)}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestFixAll1() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.ToString() + 1}}
end sub
end class",
"
class C
sub M()
dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestFixAll2() As Task
Await TestInRegularAndScript1Async(
"
class C
{
sub M()
{
dim v = new with {new with {{|FixAllInDocument:|}me.Equals(1), me.ToString() + 1}}
}
end class",
"
class C
{
sub M()
{
dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}}
}
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestFixAll3() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.Equals(2)}}
end sub
end class",
"
class C
sub M()
dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.Equals(2)}}
end sub
end class")
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.AddAnonymousTypeMemberName
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAnonymousTypeMemberName
Public Class AddAnonymousTypeMemberNameTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(Workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New VisualBasicAddAnonymousTypeMemberNameCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function Test1() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {[||]me.Equals(1)}
end sub
end class",
"
class C
sub M()
dim v = new with {.{|Rename:V|} = me.Equals(1)}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestExistingName1() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {.V = 1, [||]me.Equals(1)}
end sub
end class",
"
class C
sub M()
dim v = new with {.V = 1, .{|Rename:V1|} = me.Equals(1)}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestExistingName2() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {.v = 1, [||]me.Equals(1)}
end sub
end class",
"
class C
sub M()
dim v = new with {.v = 1, .{|Rename:V1|} = me.Equals(1)}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestFixAll1() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.ToString() + 1}}
end sub
end class",
"
class C
sub M()
dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}}
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestFixAll2() As Task
Await TestInRegularAndScript1Async(
"
class C
{
sub M()
{
dim v = new with {new with {{|FixAllInDocument:|}me.Equals(1), me.ToString() + 1}}
}
end class",
"
class C
{
sub M()
{
dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}}
}
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)>
Public Async Function TestFixAll3() As Task
Await TestInRegularAndScript1Async(
"
class C
sub M()
dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.Equals(2)}}
end sub
end class",
"
class C
sub M()
dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.Equals(2)}}
end sub
end class")
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/EditorFeatures/CSharpTest/AssignOutParameters/AssignOutParametersAtStartTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.AssignOutParameters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.AssignOutParameters.AssignOutParametersAtStartCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AssignOutParameters
{
/// <summary>
/// Note: many of these tests will validate that there is no fix offered here. That's because
/// for many of them, that fix is offered by the <see cref="AssignOutParametersAboveReturnCodeFixProvider"/>
/// instead. These tests have been marked as such.
/// </summary>
public class AssignOutParametersAtStartTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForSimpleReturn()
{
// Handled by other fixer
var code = @"class C
{
char M(out int i)
{
{|CS0177:return 'a';|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForSwitchSectionReturn()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(out int i)
{
switch (0)
{
default:
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(out int i)
{
i = 0;
switch (0)
{
default:
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMissingWhenVariableAssigned()
{
var code = @"class C
{
char M(out int i)
{
i = 0;
return 'a';
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestWhenNotAssignedThroughAllPaths1()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i)
{
if (b)
i = 1;
{|CS0177:return 'a';|}
}
}",
@"class C
{
char M(bool b, out int i)
{
i = 0;
if (b)
i = 1;
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestWhenNotAssignedThroughAllPaths2()
{
// Handled by other fixer
var code = @"class C
{
bool M(out int i1, out int i2)
{
{|CS0177:return Try(out i1) || Try(out i2);|}
}
bool Try(out int i)
{
i = 0;
return true;
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMissingWhenAssignedThroughAllPaths()
{
var code = @"class C
{
char M(bool b, out int i)
{
if (b)
i = 1;
else
i = 2;
return 'a';
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMultiple()
{
// Handled by other fixer
var code = @"class C
{
char M(out int i, out string s)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMultiple_AssignedInReturn1()
{
// Handled by other fixer
var code = @"class C
{
string M(out int i, out string s)
{
{|CS0177:return s = """";|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMultiple_AssignedInReturn2()
{
// Handled by other fixer
var code = @"class C
{
string M(out int i, out string s)
{
{|CS0177:return (i = 0).ToString();|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestNestedReturn()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(out int i)
{
if (true)
{
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(out int i)
{
i = 0;
if (true)
{
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestNestedReturnNoBlock()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(out int i)
{
if (true)
{|CS0177:return 'a';|}
}
}",
@"class C
{
char M(out int i)
{
i = 0;
if (true)
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestNestedReturnEvenWhenWrittenAfter()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i)
{
if (b)
{
{|CS0177:return 'a';|}
}
i = 1;
throw null;
}
}",
@"class C
{
char M(bool b, out int i)
{
i = 0;
if (b)
{
return 'a';
}
i = 1;
throw null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForExpressionBodyMember()
{
// Handled by other fixer
var code = @"class C
{
char M(out int i) => {|CS0177:'a'|};
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForLambdaExpressionBody()
{
// Handled by other fixer
var code = @"class C
{
delegate char D(out int i);
void X()
{
D d = (out int i) => {|CS0177:'a'|};
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMissingForLocalFunctionExpressionBody()
{
// Handled by other fixer
var code = @"class C
{
void X()
{
char {|CS0177:D|}(out int i) => 'a';
D(out _);
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForLambdaBlockBody()
{
// Handled by other fixer
var code = @"class C
{
delegate char D(out int i);
void X()
{
D d = (out int i) =>
{
{|CS0177:return 'a';|}
};
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForLocalFunctionBlockBody()
{
// Handled by other fixer
var code = @"class C
{
void X()
{
char D(out int i)
{
{|CS0177:return 'a';|}
}
D(out _);
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForOutParamInSinglePath()
{
var code = @"class C
{
char M(bool b, out int i)
{
if (b)
i = 1;
else
SomeMethod(out i);
return 'a';
}
void SomeMethod(out int i) => i = 0;
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll1()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
else
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
return 'a';
}
else
{
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll1_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
else
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}
char N(bool b, out int i, out int j)
{
if (b)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
else
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
return 'a';
}
else
{
return 'a';
}
}
char N(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
return 'a';
}
else
{
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll2()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{|CS0177:{|CS0177:return 'a';|}|}
else
{|CS0177:{|CS0177:return 'a';|}|}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
return 'a';
else
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll2_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{|CS0177:{|CS0177:return 'a';|}|}
else
{|CS0177:{|CS0177:return 'a';|}|}
}
char N(bool b, out int i, out int j)
{
if (b)
{|CS0177:{|CS0177:return 'a';|}|}
else
{|CS0177:{|CS0177:return 'a';|}|}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
return 'a';
else
return 'a';
}
char N(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
return 'a';
else
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll3()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
i = 0;
{|CS0177:return 'a';|}
}
else
{
j = 0;
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
i = 0;
return 'a';
}
else
{
j = 0;
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll3_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
i = 0;
{|CS0177:return 'a';|}
}
else
{
j = 0;
{|CS0177:return 'a';|}
}
}
char N(bool b, out int i, out int j)
{
if (b)
{
i = 0;
{|CS0177:return 'a';|}
}
else
{
j = 0;
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
i = 0;
return 'a';
}
else
{
j = 0;
return 'a';
}
}
char N(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
i = 0;
return 'a';
}
else
{
j = 0;
return 'a';
}
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.AssignOutParameters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.AssignOutParameters.AssignOutParametersAtStartCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AssignOutParameters
{
/// <summary>
/// Note: many of these tests will validate that there is no fix offered here. That's because
/// for many of them, that fix is offered by the <see cref="AssignOutParametersAboveReturnCodeFixProvider"/>
/// instead. These tests have been marked as such.
/// </summary>
public class AssignOutParametersAtStartTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForSimpleReturn()
{
// Handled by other fixer
var code = @"class C
{
char M(out int i)
{
{|CS0177:return 'a';|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForSwitchSectionReturn()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(out int i)
{
switch (0)
{
default:
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(out int i)
{
i = 0;
switch (0)
{
default:
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMissingWhenVariableAssigned()
{
var code = @"class C
{
char M(out int i)
{
i = 0;
return 'a';
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestWhenNotAssignedThroughAllPaths1()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i)
{
if (b)
i = 1;
{|CS0177:return 'a';|}
}
}",
@"class C
{
char M(bool b, out int i)
{
i = 0;
if (b)
i = 1;
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestWhenNotAssignedThroughAllPaths2()
{
// Handled by other fixer
var code = @"class C
{
bool M(out int i1, out int i2)
{
{|CS0177:return Try(out i1) || Try(out i2);|}
}
bool Try(out int i)
{
i = 0;
return true;
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMissingWhenAssignedThroughAllPaths()
{
var code = @"class C
{
char M(bool b, out int i)
{
if (b)
i = 1;
else
i = 2;
return 'a';
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMultiple()
{
// Handled by other fixer
var code = @"class C
{
char M(out int i, out string s)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMultiple_AssignedInReturn1()
{
// Handled by other fixer
var code = @"class C
{
string M(out int i, out string s)
{
{|CS0177:return s = """";|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMultiple_AssignedInReturn2()
{
// Handled by other fixer
var code = @"class C
{
string M(out int i, out string s)
{
{|CS0177:return (i = 0).ToString();|}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestNestedReturn()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(out int i)
{
if (true)
{
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(out int i)
{
i = 0;
if (true)
{
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestNestedReturnNoBlock()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(out int i)
{
if (true)
{|CS0177:return 'a';|}
}
}",
@"class C
{
char M(out int i)
{
i = 0;
if (true)
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestNestedReturnEvenWhenWrittenAfter()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i)
{
if (b)
{
{|CS0177:return 'a';|}
}
i = 1;
throw null;
}
}",
@"class C
{
char M(bool b, out int i)
{
i = 0;
if (b)
{
return 'a';
}
i = 1;
throw null;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForExpressionBodyMember()
{
// Handled by other fixer
var code = @"class C
{
char M(out int i) => {|CS0177:'a'|};
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForLambdaExpressionBody()
{
// Handled by other fixer
var code = @"class C
{
delegate char D(out int i);
void X()
{
D d = (out int i) => {|CS0177:'a'|};
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestMissingForLocalFunctionExpressionBody()
{
// Handled by other fixer
var code = @"class C
{
void X()
{
char {|CS0177:D|}(out int i) => 'a';
D(out _);
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForLambdaBlockBody()
{
// Handled by other fixer
var code = @"class C
{
delegate char D(out int i);
void X()
{
D d = (out int i) =>
{
{|CS0177:return 'a';|}
};
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForLocalFunctionBlockBody()
{
// Handled by other fixer
var code = @"class C
{
void X()
{
char D(out int i)
{
{|CS0177:return 'a';|}
}
D(out _);
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestForOutParamInSinglePath()
{
var code = @"class C
{
char M(bool b, out int i)
{
if (b)
i = 1;
else
SomeMethod(out i);
return 'a';
}
void SomeMethod(out int i) => i = 0;
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll1()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
else
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
return 'a';
}
else
{
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll1_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
else
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}
char N(bool b, out int i, out int j)
{
if (b)
{
{|CS0177:{|CS0177:return 'a';|}|}
}
else
{
{|CS0177:{|CS0177:return 'a';|}|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
return 'a';
}
else
{
return 'a';
}
}
char N(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
return 'a';
}
else
{
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll2()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{|CS0177:{|CS0177:return 'a';|}|}
else
{|CS0177:{|CS0177:return 'a';|}|}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
return 'a';
else
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll2_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{|CS0177:{|CS0177:return 'a';|}|}
else
{|CS0177:{|CS0177:return 'a';|}|}
}
char N(bool b, out int i, out int j)
{
if (b)
{|CS0177:{|CS0177:return 'a';|}|}
else
{|CS0177:{|CS0177:return 'a';|}|}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
return 'a';
else
return 'a';
}
char N(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
return 'a';
else
return 'a';
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll3()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
i = 0;
{|CS0177:return 'a';|}
}
else
{
j = 0;
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
i = 0;
return 'a';
}
else
{
j = 0;
return 'a';
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)]
public async Task TestFixAll3_MultipleMethods()
{
await VerifyCS.VerifyCodeFixAsync(
@"class C
{
char M(bool b, out int i, out int j)
{
if (b)
{
i = 0;
{|CS0177:return 'a';|}
}
else
{
j = 0;
{|CS0177:return 'a';|}
}
}
char N(bool b, out int i, out int j)
{
if (b)
{
i = 0;
{|CS0177:return 'a';|}
}
else
{
j = 0;
{|CS0177:return 'a';|}
}
}
}",
@"class C
{
char M(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
i = 0;
return 'a';
}
else
{
j = 0;
return 'a';
}
}
char N(bool b, out int i, out int j)
{
i = 0;
j = 0;
if (b)
{
i = 0;
return 'a';
}
else
{
j = 0;
return 'a';
}
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 55,962 | Inline Hints: Removed experimental from the title | akhera99 | "2021-08-27T16:47:40Z" | "2021-08-27T19:59:35Z" | 9faa78ee058ec6b4f2bea1f2d0556f7ebe8b3c19 | 152b6cc6a8b7fb696d89757528cc4e534ff94d8f | Inline Hints: Removed experimental from the title. | ./src/Compilers/CSharp/Test/Semantic/Diagnostics/CompilationEventTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class CompilationEventTests : CompilingTestBase
{
internal static void VerifyEvents(AsyncQueue<CompilationEvent> queue, params string[] expectedEvents)
{
var expected = new HashSet<string>();
foreach (var s in expectedEvents)
{
if (!expected.Add(s))
{
Console.WriteLine("Expected duplicate " + s);
}
}
var actual = ArrayBuilder<CompilationEvent>.GetInstance();
while (queue.Count > 0 || !queue.IsCompleted)
{
var te = queue.DequeueAsync(CancellationToken.None);
Assert.True(te.IsCompleted);
actual.Add(te.Result);
}
bool unexpected = false;
foreach (var a in actual)
{
var eventString = a.ToString();
if (!expected.Remove(eventString))
{
if (!unexpected)
{
Console.WriteLine("UNEXPECTED EVENTS:");
unexpected = true;
}
Console.WriteLine(eventString);
}
}
if (expected.Count != 0)
{
Console.WriteLine("MISSING EVENTS:");
}
foreach (var e in expected)
{
Console.WriteLine(e);
}
if (unexpected || expected.Count != 0 || expectedEvents.Length != actual.Count)
{
bool first = true;
Console.WriteLine("ACTUAL EVENTS:");
foreach (var e in actual)
{
if (!first)
{
Console.WriteLine(",");
}
first = false;
Console.Write("\"" + e.ToString() + "\"");
}
Console.WriteLine();
Assert.True(false);
}
}
[Fact]
public void TestQueuedSymbols()
{
var source =
@"namespace N
{
partial class C<T1>
{
partial void M(int x1);
internal int P { get; private set; }
int F = 12;
void N<T2>(int y = 12) { F = F + 1; }
}
partial class C<T1>
{
partial void M(int x2) {}
}
}";
var q = new AsyncQueue<CompilationEvent>();
CreateCompilationWithMscorlib45(source)
.WithEventQueue(q)
.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
) // force diagnostics twice
.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
);
VerifyEvents(q);
}
private static void VerifyEvents(AsyncQueue<CompilationEvent> q)
{
VerifyEvents(q,
"CompilationStartedEvent",
"SymbolDeclaredCompilationEvent(P int C<T1>.P @ : (5,4)-(5,40))",
"SymbolDeclaredCompilationEvent(F int C<T1>.F @ : (6,8)-(6,14))",
"SymbolDeclaredCompilationEvent(C C<T1> @ : (2,2)-(8,3), : (9,2)-(12,3))",
"SymbolDeclaredCompilationEvent(M void C<T1>.M(int x1) @ : (4,4)-(4,27))",
"SymbolDeclaredCompilationEvent(M void C<T1>.M(int x2) @ : (11,4)-(11,29))",
"SymbolDeclaredCompilationEvent(N N @ : (0,0)-(13,1))",
"SymbolDeclaredCompilationEvent(<empty> @ : (0,0)-(13,1))",
"SymbolDeclaredCompilationEvent(get_P int C<T1>.P.get @ : (5,21)-(5,25))",
"SymbolDeclaredCompilationEvent(set_P void C<T1>.P.set @ : (5,26)-(5,38))",
"SymbolDeclaredCompilationEvent(N void C<T1>.N<T2>(int y = 12) @ : (7,4)-(7,41))",
"CompilationUnitCompletedEvent()",
"CompilationCompletedEvent"
);
}
[Fact]
public void TestQueuedSymbolsAndGetUsedAssemblyReferences()
{
var source =
@"namespace N
{
partial class C<T1>
{
partial void M(int x1);
internal int P { get; private set; }
int F = 12;
void N<T2>(int y = 12) { F = F + 1; }
}
partial class C<T1>
{
partial void M(int x2) {}
}
}";
var q = new AsyncQueue<CompilationEvent>();
var comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.GetUsedAssemblyReferences();
VerifyEvents(q);
q = new AsyncQueue<CompilationEvent>();
comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
);
comp.GetUsedAssemblyReferences();
VerifyEvents(q);
q = new AsyncQueue<CompilationEvent>();
comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.GetUsedAssemblyReferences();
comp.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
);
VerifyEvents(q);
q = new AsyncQueue<CompilationEvent>();
comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.GetUsedAssemblyReferences();
comp.GetUsedAssemblyReferences();
VerifyEvents(q);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class CompilationEventTests : CompilingTestBase
{
internal static void VerifyEvents(AsyncQueue<CompilationEvent> queue, params string[] expectedEvents)
{
var expected = new HashSet<string>();
foreach (var s in expectedEvents)
{
if (!expected.Add(s))
{
Console.WriteLine("Expected duplicate " + s);
}
}
var actual = ArrayBuilder<CompilationEvent>.GetInstance();
while (queue.Count > 0 || !queue.IsCompleted)
{
var te = queue.DequeueAsync(CancellationToken.None);
Assert.True(te.IsCompleted);
actual.Add(te.Result);
}
bool unexpected = false;
foreach (var a in actual)
{
var eventString = a.ToString();
if (!expected.Remove(eventString))
{
if (!unexpected)
{
Console.WriteLine("UNEXPECTED EVENTS:");
unexpected = true;
}
Console.WriteLine(eventString);
}
}
if (expected.Count != 0)
{
Console.WriteLine("MISSING EVENTS:");
}
foreach (var e in expected)
{
Console.WriteLine(e);
}
if (unexpected || expected.Count != 0 || expectedEvents.Length != actual.Count)
{
bool first = true;
Console.WriteLine("ACTUAL EVENTS:");
foreach (var e in actual)
{
if (!first)
{
Console.WriteLine(",");
}
first = false;
Console.Write("\"" + e.ToString() + "\"");
}
Console.WriteLine();
Assert.True(false);
}
}
[Fact]
public void TestQueuedSymbols()
{
var source =
@"namespace N
{
partial class C<T1>
{
partial void M(int x1);
internal int P { get; private set; }
int F = 12;
void N<T2>(int y = 12) { F = F + 1; }
}
partial class C<T1>
{
partial void M(int x2) {}
}
}";
var q = new AsyncQueue<CompilationEvent>();
CreateCompilationWithMscorlib45(source)
.WithEventQueue(q)
.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
) // force diagnostics twice
.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
);
VerifyEvents(q);
}
private static void VerifyEvents(AsyncQueue<CompilationEvent> q)
{
VerifyEvents(q,
"CompilationStartedEvent",
"SymbolDeclaredCompilationEvent(P int C<T1>.P @ : (5,4)-(5,40))",
"SymbolDeclaredCompilationEvent(F int C<T1>.F @ : (6,8)-(6,14))",
"SymbolDeclaredCompilationEvent(C C<T1> @ : (2,2)-(8,3), : (9,2)-(12,3))",
"SymbolDeclaredCompilationEvent(M void C<T1>.M(int x1) @ : (4,4)-(4,27))",
"SymbolDeclaredCompilationEvent(M void C<T1>.M(int x2) @ : (11,4)-(11,29))",
"SymbolDeclaredCompilationEvent(N N @ : (0,0)-(13,1))",
"SymbolDeclaredCompilationEvent(<empty> @ : (0,0)-(13,1))",
"SymbolDeclaredCompilationEvent(get_P int C<T1>.P.get @ : (5,21)-(5,25))",
"SymbolDeclaredCompilationEvent(set_P void C<T1>.P.set @ : (5,26)-(5,38))",
"SymbolDeclaredCompilationEvent(N void C<T1>.N<T2>(int y = 12) @ : (7,4)-(7,41))",
"CompilationUnitCompletedEvent()",
"CompilationCompletedEvent"
);
}
[Fact]
public void TestQueuedSymbolsAndGetUsedAssemblyReferences()
{
var source =
@"namespace N
{
partial class C<T1>
{
partial void M(int x1);
internal int P { get; private set; }
int F = 12;
void N<T2>(int y = 12) { F = F + 1; }
}
partial class C<T1>
{
partial void M(int x2) {}
}
}";
var q = new AsyncQueue<CompilationEvent>();
var comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.GetUsedAssemblyReferences();
VerifyEvents(q);
q = new AsyncQueue<CompilationEvent>();
comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
);
comp.GetUsedAssemblyReferences();
VerifyEvents(q);
q = new AsyncQueue<CompilationEvent>();
comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.GetUsedAssemblyReferences();
comp.VerifyDiagnostics(
// (12,18): warning CS8826: Partial method declarations 'void C<T1>.M(int x1)' and 'void C<T1>.M(int x2)' have signature differences.
// partial void M(int x2) {}
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void C<T1>.M(int x1)", "void C<T1>.M(int x2)").WithLocation(12, 18)
);
VerifyEvents(q);
q = new AsyncQueue<CompilationEvent>();
comp = CreateCompilationWithMscorlib45(source).WithEventQueue(q);
comp.GetUsedAssemblyReferences();
comp.GetUsedAssemblyReferences();
VerifyEvents(q);
}
}
}
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.