diff --git a/BuildAndTest.proj b/BuildAndTest.proj
index 385739580af0a..f2fac6687f7a7 100644
--- a/BuildAndTest.proj
+++ b/BuildAndTest.proj
@@ -7,57 +7,51 @@
$(MSBuildThisFileDirectory)Roslyn.sln
$(MSBuildThisFileDirectory)src\Samples\Samples.sln
+ true
Debug
$(RunTestArgs) -xml
$(RunTestArgs) -test64
$(RunTestArgs) -testVsi
+ $(RunTestArgs) -trait:Feature=NetCore
$(RunTestArgs) -trait:$(Trait)
$(RunTestArgs) -notrait:$(NoTrait)
+ false
*.UnitTests.dll
*.IntegrationTests.dll
$(MSBuildThisFileDirectory)Binaries\$(Configuration)\
$(RunTestArgs) -log:"$(OutputDirectory)\runtests.log"
$(OutputDirectory)\CoreClrTest
-
- RestorePackages=false;
- TreatWarningsAsErrors=true;
- DeployExtension=false;
-
@@ -81,6 +75,7 @@
@@ -115,7 +110,7 @@
-
+
$(NuGetPackageRoot)\roslyntools.microsoft.vsixexpinstaller\$(RoslynToolsMicrosoftVSIXExpInstallerVersion)\tools\VsixExpInstaller.exe
diff --git a/README.md b/README.md
index 09374138191bd..192a511459271 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
|**dev16**|[![Build Status](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_debug_unit32/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_debug_unit32/)|[![Build Status](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_debug_unit64/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_debug_unit64/)|[![Build Status](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_release_unit32/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_release_unit32/)|[![Build Status](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_release_unit64/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_release_unit64/)|[![Build Status](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_determinism/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_determinism/)|[![Build Status](https://ci.dot.net/buildStatus/icon?job=dotnet_roslyn/dev16/windows_debug_vs-integration)](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_debug_vs-integration/)|[![Build Status](https://ci.dot.net/buildStatus/icon?job=dotnet_roslyn/dev16/windows_release_vs-integration)](https://ci.dot.net/job/dotnet_roslyn/job/dev16/job/windows_release_vs-integration/)|
### Linux/Mac - Unit Tests
-|Branch|Ubuntu14|Ubuntu16|MacOSX|
+|Branch|Ubuntu14|Ubuntu16|macOS|
|:--:|:--:|:--:|:--:|
|**master**|[![BuildStatus](https://ci.dot.net/job/dotnet_roslyn/job/master/job/ubuntu_14_debug/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/master/job/ubuntu_14_debug/)|[![BuildStatus](https://ci.dot.net/job/dotnet_roslyn/job/master/job/ubuntu_16_debug/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/master/job/ubuntu_16_debug/)|[![BuildStatus](https://ci.dot.net/job/dotnet_roslyn/job/master/job/mac_debug/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/master/job/mac_debug/)|
|**dev15.0.x**|[![BuildStatus](https://ci.dot.net/job/dotnet_roslyn/job/dev15.0.x/job/linux_debug/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/dev15.0.x/job/linux_debug/)||[![BuildStatus](https://ci.dot.net/job/dotnet_roslyn/job/dev15.0.x/job/mac_debug/badge/icon)](https://ci.dot.net/job/dotnet_roslyn/job/dev15.0.x/job/mac_debug/)|
diff --git a/build/Targets/Imports.targets b/build/Targets/Imports.targets
index 6aaa705f52acc..a09755352405d 100644
--- a/build/Targets/Imports.targets
+++ b/build/Targets/Imports.targets
@@ -41,6 +41,11 @@
false
$(OutputPath)Dlls\$(MSBuildProjectName)\
+
+
+
+
+
@@ -133,6 +138,8 @@
true
false
false
+
+ $(NuGetPackageRoot)\Microsoft.DotNet.IBCMerge\$(MicrosoftDotNetIBCMerge)\lib\net45\ibcmerge.exe
@@ -423,16 +430,24 @@
-
+
+
+
+ ConsoleToMSBuild="true"
+ Condition="Exists('$(IbcMergePath)')">
@@ -440,22 +455,18 @@
-
-
-
+ Condition="'$(_IsAnyPortableUnitTest)' == 'true' AND '$(DeveloperBuild)' == 'true' AND '$(OS)' == 'Windows_NT'">
+
+
+
+
+
+
+
+
+
+
+
-
+
add to 'defines'
- If defines.ContainsKey(symbolName) Then
- defines = defines.Remove(symbolName)
- End If
- defines = defines.Add(symbolName, value)
+ defines = defines.SetItem(symbolName, value)
ElseIf tokens.Current.Kind = SyntaxKind.CommaToken OrElse
tokens.Current.Kind = SyntaxKind.ColonToken OrElse
tokens.Current.Kind = SyntaxKind.EndOfFileToken Then
' We have no value being assigned, so we'll just assign it to true
- If defines.ContainsKey(symbolName) Then
- defines = defines.Remove(symbolName)
- End If
- defines = defines.Add(symbolName, InternalSyntax.CConst.Create(True))
+ defines = defines.SetItem(symbolName, InternalSyntax.CConst.Create(True))
ElseIf tokens.Current.Kind = SyntaxKind.BadToken Then
GetErrorStringForRemainderOfConditionalCompilation(tokens, parsedTokensAsString)
diff --git a/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb b/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb
index 3e3947ff04456..19c0e78b86ca6 100644
--- a/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb
+++ b/src/Compilers/VisualBasic/Portable/Compilation/VisualBasicCompilation.vb
@@ -245,7 +245,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic
Debug.Assert(tree IsNot VisualBasicSyntaxTree.Dummy)
Debug.Assert(tree.IsMyTemplate)
- Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy)
+ Interlocked.CompareExchange(Of SyntaxTree)(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy)
Else
' we need to make one.
Dim text As String = EmbeddedResources.VbMyTemplateText
@@ -260,7 +260,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic
Throw ExceptionUtilities.Unreachable
End If
- If Interlocked.CompareExchange(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Is VisualBasicSyntaxTree.Dummy Then
+ If Interlocked.CompareExchange(Of SyntaxTree)(_lazyMyTemplate, tree, VisualBasicSyntaxTree.Dummy) Is VisualBasicSyntaxTree.Dummy Then
' set global cache
s_myTemplateCache(parseOptions) = tree
End If
diff --git a/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/VisualBasicSymbolMatcher.vb b/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/VisualBasicSymbolMatcher.vb
index 32e5fa5769498..815b55c770ffa 100644
--- a/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/VisualBasicSymbolMatcher.vb
+++ b/src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/VisualBasicSymbolMatcher.vb
@@ -134,7 +134,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
typesByName.Add(type.Name, type)
End If
Next
- Interlocked.CompareExchange(Me._lazyTopLevelTypes, typesByName, Nothing)
+ Interlocked.CompareExchange(Of IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition))(Me._lazyTopLevelTypes, typesByName, Nothing)
End If
Return Me._lazyTopLevelTypes
End Function
diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceLambdaSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceLambdaSymbol.vb
index 8b2c68f7619ea..15b986a2f43a5 100644
--- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceLambdaSymbol.vb
+++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceLambdaSymbol.vb
@@ -55,7 +55,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Get
If Me._lazyAnonymousDelegateSymbol Is ErrorTypeSymbol.UnknownResultType Then
Dim newValue As NamedTypeSymbol = MakeAssociatedAnonymousDelegate()
- Dim oldValue As NamedTypeSymbol = Interlocked.CompareExchange(Me._lazyAnonymousDelegateSymbol, newValue, ErrorTypeSymbol.UnknownResultType)
+ Dim oldValue As NamedTypeSymbol = Interlocked.CompareExchange(Of NamedTypeSymbol)(Me._lazyAnonymousDelegateSymbol, newValue, ErrorTypeSymbol.UnknownResultType)
Debug.Assert(oldValue Is ErrorTypeSymbol.UnknownResultType OrElse oldValue Is newValue)
End If
Return Me._lazyAnonymousDelegateSymbol
diff --git a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb
index b97582748a043..6a1a6a0d13c40 100644
--- a/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb
+++ b/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.vb
@@ -1296,7 +1296,7 @@ lReportErrorOnTwoTokens:
meParameter = Nothing
Else
If _lazyMeParameter Is Nothing Then
- Interlocked.CompareExchange(_lazyMeParameter, New MeParameterSymbol(Me), Nothing)
+ Interlocked.CompareExchange(Of ParameterSymbol)(_lazyMeParameter, New MeParameterSymbol(Me), Nothing)
End If
meParameter = _lazyMeParameter
diff --git a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb
index cf7dfb5a7b6b2..5613d3dca11c5 100644
--- a/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb
+++ b/src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedMethodBase.vb
@@ -178,7 +178,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
meParameter = Nothing
Else
If _lazyMeParameter Is Nothing Then
- Interlocked.CompareExchange(_lazyMeParameter, New MeParameterSymbol(Me), Nothing)
+ Interlocked.CompareExchange(Of ParameterSymbol)(_lazyMeParameter, New MeParameterSymbol(Me), Nothing)
End If
meParameter = _lazyMeParameter
diff --git a/src/Compilers/VisualBasic/Test/CommandLine/BasicCommandLineTest.vbproj b/src/Compilers/VisualBasic/Test/CommandLine/BasicCommandLineTest.vbproj
index 26b6b5e233155..3e1744bafea98 100644
--- a/src/Compilers/VisualBasic/Test/CommandLine/BasicCommandLineTest.vbproj
+++ b/src/Compilers/VisualBasic/Test/CommandLine/BasicCommandLineTest.vbproj
@@ -12,6 +12,7 @@
false
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}
UnitTest
diff --git a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb
index f2fce5f8fc94a..84f612cb5eb24 100644
--- a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb
+++ b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb
@@ -8290,6 +8290,29 @@ End Module
parsedArgs.Errors.Verify(Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("langversion", "1000").WithLocation(1, 1))
End Sub
+
+
+ Public Sub MissingCompilerAssembly()
+ Dim dir = Temp.CreateDirectory()
+ Dim vbcPath = dir.CopyFile(GetType(Vbc).Assembly.Location).Path
+
+ ' Missing Microsoft.CodeAnalysis.VisualBasic.dll.
+ Dim result = ProcessUtilities.Run(vbcPath, arguments:="/nologo /t:library unknown.vb", workingDirectory:=dir.Path)
+ Assert.Equal(1, result.ExitCode)
+ Assert.Equal(
+ $"Could not load file or assembly '{GetType(VisualBasicCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.",
+ result.Output.Trim())
+
+ ' Missing System.Collections.Immutable.dll.
+ dir.CopyFile(GetType(Compilation).Assembly.Location)
+ dir.CopyFile(GetType(VisualBasicCompilation).Assembly.Location)
+ result = ProcessUtilities.Run(vbcPath, arguments:="/nologo /t:library unknown.vb", workingDirectory:=dir.Path)
+ Assert.Equal(1, result.ExitCode)
+ Assert.Equal(
+ $"Could not load file or assembly '{GetType(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.",
+ result.Output.Trim())
+ End Sub
+
Private Function MakeTrivialExe(Optional directory As String = Nothing) As String
Return Temp.CreateFile(directory:=directory, prefix:="", extension:=".vb").WriteAllText("
Class Program
diff --git a/src/Compilers/VisualBasic/Test/Emit/BasicCompilerEmitTest.vbproj b/src/Compilers/VisualBasic/Test/Emit/BasicCompilerEmitTest.vbproj
index b3b892af154ae..b63d0f9d64a4f 100644
--- a/src/Compilers/VisualBasic/Test/Emit/BasicCompilerEmitTest.vbproj
+++ b/src/Compilers/VisualBasic/Test/Emit/BasicCompilerEmitTest.vbproj
@@ -11,6 +11,7 @@
Roslyn.Compilers.VisualBasic.Emit.UnitTests
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}
UnitTest
diff --git a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb
index 05b2da99f587c..63170568905e5 100644
--- a/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb
+++ b/src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.vb
@@ -7863,6 +7863,336 @@ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Strin
End Sub
+
+ Public Sub TupleCTypeNullableConversionWithTypelessTuple()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertNoDiagnostics()
+ CompileAndVerify(comp, expectedOutput:="(1, )")
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
+ Assert.Equal("(1, Nothing)", node.ToString())
+ Assert.Null(model.GetTypeInfo(node).Type)
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
+
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
+
+ End Sub
+
+
+ Public Sub TupleDirectCastNullableConversionWithTypelessTuple()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertNoDiagnostics()
+ CompileAndVerify(comp, expectedOutput:="(1, )")
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
+ Assert.Equal("(1, Nothing)", node.ToString())
+ Assert.Null(model.GetTypeInfo(node).Type)
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
+
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
+
+ End Sub
+
+
+ Public Sub TupleTryCastNullableConversionWithTypelessTuple()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertTheseDiagnostics(
+BC30792: 'TryCast' operand must be reference type, but '(Integer, String)?' is a value type.
+ Dim x As (Integer, String)? = TryCast((1, Nothing), (Integer, String)?)
+ ~~~~~~~~~~~~~~~~~~
+ )
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
+ Assert.Equal("(1, Nothing)", node.ToString())
+ Assert.Null(model.GetTypeInfo(node).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
+
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
+
+ End Sub
+
+
+ Public Sub TupleTryCastNullableConversionWithTypelessTuple2()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs)
+
+ comp.AssertTheseDiagnostics(
+BC30311: Value of type '(Integer, Object)' cannot be converted to 'C(Of Integer, T)'.
+ Dim x = TryCast((0, Nothing), C(Of Integer, T))
+ ~~~~~~~~~~~~
+ )
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
+ Assert.Equal("(0, Nothing)", node.ToString())
+ Assert.Null(model.GetTypeInfo(node).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind)
+
+ Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString())
+ Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString())
+
+ End Sub
+
+
+ Public Sub TupleImplicitNullableConversionWithTypelessTuple()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertNoDiagnostics()
+ CompileAndVerify(comp, expectedOutput:="(1, )")
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single()
+ Assert.Equal("(1, Nothing)", node.ToString())
+ Assert.Null(model.GetTypeInfo(node).Type)
+ Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind)
+
+ End Sub
+
+
+ Public Sub ImplicitConversionOnTypelessTupleWithUserConversion()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertTheseDiagnostics(
+BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'.
+ Dim y As C? = (2, Nothing)
+ ~~~~~~~~~~~~
+ )
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
+ Assert.Equal("(1, Nothing)", firstTuple.ToString())
+ Assert.Null(model.GetTypeInfo(firstTuple).Type)
+ Assert.Equal("C", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(firstTuple).Kind)
+
+ Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
+ Assert.Equal("(2, Nothing)", secondTuple.ToString())
+ Assert.Null(model.GetTypeInfo(secondTuple).Type)
+ Assert.Equal("System.Nullable(Of C)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(secondTuple).Kind)
+
+ End Sub
+
+
+ Public Sub DirectCastOnTypelessTupleWithUserConversion()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertTheseDiagnostics(
+BC30311: Value of type '(Integer, Object)' cannot be converted to 'C'.
+ Dim x = DirectCast((1, Nothing), C)
+ ~~~~~~~~~~~~
+BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'.
+ Dim y = DirectCast((2, Nothing), C?)
+ ~~~~~~~~~~~~
+ )
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
+ Assert.Equal("(1, Nothing)", firstTuple.ToString())
+ Assert.Null(model.GetTypeInfo(firstTuple).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind)
+
+ Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
+ Assert.Equal("(2, Nothing)", secondTuple.ToString())
+ Assert.Null(model.GetTypeInfo(secondTuple).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind)
+
+ End Sub
+
+
+ Public Sub TryCastOnTypelessTupleWithUserConversion()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertTheseDiagnostics(
+BC30792: 'TryCast' operand must be reference type, but 'C' is a value type.
+ Dim x = TryCast((1, Nothing), C)
+ ~
+BC30792: 'TryCast' operand must be reference type, but 'C?' is a value type.
+ Dim y = TryCast((2, Nothing), C?)
+ ~~
+ )
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
+ Assert.Equal("(1, Nothing)", firstTuple.ToString())
+ Assert.Null(model.GetTypeInfo(firstTuple).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind)
+
+ Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
+ Assert.Equal("(2, Nothing)", secondTuple.ToString())
+ Assert.Null(model.GetTypeInfo(secondTuple).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind)
+
+ End Sub
+
+
+ Public Sub CTypeOnTypelessTupleWithUserConversion()
+ Dim comp = CreateCompilationWithMscorlibAndVBRuntime(
+
+
+, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe)
+
+ comp.AssertTheseDiagnostics(
+BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'.
+ Dim y = CType((2, Nothing), C?)
+ ~~~~~~~~~~~~
+ )
+
+ Dim tree = comp.SyntaxTrees.Single()
+ Dim model = comp.GetSemanticModel(tree)
+ Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0)
+ Assert.Equal("(1, Nothing)", firstTuple.ToString())
+ Assert.Null(model.GetTypeInfo(firstTuple).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind)
+
+ Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1)
+ Assert.Equal("(2, Nothing)", secondTuple.ToString())
+ Assert.Null(model.GetTypeInfo(secondTuple).Type)
+ Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString())
+ Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind)
+
+ End Sub
+
Public Sub TupleTargetTypeLambda()
@@ -8261,6 +8591,35 @@ End Module
End Sub
+
+
+
+ Public Sub GetSymbolInfo_01()
+ Dim source = "
+ Class C
+ Shared Sub Main()
+ Dim x1 = (Alice:=1, ""hello"")
+
+ Dim Alice = x1.Alice
+ End Sub
+End Class
+ "
+
+ Dim tree = Parse(source, options:=TestOptions.Regular)
+ Dim comp = CreateCompilationWithMscorlib(tree)
+
+ Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False)
+ Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes()
+
+ Dim nc = nodes.OfType(Of NameColonEqualsSyntax)().ElementAt(0)
+
+ Dim sym = model.GetSymbolInfo(nc.Name)
+
+ Assert.Equal("Alice", sym.Symbol.Name)
+ Assert.Equal(SymbolKind.Field, sym.Symbol.Kind) ' Incorrectly returns Local
+ Assert.Equal(nc.Name.GetLocation(), sym.Symbol.Locations(0)) ' Incorrect location
+ End Sub
+
Public Sub RetargetTupleErrorType()
Dim libComp = CreateCompilationWithMscorlibAndVBRuntime(
diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb
index eecd8ec2417cb..89023dcc6d729 100644
--- a/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb
+++ b/src/Compilers/VisualBasic/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.vb
@@ -7,8 +7,6 @@ Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Test.Utilities.VBInstrumentationChecker
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests
-Imports Roslyn.Test.Utilities
-Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.DynamicAnalysis.UnitTests
@@ -2368,6 +2366,173 @@ End Class
AssertInstrumented(verifier, "D.M")
End Sub
+
+ Public Sub TestPartialMethodsWithImplementation()
+ Dim testSource =
+ 0
+ Console.WriteLine("Method1: x > 0")
+ Method1(0)
+ ElseIf x < 0
+ Console.WriteLine("Method1: x < 0")
+ End If
+ End Sub
+End Class
+
+Module Program
+ Public Sub Main()
+ Test()
+ Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()
+ End Sub
+
+ Sub Test()
+ Console.WriteLine("Test")
+ Dim c = new Class1()
+ c.Method2(1)
+ End Sub
+End Module
+]]>
+
+
+ Dim source =
+ <%= testSource %>
+ <%= InstrumentationHelperSource %>
+
+
+ Dim checker = New VBInstrumentationChecker()
+ checker.Method(1, 1, "New", expectBodySpan:=False)
+ checker.Method(2, 1, "Private Sub Method1(x as Integer)").
+ True("Console.WriteLine(""Method1: x = {0}"", x)").
+ True("Console.WriteLine(""Method1: x > 0"")").
+ True("Method1(0)").
+ False("Console.WriteLine(""Method1: x < 0"")").
+ True("x < 0").
+ True("x > 0")
+ checker.Method(3, 1, "Public Sub Method2(x as Integer)").
+ True("Console.WriteLine(""Method2: x = {0}"", x)").
+ True("Method1(x)")
+ checker.Method(4, 1, "Public Sub Main()").
+ True("Test()").
+ True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
+ checker.Method(5, 1, "Sub Test()").
+ True("Console.WriteLine(""Test"")").
+ True("new Class1()").
+ True("c.Method2(1)")
+ checker.Method(8, 1).
+ True().
+ False().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True()
+
+ Dim expectedOutput = "Test
+Method2: x = 1
+Method1: x = 1
+Method1: x > 0
+Method1: x = 0
+" + XCDataToString(checker.ExpectedOutput)
+
+ Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
+ checker.CompleteCheck(verifier.Compilation, testSource)
+ verifier.VerifyDiagnostics()
+
+ verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
+ checker.CompleteCheck(verifier.Compilation, testSource)
+ verifier.VerifyDiagnostics()
+ End Sub
+
+
+ Public Sub TestPartialMethodsWithoutImplementation()
+ Dim testSource =
+
+
+
+ Dim source =
+ <%= testSource %>
+ <%= InstrumentationHelperSource %>
+
+
+ Dim checker = New VBInstrumentationChecker()
+ checker.Method(1, 1, "New", expectBodySpan:=False)
+ checker.Method(2, 1, "Public Sub Method2(x as Integer)").
+ True("Console.WriteLine(""Method2: x = {0}"", x)")
+ checker.Method(3, 1, "Public Sub Main()").
+ True("Test()").
+ True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()")
+ checker.Method(4, 1, "Sub Test()").
+ True("Console.WriteLine(""Test"")").
+ True("new Class1()").
+ True("c.Method2(1)")
+ checker.Method(7, 1).
+ True().
+ False().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True().
+ True()
+
+ Dim expectedOutput = "Test
+Method2: x = 1
+" + XCDataToString(checker.ExpectedOutput)
+
+ Dim verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.ReleaseExe)
+ checker.CompleteCheck(verifier.Compilation, testSource)
+ verifier.VerifyDiagnostics()
+
+ verifier = CompileAndVerify(source, expectedOutput, options:=TestOptions.DebugExe)
+ checker.CompleteCheck(verifier.Compilation, testSource)
+ verifier.VerifyDiagnostics()
+ End Sub
+
Private Shared Sub AssertNotInstrumented(verifier As CompilationVerifier, qualifiedMethodName As String)
AssertInstrumented(verifier, qualifiedMethodName, expected:=False)
End Sub
@@ -2394,6 +2559,14 @@ End Class
emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
End Function
+ Private Overloads Function CompileAndVerify(source As XElement, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
+ Return CompileAndVerify(source,
+ LatestVbReferences,
+ expectedOutput,
+ options:=If(options, TestOptions.ReleaseExe).WithDeterministic(True),
+ emitOptions:=EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)))
+ End Function
+
Private Overloads Function CompileAndVerify(source As String, Optional expectedOutput As String = Nothing, Optional options As VisualBasicCompilationOptions = Nothing) As CompilationVerifier
Return CompileAndVerify(source,
LatestVbReferences,
diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.vb
index e7dda329a77fd..7542cc44b18b0 100644
--- a/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.vb
+++ b/src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.vb
@@ -18,6 +18,107 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class EditAndContinueTests
Inherits EditAndContinueTestBase
+
+ Public Sub SemanticErrors_MethodBody()
+ Dim source0 = MarkedSource("
+Class C
+ Shared Sub E()
+ Dim x As Integer = 1
+ System.Console.WriteLine(x)
+ End Sub
+
+ Shared Sub G()
+ System.Console.WriteLine(1)
+ End Sub
+End Class
+")
+ Dim source1 = MarkedSource("
+Class C
+ Shared Sub E()
+ Dim x = Unknown(2)
+ System.Console.WriteLine(x)
+ End Sub
+
+ Shared Sub G()
+ System.Console.WriteLine(2)
+ End Sub
+End Class
+")
+ Dim compilation0 = CreateCompilationWithMscorlib(source0.Tree, options:=ComSafeDebugDll)
+ Dim compilation1 = compilation0.WithSource(source1.Tree)
+
+ Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E")
+ Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E")
+ Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G")
+ Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G")
+
+ Dim v0 = CompileAndVerify(compilation0)
+ Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)
+ Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo)
+
+ ' Semantic errors are reported only for the bodies of members being emitted.
+ Dim diffError = compilation1.EmitDifference(
+ generation0,
+ ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True)))
+
+ diffError.EmitResult.Diagnostics.Verify(
+ Diagnostic(ERRID.ERR_NameNotDeclared1, "Unknown").WithArguments("Unknown").WithLocation(4, 17))
+
+ Dim diffGood = compilation1.EmitDifference(
+ generation0,
+ ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True)))
+
+ diffGood.EmitResult.Diagnostics.Verify()
+ diffGood.VerifyIL("C.G", "
+{
+ // Code size 9 (0x9)
+ .maxstack 1
+ IL_0000: nop
+ IL_0001: ldc.i4.2
+ IL_0002: call ""Sub System.Console.WriteLine(Integer)""
+ IL_0007: nop
+ IL_0008: ret
+}")
+ End Sub
+
+
+ Public Sub SemanticErrors_Declaration()
+ Dim source0 = MarkedSource("
+Class C
+ Sub G()
+ System.Console.WriteLine(1)
+ End Sub
+End Class
+")
+ Dim source1 = MarkedSource("
+Class C
+ Sub G()
+ System.Console.WriteLine(1)
+ End Sub
+End Class
+
+Class Bad
+ Inherits Bad
+End Class
+")
+ Dim compilation0 = CreateCompilationWithMscorlib(source0.Tree, options:=ComSafeDebugDll)
+ Dim compilation1 = compilation0.WithSource(source1.Tree)
+
+ Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G")
+ Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G")
+
+ Dim v0 = CompileAndVerify(compilation0)
+ Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData)
+ Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo)
+
+ Dim diff = compilation1.EmitDifference(
+ generation0,
+ ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True)))
+
+ diff.EmitResult.Diagnostics.Verify(
+ Diagnostic(ERRID.ERR_TypeInItsInheritsClause1, "Bad").WithArguments("Bad").WithLocation(9, 12))
+ End Sub
+
Public Sub ModifyMethod_WithTuples()
Dim source0 =
@@ -5183,5 +5284,8 @@ End Class")
}
")
End Sub
+
+
+
End Class
End Namespace
diff --git a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTupleTests.vb b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTupleTests.vb
index 3c2dee5be373d..c78d3704c08d5 100644
--- a/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTupleTests.vb
+++ b/src/Compilers/VisualBasic/Test/Emit/PDB/PDBTupleTests.vb
@@ -1,6 +1,7 @@
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Test.Utilities
+Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
@@ -9,16 +10,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Sub Local()
- Dim source =
-
-
-
+"
Dim comp = CreateCompilationWithMscorlib(source, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll)
comp.VerifyPdb("C.F",
@@ -33,9 +31,9 @@ End Class
-
-
-
+
+
+
@@ -46,6 +44,88 @@ End Class
)
End Sub
+
+ Public Sub VariablesAndConstantsInUnreachableCode()
+ Dim source = "
+Imports System
+Imports System.Collections.Generic
+
+Class C(Of T)
+ Enum E
+ A
+ End Enum
+
+ Sub F()
+ Dim v1 As C(Of (a As Integer, b As Integer)).E = Nothing
+ Const c1 As C(Of (a As Integer, b As Integer)).E = Nothing
+
+ Throw New Exception()
+
+ Dim v2 As C(Of (a As Integer, b As Integer)).E = Nothing
+ Const c2 As C(Of (a As Integer, b As Integer)).E = Nothing
+
+ Do
+ Dim v3 As C(Of (a As Integer, b As Integer)).E = Nothing
+ Const c3 As C(Of (a As Integer, b As Integer)).E = Nothing
+ Loop
+ End Sub
+End Class
+"
+ Dim c = CreateCompilationWithMscorlib(source, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll)
+
+ Dim v = CompileAndVerify(c)
+ v.VerifyIL("C(Of T).F()", "
+{
+ // Code size 9 (0x9)
+ .maxstack 1
+ .locals init (C(Of (a As Integer, b As Integer)).E V_0, //v1
+ C(Of (a As Integer, b As Integer)).E V_1, //v2
+ C(Of (a As Integer, b As Integer)).E V_2) //v3
+ IL_0000: nop
+ IL_0001: ldc.i4.0
+ IL_0002: stloc.0
+ IL_0003: newobj ""Sub System.Exception..ctor()""
+ IL_0008: throw
+}
+")
+
+ c.VerifyPdb(
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )
+ End Sub
+
End Class
End Namespace
diff --git a/src/Compilers/VisualBasic/Test/Semantic/BasicCompilerSemanticTest.vbproj b/src/Compilers/VisualBasic/Test/Semantic/BasicCompilerSemanticTest.vbproj
index 3ba2d014bb6af..44e47678f3728 100644
--- a/src/Compilers/VisualBasic/Test/Semantic/BasicCompilerSemanticTest.vbproj
+++ b/src/Compilers/VisualBasic/Test/Semantic/BasicCompilerSemanticTest.vbproj
@@ -11,6 +11,7 @@
Roslyn.Compilers.VisualBasic.Semantic.UnitTests
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}
UnitTest
@@ -107,6 +108,8 @@
+
+
diff --git a/src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IFieldReferenceExpression.vb b/src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IFieldReferenceExpression.vb
new file mode 100644
index 0000000000000..016cd8a89dcb6
--- /dev/null
+++ b/src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IFieldReferenceExpression.vb
@@ -0,0 +1,36 @@
+' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+Imports Microsoft.CodeAnalysis.Semantics
+Imports Microsoft.CodeAnalysis.Test.Utilities
+Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
+Imports Roslyn.Test.Utilities
+
+Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
+
+ Partial Public Class IOperationTests
+ Inherits SemanticModelTestBase
+
+
+ Public Sub FieldReference_Attribute()
+ Dim source = 'BIND:"Conditional(field)"
+ Private Sub M()
+ End Sub
+End Class]]>.Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of AttributeSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+ End Class
+End Namespace
diff --git a/src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IParameterReferenceExpression.vb b/src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IParameterReferenceExpression.vb
new file mode 100644
index 0000000000000..65581f7e4b429
--- /dev/null
+++ b/src/Compilers/VisualBasic/Test/Semantic/IOperation/IOperationTests_IParameterReferenceExpression.vb
@@ -0,0 +1,631 @@
+' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+Imports Microsoft.CodeAnalysis.Semantics
+Imports Microsoft.CodeAnalysis.Test.Utilities
+Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
+Imports Roslyn.Test.Utilities
+
+Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
+
+ Partial Public Class IOperationTests
+ Inherits SemanticModelTestBase
+
+
+ Public Sub ParameterReference_TupleExpression()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of TupleExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_AnonymousObjectCreation()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of AnonymousObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_QueryExpression()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_QueryExpressionAggregateClause()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_QueryExpressionOrderByClause()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_QueryExpressionGroupByClause()
+ Dim source = .Value
+
+ Dim expectedOperationTree = , )(keySelector As System.Func(Of System.String, ), resultSelector As System.Func(Of , System.Collections.Generic.IEnumerable(Of System.String), )) As System.Collections.Generic.IEnumerable(Of )) (OperationKind.InvocationExpression, Type: System.Collections.Generic.IEnumerable(Of )) (Syntax: 'Group By w ... nto Count()')
+ Instance Receiver: IConversionExpression (ConversionKind.Basic, Implicit) (OperationKind.ConversionExpression, Type: System.Collections.Generic.IEnumerable(Of System.String)) (Syntax: 'y In x')
+ IOperation: (OperationKind.None) (Syntax: 'y In x')
+ Children(1): IOperation: (OperationKind.None) (Syntax: 'x')
+ Children(1): IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.String()) (Syntax: 'x')
+ Arguments(2): IArgument (ArgumentKind.DefaultValue, Matching Parameter: keySelector) (OperationKind.Argument) (Syntax: 'x')
+ IConversionExpression (ConversionKind.Basic, Implicit) (OperationKind.ConversionExpression, Type: System.Func(Of System.String, )) (Syntax: 'x')
+ IOperation: (OperationKind.None) (Syntax: 'x')
+ Children(1): IOperation: (OperationKind.None) (Syntax: 'Group By w ... nto Count()')
+ Children(2): IOperation: (OperationKind.None) (Syntax: 'w = x')
+ Children(1): IParameterReferenceExpression: x (OperationKind.ParameterReferenceExpression, Type: System.String()) (Syntax: 'x')
+ IOperation: (OperationKind.None) (Syntax: 'z = y')
+ Children(1): IOperation: (OperationKind.None) (Syntax: 'y')
+ IArgument (ArgumentKind.DefaultValue, Matching Parameter: resultSelector) (OperationKind.Argument) (Syntax: 'Group By w ... nto Count()')
+ IConversionExpression (ConversionKind.Basic, Implicit) (OperationKind.ConversionExpression, Type: System.Func(Of , System.Collections.Generic.IEnumerable(Of System.String), )) (Syntax: 'Group By w ... nto Count()')
+ IOperation: (OperationKind.None) (Syntax: 'Group By w ... nto Count()')
+ Children(1): IOperation: (OperationKind.None) (Syntax: 'Group By w ... nto Count()')
+ Children(3): IOperation: (OperationKind.None) (Syntax: 'w')
+ IOperation: (OperationKind.None) (Syntax: 'z')
+ IOperation: (OperationKind.None) (Syntax: 'Count()')
+ Children(1): IOperation: (OperationKind.None) (Syntax: 'Count()')
+ Children(1): IInvocationExpression ( Function System.Collections.Generic.IEnumerable(Of System.String).Count() As System.Int32) (OperationKind.InvocationExpression, Type: System.Int32) (Syntax: 'Count()')
+ Instance Receiver: IParameterReferenceExpression: $VB$ItAnonymous (OperationKind.ParameterReferenceExpression, Type: System.Collections.Generic.IEnumerable(Of System.String)) (Syntax: 'Group By w ... nto Count()')
+]]>.Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of QueryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_ObjectAndCollectionInitializer()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_NameOfExpression()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of NameOfExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_LateBoundIndexerAccess()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_LateBoundMemberAccess()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_LateBoundInvocation()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_InterpolatedStringExpression()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of InterpolatedStringExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_MidAssignmentStatement()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of AssignmentStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_MisplacedCaseStatement()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = .Value
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of CaseStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_RedimStatement()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of ReDimStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_EraseStatement()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of EraseStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_UnstructuredExceptionHandlingStatement()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_LateAddressOfOperator()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_NullableIsTrueOperator()
+ Dim source = .Value
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = String.Empty
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of MultiLineIfBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
+ End Sub
+
+
+ Public Sub ParameterReference_NoPiaObjectCreation()
+ Dim sources0 =
+
+
+
+
+
+Public Interface I
+ Property P As Integer
+End Interface
+
+Public Class C
+ Public Sub New(o As Object)
+ End Sub
+End Class
+]]>
+
+ Dim sources1 =
+
+
+ Dim compilation0 = CreateCompilationWithMscorlib(sources0)
+ compilation0.AssertTheseDiagnostics()
+
+ ' No errors for /r:_.dll
+ Dim compilation1 = CreateCompilationWithReferences(
+ sources1,
+ references:={MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes:=True)})
+
+ Dim expectedOperationTree = .Value
+
+ Dim expectedDiagnostics = .Value
+
+ VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(compilation1, "a.vb", expectedOperationTree, expectedDiagnostics)
+ End Sub
+ End Class
+End Namespace
diff --git a/src/Compilers/VisualBasic/Test/Symbol/BasicCompilerSymbolTest.vbproj b/src/Compilers/VisualBasic/Test/Symbol/BasicCompilerSymbolTest.vbproj
index 1659ea54b14cc..d522cbc0c274d 100644
--- a/src/Compilers/VisualBasic/Test/Symbol/BasicCompilerSymbolTest.vbproj
+++ b/src/Compilers/VisualBasic/Test/Symbol/BasicCompilerSymbolTest.vbproj
@@ -11,6 +11,7 @@
Roslyn.Compilers.VisualBasic.Symbol.UnitTests
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}
UnitTest
diff --git a/src/Compilers/VisualBasic/Test/Syntax/BasicCompilerSyntaxTest.vbproj b/src/Compilers/VisualBasic/Test/Syntax/BasicCompilerSyntaxTest.vbproj
index cbfc5084f0e54..d2a065d42983b 100644
--- a/src/Compilers/VisualBasic/Test/Syntax/BasicCompilerSyntaxTest.vbproj
+++ b/src/Compilers/VisualBasic/Test/Syntax/BasicCompilerSyntaxTest.vbproj
@@ -11,6 +11,7 @@
Roslyn.Compilers.VisualBasic.Syntax.UnitTests
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}
UnitTest
diff --git a/src/Compilers/VisualBasic/vbc/Program.cs b/src/Compilers/VisualBasic/vbc/Program.cs
index 0422f7a3c2079..7aef6f564b99a 100644
--- a/src/Compilers/VisualBasic/vbc/Program.cs
+++ b/src/Compilers/VisualBasic/vbc/Program.cs
@@ -1,19 +1,30 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+using System;
using System.IO;
using Microsoft.CodeAnalysis.CommandLine;
-using Roslyn.Utilities;
-using System;
namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine
{
public class Program
{
public static int Main(string[] args)
- => Main(args, Array.Empty());
+ {
+ try
+ {
+ return MainCore(args);
+ }
+ catch (FileNotFoundException e)
+ {
+ // Catch exception from missing compiler assembly.
+ // Report the exception message and terminate the process.
+ Console.WriteLine(e.Message);
+ return CommonCompiler.Failed;
+ }
+ }
- public static int Main(string[] args, string[] extraArgs)
- => DesktopBuildClient.Run(args, extraArgs, RequestLanguage.VisualBasicCompile, Vbc.Run, new DesktopAnalyzerAssemblyLoader());
+ private static int MainCore(string[] args)
+ => DesktopBuildClient.Run(args, RequestLanguage.VisualBasicCompile, Vbc.Run, new DesktopAnalyzerAssemblyLoader());
public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader)
=> Vbc.Run(args, new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir), textWriter, analyzerLoader);
diff --git a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs
index df00e9a350471..3c674d113aea5 100644
--- a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs
+++ b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs
@@ -4554,5 +4554,54 @@ void M()
}
}");
}
+
+ [WorkItem(19218, "https://github.com/dotnet/roslyn/issues/19218")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
+ public async Task TestChangeCaseWithUsingsInNestedNamespace()
+ {
+ await TestInRegularAndScriptAsync(
+@"namespace VS
+{
+ interface IVsStatusbar
+ {
+ }
+}
+
+namespace Outer
+{
+ using System;
+
+ class C
+ {
+ void M()
+ {
+ // Note: IVsStatusBar is cased incorrectly.
+ [|IVsStatusBar|] b;
+ }
+ }
+}
+",
+@"namespace VS
+{
+ interface IVsStatusbar
+ {
+ }
+}
+
+namespace Outer
+{
+ using System;
+ using VS;
+
+ class C
+ {
+ void M()
+ {
+ IVsStatusbar b;
+ }
+ }
+}
+");
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_NuGet.cs b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_NuGet.cs
index 53155eedcb87e..28f2e728a387f 100644
--- a/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_NuGet.cs
+++ b/src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_NuGet.cs
@@ -54,7 +54,7 @@ public async Task TestSearchPackageSingleName()
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock(MockBehavior.Loose);
- installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
+ installerServiceMock.Setup(i => i.IsEnabled(It.IsAny())).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny(), It.IsAny(), It.IsAny(), "NuGetPackage", It.IsAny(), It.IsAny(), It.IsAny()))
.Returns(true);
@@ -83,7 +83,7 @@ public async Task TestSearchPackageMultipleNames()
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock(MockBehavior.Loose);
- installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
+ installerServiceMock.Setup(i => i.IsEnabled(It.IsAny())).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny(), It.IsAny(), It.IsAny(), "NuGetPackage", It.IsAny(), It.IsAny(), It.IsAny()))
.Returns(true);
@@ -112,7 +112,7 @@ public async Task TestMissingIfPackageAlreadyInstalled()
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock(MockBehavior.Loose);
- installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
+ installerServiceMock.Setup(i => i.IsEnabled(It.IsAny())).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.IsInstalled(It.IsAny(), It.IsAny(), "NuGetPackage"))
.Returns(true);
@@ -135,7 +135,7 @@ public async Task TestOptionsOffered()
// Make a loose mock for the installer service. We don't care what this test
// calls on it.
var installerServiceMock = new Mock(MockBehavior.Loose);
- installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
+ installerServiceMock.Setup(i => i.IsEnabled(It.IsAny())).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage"))
.Returns(ImmutableArray.Create("1.0", "2.0"));
@@ -177,7 +177,7 @@ await TestSmartTagTextAsync(
public async Task TestInstallGetsCalledNoVersion()
{
var installerServiceMock = new Mock(MockBehavior.Loose);
- installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
+ installerServiceMock.Setup(i => i.IsEnabled(It.IsAny())).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny(), It.IsAny(), It.IsAny(), "NuGetPackage", /*versionOpt*/ null, It.IsAny(), It.IsAny()))
.Returns(true);
@@ -205,7 +205,7 @@ class C
public async Task TestInstallGetsCalledWithVersion()
{
var installerServiceMock = new Mock(MockBehavior.Loose);
- installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
+ installerServiceMock.Setup(i => i.IsEnabled(It.IsAny())).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage"))
.Returns(ImmutableArray.Create("1.0"));
@@ -235,7 +235,7 @@ class C
public async Task TestFailedInstallRollsBackFile()
{
var installerServiceMock = new Mock(MockBehavior.Loose);
- installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true);
+ installerServiceMock.Setup(i => i.IsEnabled(It.IsAny())).Returns(true);
installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources);
installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage"))
.Returns(ImmutableArray.Create("1.0"));
diff --git a/src/EditorFeatures/CSharpTest/CSharpEditorServicesTest.csproj b/src/EditorFeatures/CSharpTest/CSharpEditorServicesTest.csproj
index cc0cccb814266..24d00d4664012 100644
--- a/src/EditorFeatures/CSharpTest/CSharpEditorServicesTest.csproj
+++ b/src/EditorFeatures/CSharpTest/CSharpEditorServicesTest.csproj
@@ -146,6 +146,7 @@
Library
Microsoft.CodeAnalysis.Editor.CSharp.UnitTests
Roslyn.Services.Editor.CSharp.UnitTests
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
UnitTest
@@ -294,7 +295,6 @@
-
@@ -307,8 +307,8 @@
-
-
+
+
@@ -397,6 +397,13 @@
+
+
+
+
+
+
+
@@ -432,13 +439,13 @@
-
-
-
-
-
-
-
+
+
+
+
+
+
+
diff --git a/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs
index 9b5a317f94b7d..9cbed1ce3a764 100644
--- a/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs
+++ b/src/EditorFeatures/CSharpTest/CodeActions/IntroduceVariable/IntroduceVariableTests.cs
@@ -8,7 +8,6 @@
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
-using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
@@ -556,7 +555,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
}
@@ -574,7 +573,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
}
@@ -600,7 +599,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
}
@@ -618,7 +617,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
}
@@ -643,7 +642,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
@@ -658,7 +657,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
@@ -681,7 +680,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
@@ -696,7 +695,7 @@ public class @class
{
}
- public static void Add(object t)
+ public static void Add(object @class)
{
}
@@ -2180,8 +2179,8 @@ int Main(int i)
switch (1)
{
case 0:
- const int {|Rename:V|} = 1 + 1;
- var f = Main(V);
+ const int {|Rename:I|} = 1 + 1;
+ var f = Main(I);
Console.WriteLine(f);
}
}
@@ -2432,8 +2431,8 @@ class C
static void Main(string[] args)
{
var set = new HashSet();
- var {|Rename:v|} = set.ToString();
- set.Add(v);
+ var {|Rename:item|} = set.ToString();
+ set.Add(item);
}
}",
options: ImplicitTypingEverywhere());
@@ -2530,8 +2529,8 @@ class Program
static void Main(string[] args)
{
var d = new Dictionary();
- var {|Rename:exception|} = new Exception();
- d.Add(""a"", exception);
+ var {|Rename:value|} = new Exception();
+ d.Add(""a"", value);
}
}",
ignoreTrivia: false, options: ImplicitTypingEverywhere());
@@ -3091,8 +3090,8 @@ class Complex
int real; int imaginary;
public static Complex operator +(Complex a, Complex b)
{
- var {|Rename:v|} = b.real + 1;
- return a.Add(v);
+ var {|Rename:b1|} = b.real + 1;
+ return a.Add(b1);
}
private Complex Add(int b)
@@ -3161,7 +3160,7 @@ public struct DBBool
@"using System;
public struct DBBool
{
- private const int {|Rename:V|} = 1;
+ private const int {|Rename:Value|} = 1;
public static readonly DBBool dbFalse = new DBBool(-1);
int value;
@@ -3170,7 +3169,7 @@ public struct DBBool
this.value = value;
}
- public static implicit operator DBBool(bool x) => x ? new DBBool(V) : dbFalse;
+ public static implicit operator DBBool(bool x) => x ? new DBBool(Value) : dbFalse;
}";
await TestInRegularAndScriptAsync(code, expected, ignoreTrivia: false);
@@ -3574,8 +3573,8 @@ class TestClass
{
static void Test(string[] args)
{
- var {|Rename:v|} = $""{DateTime.Now.ToString()}Text{args[0]}"";
- Console.WriteLine(v);
+ var {|Rename:value|} = $""{DateTime.Now.ToString()}Text{args[0]}"";
+ Console.WriteLine(value);
}
}";
@@ -3603,9 +3602,9 @@ class TestClass
{
static void Test(string[] args)
{
- var {|Rename:v|} = $""Text{{s}}"";
- Console.WriteLine(v);
- Console.WriteLine(v);
+ var {|Rename:value|} = $""Text{{s}}"";
+ Console.WriteLine(value);
+ Console.WriteLine(value);
}
}";
@@ -3773,8 +3772,8 @@ class C
{
public async Task M()
{
- FormattableString {|Rename:v|} = $"""";
- var f = FormattableString.Invariant(v);
+ FormattableString {|Rename:formattable|} = $"""";
+ var f = FormattableString.Invariant(formattable);
}
}
}";
@@ -4254,5 +4253,81 @@ void M()
await TestInRegularAndScriptAsync(code, expected, index: 1, ignoreTrivia: false);
}
+
+ [WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
+ public async Task TestPickNameBasedOnArgument1()
+ {
+ await TestInRegularAndScriptAsync(
+@"class C
+{
+ public C(string a, string b)
+ {
+ new TextSpan([|int.Parse(a)|], int.Parse(b));
+ }
+}
+
+struct TextSpan
+{
+ public TextSpan(int start, int length)
+ {
+
+ }
+}",
+@"class C
+{
+ public C(string a, string b)
+ {
+ int {|Rename:start|} = int.Parse(a);
+ new TextSpan(start, int.Parse(b));
+ }
+}
+
+struct TextSpan
+{
+ public TextSpan(int start, int length)
+ {
+
+ }
+}");
+ }
+
+ [WorkItem(2423, "https://github.com/dotnet/roslyn/issues/2423")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
+ public async Task TestPickNameBasedOnArgument2()
+ {
+ await TestInRegularAndScriptAsync(
+@"class C
+{
+ public C(string a, string b)
+ {
+ new TextSpan(int.Parse(a), [|int.Parse(b)|]);
+ }
+}
+
+struct TextSpan
+{
+ public TextSpan(int start, int length)
+ {
+
+ }
+}",
+@"class C
+{
+ public C(string a, string b)
+ {
+ int {|Rename:length|} = int.Parse(b);
+ new TextSpan(int.Parse(a), length);
+ }
+}
+
+struct TextSpan
+{
+ public TextSpan(int start, int length)
+ {
+
+ }
+}");
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs b/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs
index 2fe206b531079..d868634b125b9 100644
--- a/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs
+++ b/src/EditorFeatures/CSharpTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.cs
@@ -1363,7 +1363,7 @@ await TestInRegularAndScriptAsync(
@"internal interface ILanguageServiceHost
{
///
- /// Gets the active workspace project context that provides access to the language service for the active configured project.
+ /// Sets the active workspace project context that provides access to the language service for the active configured project.
///
///
/// An value that provides access to the language service for the active configured project.
@@ -1376,11 +1376,11 @@ object [||]ActiveProjectContext
@"internal interface ILanguageServiceHost
{
///
- /// Gets the active workspace project context that provides access to the language service for the active configured project.
+ /// Sets the active workspace project context that provides access to the language service for the active configured project.
///
- ///
+ ///
/// An value that provides access to the language service for the active configured project.
- ///
+ ///
void SetActiveProjectContext(object value);
}", ignoreTrivia: false);
}
@@ -1393,7 +1393,7 @@ await TestInRegularAndScriptAsync(
@"internal interface ILanguageServiceHost
{
///
- /// Gets the active workspace project context that provides access to the language service for the active configured project.
+ /// Gets or sets the active workspace project context that provides access to the language service for the active configured project.
///
///
/// An value that provides access to the language service for the active configured project.
@@ -1406,17 +1406,246 @@ object [||]ActiveProjectContext
@"internal interface ILanguageServiceHost
{
///
- /// Gets the active workspace project context that provides access to the language service for the active configured project.
+ /// Gets or sets the active workspace project context that provides access to the language service for the active configured project.
///
///
/// An value that provides access to the language service for the active configured project.
///
object GetActiveProjectContext();
+
+ ///
+ /// Gets or sets the active workspace project context that provides access to the language service for the active configured project.
+ ///
+ ///
+ /// An value that provides access to the language service for the active configured project.
+ ///
+ void SetActiveProjectContext(object value);
+}", ignoreTrivia: false);
+ }
+
+ [WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
+ public async Task TestDocumentationComment4()
+ {
+ await TestInRegularAndScriptAsync(
+@"internal interface ILanguageServiceHost
+{
+ ///
+ /// Sets .
+ ///
+ ///
+ object [||]ActiveProjectContext
+ {
+ set;
+ }
+}
+internal struct AStruct
+{
+ ///
+ private int x;
+}",
+@"internal interface ILanguageServiceHost
+{
+ ///
+ /// Sets .
+ ///
+ ///
+ void SetActiveProjectContext(object value);
+}
+internal struct AStruct
+{
+ ///
+ private int x;
+}", ignoreTrivia: false);
+ }
+
+ [WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
+ public async Task TestDocumentationComment5()
+ {
+ await TestInRegularAndScriptAsync(
+@"internal interface ILanguageServiceHost
+{
+ ///
+ /// Gets or sets .
+ ///
+ ///
+ object [||]ActiveProjectContext
+ {
+ get; set;
+ }
+}
+internal struct AStruct
+{
+ ///
+ private int x;
+}",
+@"internal interface ILanguageServiceHost
+{
+ ///
+ /// Gets or sets .
+ ///
+ ///
+ object GetActiveProjectContext();
+
+ ///
+ /// Gets or sets .
+ ///
+ ///
void SetActiveProjectContext(object value);
+}
+internal struct AStruct
+{
+ ///
+ private int x;
+}", ignoreTrivia: false);
+ }
+
+ [WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
+ public async Task TestDocumentationComment6()
+ {
+ await TestInRegularAndScriptAsync(
+@"internal interface ISomeInterface
+{
+ ///
+ ISomeInterface [||]Context
+ {
+ set;
+ }
+}
+internal struct AStruct
+{
+ ///
+ private int x;
+}",
+@"internal interface ISomeInterface
+{
+ ///
+ void SetContext(ISomeInterface value);
+}
+internal struct AStruct
+{
+ ///
+ private int x;
+}", ignoreTrivia: false);
+ }
+
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
+ public async Task TestWithDirectives1()
+ {
+ await TestInRegularAndScriptAsync(
+@"class C
+{
+ int [||]Prop
+ {
+ get
+ {
+#if true
+ return 0;
+#else
+ return 1;
+#endif
+ }
+ }
+}",
+ @"class C
+{
+ private int GetProp()
+ {
+#if true
+ return 0;
+#else
+ return 1;
+#endif
+ }
+}", ignoreTrivia: false);
+ }
+
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
+ public async Task TestWithDirectives2()
+ {
+ await TestInRegularAndScriptAsync(
+@"class C
+{
+ int [||]Prop
+ {
+ get
+ {
+#if true
+ return 0;
+#else
+ return 1;
+#endif
+ }
+ }
+}",
+ @"class C
+{
+ private int GetProp() =>
+#if true
+ 0;
+#else
+ return 1;
+#endif
+}", ignoreTrivia: false,
+ options: PreferExpressionBodiedMethods);
+ }
+
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
+ public async Task TestWithDirectives3()
+ {
+ await TestInRegularAndScriptAsync(
+@"class C
+{
+ int [||]Prop =>
+#if true
+ 0;
+#else
+ 1;
+#endif
+}",
+@"class C
+{
+ private int GetProp() =>
+#if true
+ 0;
+#else
+ 1;
+#endif
}", ignoreTrivia: false);
}
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)]
+ public async Task TestWithDirectives4()
+ {
+ await TestInRegularAndScriptAsync(
+@"class C
+{
+ int [||]Prop =>
+#if true
+ 0;
+#else
+ 1;
+#endif
+}",
+@"class C
+{
+ private int GetProp() =>
+#if true
+ 0;
+#else
+ 1;
+#endif
+}", ignoreTrivia: false,
+ options: PreferExpressionBodiedMethods);
+ }
+
private IDictionary PreferExpressionBodiedMethods =>
OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement));
}
-}
\ No newline at end of file
+}
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs
index 5b99c51236817..f66cd2e8496bf 100644
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/EnumAndCompletionListTagCompletionProviderTests.cs
@@ -16,9 +16,7 @@ public EnumAndCompletionListTagCompletionProviderTests(CSharpTestWorkspaceFixtur
}
internal override CompletionProvider CreateCompletionProvider()
- {
- return new EnumAndCompletionListTagCompletionProvider();
- }
+ => new EnumAndCompletionListTagCompletionProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableEnum()
@@ -518,5 +516,105 @@ enum E
";
await VerifyNoItemsExistAsync(markup);
}
+
+ [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
+ [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ public async Task TestInEnumInitializer1()
+ {
+ var markup =
+@"using System;
+
+[Flags]
+internal enum ProjectTreeWriterOptions
+{
+ None,
+ Tags,
+ FilePath,
+ Capabilities,
+ Visibility,
+ AllProperties = FilePath | Visibility | $$
+}";
+ await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
+ }
+
+ [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
+ [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ public async Task TestInEnumInitializer2()
+ {
+ var markup =
+@"using System;
+
+[Flags]
+internal enum ProjectTreeWriterOptions
+{
+ None,
+ Tags,
+ FilePath,
+ Capabilities,
+ Visibility,
+ AllProperties = FilePath | $$ Visibility
+}";
+ await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
+ }
+
+ [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
+ [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ public async Task TestInEnumInitializer3()
+ {
+ var markup =
+@"using System;
+
+[Flags]
+internal enum ProjectTreeWriterOptions
+{
+ None,
+ Tags,
+ FilePath,
+ Capabilities,
+ Visibility,
+ AllProperties = FilePath | $$ | Visibility
+}";
+ await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
+ }
+
+ [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
+ [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ public async Task TestInEnumInitializer4()
+ {
+ var markup =
+@"using System;
+
+[Flags]
+internal enum ProjectTreeWriterOptions
+{
+ None,
+ Tags,
+ FilePath,
+ Capabilities,
+ Visibility,
+ AllProperties = FilePath ^ $$
+}";
+ await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
+ }
+
+ [WorkItem(5419, "https://github.com/dotnet/roslyn/issues/5419")]
+ [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ public async Task TestInEnumInitializer5()
+ {
+ var markup =
+@"using System;
+
+[Flags]
+internal enum ProjectTreeWriterOptions
+{
+ None,
+ Tags,
+ FilePath,
+ Capabilities,
+ Visibility,
+ AllProperties = FilePath & $$
+}";
+ await VerifyItemExistsAsync(markup, "ProjectTreeWriterOptions");
+ }
}
-}
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/GlobalAssemblyCacheCompletionHelperTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/GlobalAssemblyCacheCompletionHelperTests.cs
deleted file mode 100644
index 890aa50a1db85..0000000000000
--- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/GlobalAssemblyCacheCompletionHelperTests.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Completion;
-using Microsoft.CodeAnalysis.Editor.Completion.FileSystem;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Test.Utilities;
-using Xunit;
-
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntelliSense.CompletionSetSources
-{
- public class GlobalAssemblyCacheCompletionHelperTests
- {
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public void ExistingReference()
- {
- var code = "System.Windows";
- VerifyPresence(code, "System.Windows.Forms");
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public void FullReferenceIdentity()
- {
- var code = "System,";
- VerifyPresence(code, typeof(System.Diagnostics.Process).Assembly.FullName);
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public void FullReferenceIdentityDescription()
- {
- var code = "System";
- var completions = GetItems(code);
- var systemsColl = from completion in completions
- where completion.DisplayText == "System"
- select completion;
-
- Assert.True(systemsColl.Any(
- completion => CommonCompletionItem.GetDescription(completion).Text == typeof(System.Diagnostics.Process).Assembly.FullName));
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public void NothingOnForwardSlash()
- {
- var code = "System.Windows/";
- VerifyAbsence(code);
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public void NothingOnBackSlash()
- {
- var code = @"System.Windows\";
- VerifyAbsence(code);
- }
-
- private static void VerifyPresence(string pathSoFar, string completionItem)
- {
- var completions = GetItems(pathSoFar);
- Assert.True(completions.Any(c => c.DisplayText == completionItem));
- }
-
- private static void VerifyAbsence(string pathSoFar)
- {
- var completions = GetItems(pathSoFar);
- Assert.True(completions == null || !completions.Any(), "Expected null or non-empty completions");
- }
-
- private static IEnumerable GetItems(string pathSoFar)
- {
- var helper = new GlobalAssemblyCacheCompletionHelper(null, new TextSpan());
-
- return helper.GetItems(pathSoFar, documentPath: null);
- }
- }
-}
diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/LoadDirectiveCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/LoadDirectiveCompletionProviderTests.cs
new file mode 100644
index 0000000000000..f0ef0ce6d1106
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/LoadDirectiveCompletionProviderTests.cs
@@ -0,0 +1,69 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.Completion;
+using Microsoft.CodeAnalysis.Editor.CSharp.Completion.FileSystem;
+using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
+{
+ [Trait(Traits.Feature, Traits.Features.Completion)]
+ public class LoadDirectiveCompletionProviderTests : AbstractCSharpCompletionProviderTests
+ {
+ public LoadDirectiveCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
+ {
+ }
+
+ internal override CompletionProvider CreateCompletionProvider()
+ {
+ return new LoadDirectiveCompletionProvider();
+ }
+
+ protected override bool CompareItems(string actualItem, string expectedItem)
+ {
+ return actualItem.Equals(expectedItem, StringComparison.OrdinalIgnoreCase);
+ }
+
+ protected override Task VerifyWorkerAsync(
+ string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull,
+ SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
+ int? glyph, int? matchPriority, bool? hasSuggestionItem)
+ {
+ return BaseVerifyWorkerAsync(
+ code, position, expectedItemOrNull, expectedDescriptionOrNull,
+ sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence,
+ glyph, matchPriority, hasSuggestionItem);
+ }
+
+ [Fact]
+ public async Task IsCommitCharacterTest()
+ {
+ var commitCharacters = new[] { '"', '\\' };
+ await VerifyCommitCharactersAsync("#load \"$$", textTypedSoFar: "", validChars: commitCharacters);
+ }
+
+ [Fact]
+ public void IsTextualTriggerCharacterTest()
+ {
+ var validMarkupList = new[]
+ {
+ "#load \"$$/",
+ "#load \"$$\\",
+ "#load \"$$,",
+ "#load \"$$A",
+ "#load \"$$!",
+ "#load \"$$(",
+ };
+
+ foreach (var markup in validMarkupList)
+ {
+ VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true);
+ }
+ }
+ }
+}
diff --git a/src/EditorFeatures/CSharpTest/Completion/ReferenceDirectiveCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs
similarity index 55%
rename from src/EditorFeatures/CSharpTest/Completion/ReferenceDirectiveCompletionProviderTests.cs
rename to src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs
index 1004329dbd9d5..67d4b98cac117 100644
--- a/src/EditorFeatures/CSharpTest/Completion/ReferenceDirectiveCompletionProviderTests.cs
+++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ReferenceDirectiveCompletionProviderTests.cs
@@ -6,13 +6,14 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.CSharp.Completion.FileSystem;
-using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
+using Roslyn.Utilities;
using Xunit;
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntelliSense.CompletionSetSources
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
+ [Trait(Traits.Feature, Traits.Features.Completion)]
public class ReferenceDirectiveCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
public ReferenceDirectiveCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
@@ -40,50 +41,33 @@ protected override Task VerifyWorkerAsync(
glyph, matchPriority, hasSuggestionItem);
}
- private async Task VerifyItemsExistInScriptAndInteractiveAsync(string code, params string[] expected)
- {
- foreach (var ex in expected)
- {
- await VerifyItemExistsAsync(code, ex, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
- }
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ [Fact]
public async Task IsCommitCharacterTest()
{
- var commitCharacters = new[] { '"', '\\', ',' };
+ var commitCharacters = PathUtilities.IsUnixLikePlatform ? new[] { '"', '/' } : new[] { '"', '\\', '/', ',' };
await VerifyCommitCharactersAsync("#r \"$$", textTypedSoFar: "", validChars: commitCharacters);
}
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ [Fact]
public void IsTextualTriggerCharacterTest()
{
var validMarkupList = new[]
{
+ "#r \"$$/",
"#r \"$$\\",
"#r \"$$,",
- "#r \"$$A"
- };
-
- foreach (var markup in validMarkupList)
- {
- VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true);
- }
-
- var invalidMarkupList = new[]
- {
- "#r \"$$/",
+ "#r \"$$A",
"#r \"$$!",
"#r \"$$(",
};
- foreach (var markup in invalidMarkupList)
+ foreach (var markup in validMarkupList)
{
- VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: false, shouldTriggerWithTriggerOnLettersDisabled: false);
+ VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true);
}
}
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ [ConditionalFact(typeof(WindowsOnly))]
public async Task SendEnterThroughToEditorTest()
{
await VerifySendEnterThroughToEnterAsync("#r \"System$$", "System", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
@@ -91,57 +75,34 @@ public async Task SendEnterThroughToEditorTest()
await VerifySendEnterThroughToEnterAsync("#r \"System$$", "System", sendThroughEnterOption: EnterKeyRule.Always, expected: false); // note: GAC completion helper uses its own EnterKeyRule
}
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public async Task RootDrives()
- {
- // ensure drives are listed without the trailing backslash
- var drive = Environment.GetLogicalDrives().First().TrimEnd('\\');
- await VerifyItemsExistInScriptAndInteractiveAsync(
- "#r \"$$",
- drive);
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public async Task RelativeDirectories()
- {
- await VerifyItemsExistInScriptAndInteractiveAsync(
- "#r \"$$",
- ".",
- "..");
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public async Task GACReference()
+ [ConditionalFact(typeof(WindowsOnly))]
+ public async Task GacReference()
{
- await VerifyItemsExistInScriptAndInteractiveAsync(
- "#r \"$$",
- "System.Windows.Forms");
+ await VerifyItemExistsAsync("#r \"$$", "System.Windows.Forms", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public async Task GACReferenceFullyQualified()
+ [ConditionalFact(typeof(WindowsOnly))]
+ public async Task GacReferenceFullyQualified()
{
- await VerifyItemsExistInScriptAndInteractiveAsync(
- "#r \"System.Windows.Forms,$$",
- "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
+ await VerifyItemExistsAsync(
+ "#r \"System.Windows.Forms,$$",
+ "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
+ [ConditionalFact(typeof(WindowsOnly))]
public async Task FileSystemReference()
{
- string systemDir = Path.GetFullPath(Environment.SystemDirectory);
- DirectoryInfo windowsDir = System.IO.Directory.GetParent(systemDir);
- string windowsDirPath = windowsDir.FullName;
- string windowsRoot = System.IO.Directory.GetDirectoryRoot(systemDir);
+ var systemDir = Path.GetFullPath(Environment.SystemDirectory);
+ var windowsDir = Directory.GetParent(systemDir);
+ var windowsDirPath = windowsDir.FullName;
+ var windowsRoot = Directory.GetDirectoryRoot(systemDir);
// we need to get the exact casing from the file system:
var normalizedWindowsPath = Directory.GetDirectories(windowsRoot, windowsDir.Name).Single();
var windowsFolderName = Path.GetFileName(normalizedWindowsPath);
var code = "#r \"" + windowsRoot + "$$";
- await VerifyItemsExistInScriptAndInteractiveAsync(
- code,
- windowsFolderName);
+ await VerifyItemExistsAsync(code, windowsFolderName, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Completion/LoadDirectiveCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/LoadDirectiveCompletionProviderTests.cs
deleted file mode 100644
index 44a4914fc15af..0000000000000
--- a/src/EditorFeatures/CSharpTest/Completion/LoadDirectiveCompletionProviderTests.cs
+++ /dev/null
@@ -1,86 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Completion;
-using Microsoft.CodeAnalysis.Editor.CSharp.Completion.FileSystem;
-using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
-using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
-using Roslyn.Test.Utilities;
-using Xunit;
-
-namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion
-{
- public class LoadDirectiveCompletionProviderTests : AbstractCSharpCompletionProviderTests
- {
- public LoadDirectiveCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
- {
- }
-
- internal override CompletionProvider CreateCompletionProvider()
- {
- return new LoadDirectiveCompletionProvider();
- }
-
- protected override bool CompareItems(string actualItem, string expectedItem)
- {
- return actualItem.Equals(expectedItem, StringComparison.OrdinalIgnoreCase);
- }
-
- protected override Task VerifyWorkerAsync(
- string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull,
- SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence,
- int? glyph, int? matchPriority, bool? hasSuggestionItem)
- {
- return BaseVerifyWorkerAsync(
- code, position, expectedItemOrNull, expectedDescriptionOrNull,
- sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence,
- glyph, matchPriority, hasSuggestionItem);
- }
-
- private async Task VerifyItemExistsInScriptAsync(string markup, string expected)
- {
- await VerifyItemExistsAsync(markup, expected, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: false);
- }
-
- private async Task VerifyItemIsAbsentInInteractiveAsync(string markup, string expected)
- {
- await VerifyItemIsAbsentAsync(markup, expected, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: false);
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public async Task NetworkPath()
- {
- await VerifyItemExistsInScriptAsync(
- @"#load ""$$",
- @"\\");
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public async Task NetworkPathAfterInitialBackslash()
- {
- await VerifyItemExistsInScriptAsync(
- @"#load ""\$$",
- @"\\");
- }
-
- [Fact, Trait(Traits.Feature, Traits.Features.Completion)]
- public async Task UpOneDirectoryNotShownAtRoot()
- {
- // after so many ".." we should be at the root drive an should no longer suggest the parent. we can determine
- // our current directory depth by counting the number of backslashes present in the current working directory
- // and after that many references to "..", we are at the root.
- int depth = Directory.GetCurrentDirectory().Count(c => c == Path.DirectorySeparatorChar);
- var pathToRoot = string.Concat(Enumerable.Repeat(@"..\", depth));
-
- await VerifyItemExistsInScriptAsync(
- @"#load ""$$",
- "..");
- await VerifyItemIsAbsentInInteractiveAsync(
- @"#load """ + pathToRoot + "$$",
- "..");
- }
- }
-}
diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/GenerateMethod/GenerateMethodTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/GenerateMethod/GenerateMethodTests.cs
index 3532565a413de..5866588f098b2 100644
--- a/src/EditorFeatures/CSharpTest/Diagnostics/GenerateMethod/GenerateMethodTests.cs
+++ b/src/EditorFeatures/CSharpTest/Diagnostics/GenerateMethod/GenerateMethodTests.cs
@@ -7262,7 +7262,7 @@ private object Method()
parseOptions: TestOptions.Regular);
}
- [Fact/*(Skip = "https://github.com/dotnet/roslyn/issues/15508")*/, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
[WorkItem(14136, "https://github.com/dotnet/roslyn/issues/14136")]
public async Task TestDeconstruction4()
{
@@ -7379,5 +7379,67 @@ private ref int Bar()
}
}");
}
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
+ [WorkItem(18969, "https://github.com/dotnet/roslyn/issues/18969")]
+ public async Task TestTupleElement1()
+ {
+ await TestAsync(
+@"using System;
+
+class C
+{
+ public void M1()
+ {
+ (int x, string y) t = ([|Method|](), null);
+ }
+}",
+@"using System;
+
+class C
+{
+ public void M1()
+ {
+ (int x, string y) t = (Method(), null);
+ }
+
+ private int Method()
+ {
+ throw new NotImplementedException();
+ }
+}",
+parseOptions: TestOptions.Regular);
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
+ [WorkItem(18969, "https://github.com/dotnet/roslyn/issues/18969")]
+ public async Task TestTupleElement2()
+ {
+ await TestAsync(
+@"using System;
+
+class C
+{
+ public void M1()
+ {
+ (int x, string y) t = (0, [|Method|]());
+ }
+}",
+@"using System;
+
+class C
+{
+ public void M1()
+ {
+ (int x, string y) t = (0, Method());
+ }
+
+ private string Method()
+ {
+ throw new NotImplementedException();
+ }
+}",
+parseOptions: TestOptions.Regular);
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
index bd45b420d589c..e3e978a102ef5 100644
--- a/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
+++ b/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodAsynchronous/MakeMethodAsynchronousTests.cs
@@ -599,5 +599,180 @@ async ValueTask TestAsync()
}";
await TestInRegularAndScriptAsync(initial, expected);
}
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
+ [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")]
+ public async Task AddAsyncInLocalFunction()
+ {
+ await TestInRegularAndScriptAsync(
+@"using System.Threading.Tasks;
+
+class C
+{
+ public void M1()
+ {
+ void M2()
+ {
+ [|await M3Async();|]
+ }
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+}",
+@"using System.Threading.Tasks;
+
+class C
+{
+ public void M1()
+ {
+ async Task M2Async()
+ {
+ await M3Async();
+ }
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+}");
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
+ [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")]
+ public async Task AddAsyncInLocalFunctionKeepVoidReturn()
+ {
+ await TestInRegularAndScriptAsync(
+@"using System.Threading.Tasks;
+
+class C
+{
+ public void M1()
+ {
+ void M2()
+ {
+ [|await M3Async();|]
+ }
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+}",
+@"using System.Threading.Tasks;
+
+class C
+{
+ public void M1()
+ {
+ async void M2Async()
+ {
+ await M3Async();
+ }
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+}",
+index: 1);
+ }
+
+ [Theory]
+ [InlineData(0, "Task")]
+ [InlineData(1, "void", Skip = "https://github.com/dotnet/roslyn/issues/18396")]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
+ [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")]
+ public async Task AddAsyncInLocalFunctionKeepsTrivia(int codeFixIndex, string expectedReturn)
+ {
+ await TestInRegularAndScriptAsync(
+@"using System.Threading.Tasks;
+
+class C
+{
+ public void M1()
+ {
+ // Leading trivia
+ /*1*/ void /*2*/ M2/*3*/() /*4*/
+ {
+ [|await M3Async();|]
+ }
+ }
+
+ async Task M3Async()
+ {
+ return 1;
+ }
+}",
+$@"using System.Threading.Tasks;
+
+class C
+{{
+ public void M1()
+ {{
+ // Leading trivia
+ /*1*/ async {expectedReturn} /*2*/ M2Async/*3*/() /*4*/
+ {{
+ await M3Async();
+ }}
+ }}
+
+ async Task M3Async()
+ {{
+ return 1;
+ }}
+}}",
+ index: codeFixIndex,
+ ignoreTrivia: false);
+ }
+
+ [Theory]
+ [InlineData("", 0, "Task")]
+ [InlineData("", 1, "void", Skip = "https://github.com/dotnet/roslyn/issues/18396")]
+ [InlineData("public", 0, "Task")]
+ [InlineData("public", 1, "void")]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
+ [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")]
+ public async Task AddAsyncKeepsTrivia(string modifiers, int codeFixIndex, string expectedReturn)
+ {
+ await TestInRegularAndScriptAsync(
+$@"using System.Threading.Tasks;
+
+class C
+{{
+ // Leading trivia
+ {modifiers}/*1*/ void /*2*/ M2/*3*/() /*4*/
+ {{
+ [|await M3Async();|]
+ }}
+
+ async Task M3Async()
+ {{
+ return 1;
+ }}
+}}",
+$@"using System.Threading.Tasks;
+
+class C
+{{
+ // Leading trivia
+ {modifiers}/*1*/ async {expectedReturn} /*2*/ M2Async/*3*/() /*4*/
+ {{
+ await M3Async();
+ }}
+
+ async Task M3Async()
+ {{
+ return 1;
+ }}
+}}",
+ index: codeFixIndex,
+ ignoreTrivia: false);
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodSynchronous/MakeMethodSynchronousTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
index 8942b2569cda3..a60f6c8bee688 100644
--- a/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
+++ b/src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
@@ -548,5 +548,112 @@ async void BarAsync()
}
}", ignoreTrivia: false);
}
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
+ [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")]
+ public async Task RemoveAsyncInLocalFunction()
+ {
+ await TestInRegularAndScriptAsync(
+@"using System.Threading.Tasks;
+
+class C
+{
+ public void M1()
+ {
+ async Task [|M2Async|]()
+ {
+ }
+ }
+}",
+@"using System.Threading.Tasks;
+
+class C
+{
+ public void M1()
+ {
+ void M2()
+ {
+ }
+ }
+}");
+ }
+
+ [Theory]
+ [InlineData("Task", "C")]
+ [InlineData("Task", "int")]
+ [InlineData("Task", "void")]
+ [InlineData("void", "void")]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
+ [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")]
+ public async Task RemoveAsyncInLocalFunctionKeepsTrivia(string asyncReturn, string expectedReturn)
+ {
+ await TestInRegularAndScriptAsync(
+$@"using System;
+using System.Threading.Tasks;
+
+class C
+{{
+ public void M1()
+ {{
+ // Leading trivia
+ /*1*/ async {asyncReturn} /*2*/ [|M2Async|]/*3*/() /*4*/
+ {{
+ throw new NotImplementedException();
+ }}
+ }}
+}}",
+$@"using System;
+using System.Threading.Tasks;
+
+class C
+{{
+ public void M1()
+ {{
+ // Leading trivia
+ /*1*/ {expectedReturn} /*2*/ M2/*3*/() /*4*/
+ {{
+ throw new NotImplementedException();
+ }}
+ }}
+}}");
+ }
+
+ [Theory]
+ [InlineData("", "Task", "C")]
+ [InlineData("", "Task", "int")]
+ [InlineData("", "Task", "void")]
+ [InlineData("", "void", "void")]
+ [InlineData("public", "Task", "C")]
+ [InlineData("public", "Task", "int")]
+ [InlineData("public", "Task", "void")]
+ [InlineData("public", "void", "void")]
+ [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)]
+ [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")]
+ public async Task RemoveAsyncKeepsTrivia(string modifiers, string asyncReturn, string expectedReturn)
+ {
+ await TestInRegularAndScriptAsync(
+$@"using System;
+using System.Threading.Tasks;
+
+class C
+{{
+ // Leading trivia
+ {modifiers}/*1*/ async {asyncReturn} /*2*/ [|M2Async|]/*3*/() /*4*/
+ {{
+ throw new NotImplementedException();
+ }}
+}}",
+$@"using System;
+using System.Threading.Tasks;
+
+class C
+{{
+ // Leading trivia
+ {modifiers}/*1*/ {expectedReturn} /*2*/ M2/*3*/() /*4*/
+ {{
+ throw new NotImplementedException();
+ }}
+}}");
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests.cs
index bd8d373b97b57..614005d31d0d4 100644
--- a/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests.cs
+++ b/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests.cs
@@ -1,10 +1,12 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.NamingStyles;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.NamingStyles;
using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
@@ -306,5 +308,40 @@ class D : C
internal override void [|m|]() { }
}", new TestParameters(options: MethodNamesArePascalCase));
}
+
+ [Fact, Trait(Traits.Feature, Traits.Features.NamingStyle)]
+ [WorkItem(19106, "https://github.com/dotnet/roslyn/issues/19106")]
+ public async Task TestMissingOnSymbolsWithNoName()
+ {
+ await TestMissingInRegularAndScriptAsync(
+@"
+namespace Microsoft.CodeAnalysis.Host
+{
+ internal interface
+[|}|]
+", new TestParameters(options: InterfaceNamesStartWithI));
+ }
+
+ [WorkItem(16562, "https://github.com/dotnet/roslyn/issues/16562")]
+ public async Task TestRefactorNotify()
+ {
+ var markup = @"public class [|c|] { }";
+ var testParameters = new TestParameters(options: ClassNamesArePascalCase);
+
+ using (var workspace = CreateWorkspaceFromOptions(markup, testParameters))
+ {
+ var actions = await GetCodeActionsAsync(workspace, testParameters);
+
+ var previewOperations = await actions[0].GetPreviewOperationsAsync(CancellationToken.None);
+ Assert.Empty(previewOperations.OfType());
+
+ var commitOperations = await actions[0].GetOperationsAsync(CancellationToken.None);
+ Assert.Equal(2, commitOperations.Length);
+
+ var symbolRenamedOperation = (TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.Operation)commitOperations[1];
+ Assert.Equal("c", symbolRenamedOperation._symbol.Name);
+ Assert.Equal("C", symbolRenamedOperation._newName);
+ }
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests_OptionSets.cs b/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests_OptionSets.cs
index c28a080ee3c88..8ccb9885166c1 100644
--- a/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests_OptionSets.cs
+++ b/src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/NamingStylesTests_OptionSets.cs
@@ -21,9 +21,12 @@ public partial class NamingStylesTests : AbstractCSharpDiagnosticProviderBasedUs
private IDictionary ParameterNamesAreCamelCase =>
Options(new OptionKey(SimplificationOptions.NamingPreferences, LanguageNames.CSharp), ParameterNamesAreCamelCaseOption());
- private IDictionary PropertyNamesArePascalCase =>
+ private IDictionary PropertyNamesArePascalCase =>
Options(new OptionKey(SimplificationOptions.NamingPreferences, LanguageNames.CSharp), PropertyNamesArePascalCaseOption());
+ private IDictionary InterfaceNamesStartWithI =>
+ Options(new OptionKey(SimplificationOptions.NamingPreferences, LanguageNames.CSharp), InterfacesNamesStartWithIOption());
+
private IDictionary Options(OptionKey option, object value)
{
var options = new Dictionary
@@ -117,14 +120,14 @@ private NamingStylePreferences ParameterNamesAreCamelCaseOption()
NamingStyleID = namingStyle.ID,
EnforcementLevel = DiagnosticSeverity.Error
};
-
- var info = new NamingStylePreferences(
+
+ var info = new NamingStylePreferences(
ImmutableArray.Create(symbolSpecification),
ImmutableArray.Create(namingStyle),
ImmutableArray.Create(namingRule));
return info;
- }
+ }
private NamingStylePreferences PropertyNamesArePascalCaseOption()
{
@@ -157,5 +160,37 @@ private NamingStylePreferences PropertyNamesArePascalCaseOption()
return info;
}
+
+ private NamingStylePreferences InterfacesNamesStartWithIOption()
+ {
+ var symbolSpecification = new SymbolSpecification(
+ null,
+ "Name",
+ ImmutableArray.Create(new SymbolSpecification.SymbolKindOrTypeKind(TypeKind.Interface)),
+ ImmutableArray.Empty,
+ ImmutableArray.Empty);
+
+ var namingStyle = new NamingStyle(
+ Guid.NewGuid(),
+ capitalizationScheme: Capitalization.PascalCase,
+ name: "Name",
+ prefix: "I",
+ suffix: "",
+ wordSeparator: "");
+
+ var namingRule = new SerializableNamingRule()
+ {
+ SymbolSpecificationID = symbolSpecification.ID,
+ NamingStyleID = namingStyle.ID,
+ EnforcementLevel = DiagnosticSeverity.Error
+ };
+
+ var info = new NamingStylePreferences(
+ ImmutableArray.Create(symbolSpecification),
+ ImmutableArray.Create(namingStyle),
+ ImmutableArray.Create(namingRule));
+
+ return info;
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/RemoveUnusedVariable/RemoveUnusedVariableTest.cs b/src/EditorFeatures/CSharpTest/Diagnostics/RemoveUnusedVariable/RemoveUnusedVariableTest.cs
index 3af44cb53b939..6afc81cf3de69 100644
--- a/src/EditorFeatures/CSharpTest/Diagnostics/RemoveUnusedVariable/RemoveUnusedVariableTest.cs
+++ b/src/EditorFeatures/CSharpTest/Diagnostics/RemoveUnusedVariable/RemoveUnusedVariableTest.cs
@@ -13,9 +13,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveUnuse
public partial class RemoveUnusedVariableTest : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- {
- return(null, new RemoveUnusedVariableCodeFixProvider());
- }
+ => (null, new CSharpRemoveUnusedVariableCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)]
public async Task RemoveUnusedVariable()
diff --git a/src/EditorFeatures/CSharpTest/Diagnostics/UpgradeProject/UpgradeProjectTests.cs b/src/EditorFeatures/CSharpTest/Diagnostics/UpgradeProject/UpgradeProjectTests.cs
index b4be75cb1764c..9848a492cf754 100644
--- a/src/EditorFeatures/CSharpTest/Diagnostics/UpgradeProject/UpgradeProjectTests.cs
+++ b/src/EditorFeatures/CSharpTest/Diagnostics/UpgradeProject/UpgradeProjectTests.cs
@@ -179,6 +179,25 @@ class Program
index: 1);
}
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)]
+ public async Task UpgradeProjectFromCSharp7ToCSharp7_1_B()
+ {
+ await TestLanguageVersionUpgradedAsync(
+@"public class Base { }
+public class Derived : Base { }
+public class Program
+{
+ public static void M(T x) where T: Base
+ {
+ System.Console.Write(x is [|Derived|] b0);
+ }
+}
+",
+ LanguageVersion.CSharp7_1,
+ new CSharpParseOptions(LanguageVersion.CSharp7),
+ index: 1);
+ }
+
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)]
public async Task UpgradeAllProjectsToDefault()
{
diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.cs
index 52366c79d5517..a67a29f425690 100644
--- a/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.cs
+++ b/src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.cs
@@ -3184,6 +3184,41 @@ static void Main(string[] args)
edits.VerifyRudeDiagnostics(active);
}
+ [Fact]
+ public void ForEachVariableBody_Update_ExpressionActive()
+ {
+ string src1 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(0);
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(1);
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active);
+ }
+
[Fact]
public void ForEachBody_Update_InKeywordActive()
{
@@ -3219,6 +3254,41 @@ static void Main(string[] args)
edits.VerifyRudeDiagnostics(active);
}
+ [Fact]
+ public void ForEachVariableBody_Update_InKeywordActive()
+ {
+ string src1 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(0);
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(1);
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active);
+ }
+
[Fact]
public void ForEachBody_Update_VariableActive()
{
@@ -3254,6 +3324,41 @@ static void Main(string[] args)
edits.VerifyRudeDiagnostics(active);
}
+ [Fact]
+ public void ForEachVariableBody_Update_VariableActive()
+ {
+ string src1 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(0);
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(1);
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active);
+ }
+
[Fact]
public void ForEachBody_Update_ForeachKeywordActive()
{
@@ -3289,6 +3394,41 @@ static void Main(string[] args)
edits.VerifyRudeDiagnostics(active);
}
+ [Fact]
+ public void ForEachVariableBody_Update_ForeachKeywordActive()
+ {
+ string src1 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(0);
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ private static (string, int) F() { return null; }
+
+ static void Main(string[] args)
+ {
+ foreach ((string s, int i) in F())
+ {
+ System.Console.Write(1);
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active);
+ }
+
[Fact]
public void ForEachVariable_Update()
{
@@ -3328,7 +3468,44 @@ static void Main(string[] args)
}
[Fact]
- public void ForEach_Reorder_Leaf1()
+ public void ForEachDeconstructionVariable_Update()
+ {
+ string src1 = @"
+class Test
+{
+ private static (int, (bool, double))[] F() { return new[] { (1, (true, 2.0)) }; }
+
+ static void Main(string[] args)
+ {
+ foreach ((int i, (bool b, double d)) in F())
+ {
+ System.Console.Write(0);
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ private static (int, (bool, double))[] F() { return new[] { (1, (true, 2.0)) }; }
+
+ static void Main(string[] args)
+ {
+ foreach ((int i, (var b, double d)) in F())
+ {
+ System.Console.Write(1);
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active,
+ Diagnostic(RudeEditKind.ActiveStatementUpdate, "(int i, (var b, double d))"),
+ Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( (int i, (var b, double d)) in F())", CSharpFeaturesResources.foreach_statement));
+ }
+
+ [Fact]
+ public void ForEach_Reorder_Leaf()
{
string src1 = @"
class Test
@@ -3377,19 +3554,19 @@ static void Main(string[] args)
}
[Fact]
- public void ForEach_Update_Leaf1()
+ public void ForEachVariable_Reorder_Leaf()
{
string src1 = @"
class Test
{
- public static int[] e1 = new int[1];
- public static int[] e2 = new int[1];
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
static void Main(string[] args)
{
- foreach (var a in e1)
+ foreach ((var a1, var a2) in e1)
{
- foreach (var b in e1)
+ foreach ((int b1, bool b2) in e1)
{
foreach (var c in e1)
{
@@ -3402,16 +3579,16 @@ static void Main(string[] args)
string src2 = @"
class Test
{
- public static int[] e1 = new int[1];
- public static int[] e2 = new int[1];
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
static void Main(string[] args)
{
- foreach (var b in e1)
+ foreach ((int b1, bool b2) in e1)
{
foreach (var c in e1)
{
- foreach (var a in e1)
+ foreach ((var a1, var a2) in e1)
{
System.Console.Write();
}
@@ -3426,7 +3603,7 @@ static void Main(string[] args)
}
[Fact]
- public void ForEach_Update_Leaf2()
+ public void ForEach_Update_Leaf()
{
string src1 = @"
class Test
@@ -3468,6 +3645,49 @@ static void Main(string[] args)
Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement));
}
+ [Fact]
+ public void ForEachVariable_Update_Leaf()
+ {
+ string src1 = @"
+class Test
+{
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
+
+ static void Main(string[] args)
+ {
+ System.Console.Write();
+ }
+}";
+ string src2 = @"
+class Test
+{
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
+
+ static void Main(string[] args)
+ {
+ foreach ((int b1, bool b2) in e1)
+ {
+ foreach (var c in e1)
+ {
+ foreach ((var a1, var a2) in e1)
+ {
+ System.Console.Write();
+ }
+ }
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active,
+ Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement),
+ Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((int b1, bool b2) in e1)", CSharpFeaturesResources.foreach_statement),
+ Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((var a1, var a2) in e1)", CSharpFeaturesResources.foreach_statement));
+ }
+
[Fact]
public void ForEach_Delete_Leaf1()
{
@@ -3514,6 +3734,52 @@ static void Main(string[] args)
edits.VerifyRudeDiagnostics(active);
}
+ [Fact]
+ public void ForEachVariable_Delete_Leaf1()
+ {
+ string src1 = @"
+class Test
+{
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
+
+ static void Main(string[] args)
+ {
+ foreach ((var a1, var a2) in e1)
+ {
+ foreach ((int b1, bool b2) in e1)
+ {
+ foreach (var c in e1)
+ {
+ System.Console.Write();
+ }
+ }
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
+
+ static void Main(string[] args)
+ {
+ foreach ((var a1, var a2) in e1)
+ {
+ foreach ((int b1, bool b2) in e1)
+ {
+ System.Console.Write();
+ }
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active);
+ }
+
[Fact]
public void ForEach_Delete_Leaf2()
{
@@ -3560,6 +3826,52 @@ static void Main(string[] args)
edits.VerifyRudeDiagnostics(active);
}
+ [Fact]
+ public void ForEachVariable_Delete_Leaf2()
+ {
+ string src1 = @"
+class Test
+{
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
+
+ static void Main(string[] args)
+ {
+ foreach ((var a1, var a2) in e1)
+ {
+ foreach ((int b1, bool b2) in e1)
+ {
+ foreach (var c in e1)
+ {
+ System.Console.Write();
+ }
+ }
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ public static (int, bool)[] e1 = new (int, bool)[1];
+ public static (int, bool)[] e2 = new (int, bool)[1];
+
+ static void Main(string[] args)
+ {
+ foreach ((int b1, bool b2) in e1)
+ {
+ foreach (var c in e1)
+ {
+ System.Console.Write();
+ }
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active);
+ }
+
[Fact]
public void ForEach_Delete_Leaf3()
{
@@ -3606,6 +3918,52 @@ static void Main(string[] args)
edits.VerifyRudeDiagnostics(active);
}
+ [Fact]
+ public void ForEachVariable_Delete_Leaf3()
+ {
+ string src1 = @"
+class Test
+{
+ public static int[] e1 = new int[1];
+ public static int[] e2 = new int[1];
+
+ static void Main(string[] args)
+ {
+ foreach ((var a1, var a2) in e1)
+ {
+ foreach ((int b1, bool b2) in e1)
+ {
+ foreach (var c in e1)
+ {
+ System.Console.Write();
+ }
+ }
+ }
+ }
+}";
+ string src2 = @"
+class Test
+{
+ public static int[] e1 = new int[1];
+ public static int[] e2 = new int[1];
+
+ static void Main(string[] args)
+ {
+ foreach ((var a1, var a2) in e1)
+ {
+ foreach (var c in e1)
+ {
+ System.Console.Write();
+ }
+ }
+ }
+}";
+ var edits = GetTopEdits(src1, src2);
+ var active = GetActiveStatements(src1, src2);
+
+ edits.VerifyRudeDiagnostics(active);
+ }
+
[Fact]
public void ForEach_Lambda1()
{
@@ -8182,8 +8540,7 @@ static void F(object o)
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
- edits.VerifyRudeDiagnostics(active,
- Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "var (x, y)", CSharpFeaturesResources.deconstruction));
+ edits.VerifyRudeDiagnostics(active);
}
[Fact]
diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs
index 15845eed701aa..288f7948c828d 100644
--- a/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs
+++ b/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs
@@ -496,8 +496,8 @@ public static void Main()
}
}
- [Fact]
- public async Task AnalyzeDocumentAsync_SemanticError_Change()
+ [Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")]
+ public async Task AnalyzeDocumentAsync_SemanticErrorInMethodBody_Change()
{
string source1 = @"
class C
@@ -521,6 +521,46 @@ public static void Main()
";
var analyzer = new CSharpEditAndContinueAnalyzer();
+ using (var workspace = TestWorkspace.CreateCSharp(source1))
+ {
+ var documentId = workspace.CurrentSolution.Projects.First().Documents.First().Id;
+ var oldSolution = workspace.CurrentSolution;
+ var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2));
+
+ var baseActiveStatements = ImmutableArray.Create();
+ var result = await analyzer.AnalyzeDocumentAsync(oldSolution, baseActiveStatements, newSolution.GetDocument(documentId), default(CancellationToken));
+
+ Assert.True(result.HasChanges);
+
+ // no declaration errors (error in method body is only reported when emitting):
+ Assert.False(result.HasChangesAndErrors);
+ Assert.False(result.HasChangesAndCompilationErrors);
+ }
+ }
+
+ [Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")]
+ public async Task AnalyzeDocumentAsync_SemanticErrorInDeclaration_Change()
+ {
+ string source1 = @"
+class C
+{
+ public static void Main(Bar x)
+ {
+ System.Console.WriteLine(1);
+ }
+}
+";
+ string source2 = @"
+class C
+{
+ public static void Main(Bar x)
+ {
+ System.Console.WriteLine(2);
+ }
+}
+";
+ var analyzer = new CSharpEditAndContinueAnalyzer();
+
using (var workspace = TestWorkspace.CreateCSharp(source1))
{
var documentId = workspace.CurrentSolution.Projects.First().Documents.First().Id;
diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/Extensions.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/Extensions.cs
index 11943c1ccf4e9..877df16e72d2e 100644
--- a/src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/Extensions.cs
+++ b/src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/Extensions.cs
@@ -5,6 +5,7 @@
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.EditAndContinue.UnitTests;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditAndContinue;
+using Microsoft.CodeAnalysis.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
@@ -58,16 +59,34 @@ internal static void VerifySemanticDiagnostics(
this EditScript editScript,
params RudeEditDiagnosticDescription[] expectedDiagnostics)
{
- VerifySemantics(editScript, ActiveStatementsDescription.Empty, null, expectedDiagnostics);
+ VerifySemanticDiagnostics(editScript, null, expectedDiagnostics);
+ }
+
+ internal static void VerifySemanticDiagnostics(
+ this EditScript editScript,
+ DiagnosticDescription expectedDeclarationError,
+ params RudeEditDiagnosticDescription[] expectedDiagnostics)
+ {
+ VerifySemantics(editScript, ActiveStatementsDescription.Empty, null, expectedDeclarationError, expectedDiagnostics);
+ }
+
+ internal static void VerifySemantics(
+ this EditScript editScript,
+ ActiveStatementsDescription activeStatements,
+ SemanticEditDescription[] expectedSemanticEdits,
+ params RudeEditDiagnosticDescription[] expectedDiagnostics)
+ {
+ VerifySemantics(editScript, activeStatements, expectedSemanticEdits, null, expectedDiagnostics);
}
internal static void VerifySemantics(
this EditScript editScript,
ActiveStatementsDescription activeStatements,
SemanticEditDescription[] expectedSemanticEdits,
+ DiagnosticDescription expectedDeclarationError,
params RudeEditDiagnosticDescription[] expectedDiagnostics)
{
- VerifySemantics(editScript, activeStatements, null, null, expectedSemanticEdits, expectedDiagnostics);
+ VerifySemantics(editScript, activeStatements, null, null, expectedSemanticEdits, expectedDeclarationError, expectedDiagnostics);
}
internal static void VerifySemantics(
@@ -76,6 +95,7 @@ internal static void VerifySemantics(
IEnumerable additionalOldSources,
IEnumerable additionalNewSources,
SemanticEditDescription[] expectedSemanticEdits,
+ DiagnosticDescription expectedDeclarationError,
params RudeEditDiagnosticDescription[] expectedDiagnostics)
{
CSharpEditAndContinueTestHelpers.Instance.VerifySemantics(
@@ -84,6 +104,7 @@ internal static void VerifySemantics(
additionalOldSources,
additionalNewSources,
expectedSemanticEdits,
+ expectedDeclarationError,
expectedDiagnostics);
}
}
diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditStatementTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditStatementTests.cs
index 50a769bea0d33..152b61439997e 100644
--- a/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditStatementTests.cs
+++ b/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditStatementTests.cs
@@ -4416,7 +4416,7 @@ void F()
}
// Add corresponding test to VB
- [WpfFact(Skip = "TODO")]
+ [Fact(Skip = "TODO")]
public void Lambdas_Update_Signature_CustomModifiers1()
{
var delegateSource = @"
@@ -4502,6 +4502,43 @@ void F()
edits.VerifySemanticDiagnostics();
}
+ [Fact]
+ public void Lambdas_Signature_SemanticErrors()
+ {
+ var src1 = @"
+using System;
+
+class C
+{
+ void G(Func f) {}
+
+ void F()
+ {
+ G(a => 1);
+ }
+}
+";
+ var src2 = @"
+using System;
+
+class C
+{
+ void G(Func f) {}
+
+ void F()
+ {
+ G(a => 2);
+ }
+}
+";
+ var edits = GetTopEdits(src1, src2);
+
+ edits.VerifySemanticDiagnostics(
+ // (6,17): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?)
+ // void G(Func f) {}
+ Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(6, 17));
+ }
+
[Fact]
public void Lambdas_Update_DelegateType1()
{
@@ -7530,6 +7567,7 @@ static IEnumerable F()
null,
null,
null,
+ null,
new[]
{
Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static IEnumerable F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute")
@@ -8111,12 +8149,13 @@ static async Task F()
var edits = GetTopEdits(src1, src2);
CSharpEditAndContinueTestHelpers.InstanceMinAsync.VerifySemantics(
- edits,
- ActiveStatementsDescription.Empty,
- null,
- null,
- null,
- new[]
+ editScript: edits,
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalNewSources: null,
+ additionalOldSources: null,
+ expectedSemanticEdits: null,
+ expectedDeclarationError: null,
+ expectedDiagnostics: new[]
{
Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static async Task F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute")
});
@@ -8159,6 +8198,43 @@ static async Task F()
null);
}
+ [Fact]
+ public void SemanticError_AwaitInPropertyAccessor()
+ {
+ string src1 = @"
+using System.Threading.Tasks;
+
+class C
+{
+ public Task P
+ {
+ get
+ {
+ await Task.Delay(1);
+ return 1;
+ }
+ }
+}
+";
+ string src2 = @"
+using System.Threading.Tasks;
+
+class C
+{
+ public Task P
+ {
+ get
+ {
+ await Task.Delay(2);
+ return 1;
+ }
+ }
+}
+";
+ var edits = GetTopEdits(src1, src2);
+ edits.VerifySemanticDiagnostics();
+ }
+
#endregion
#region Out Var
diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditTopLevelTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditTopLevelTests.cs
index 926c182fa6e7b..d2aa6170d44f5 100644
--- a/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditTopLevelTests.cs
+++ b/src/EditorFeatures/CSharpTest/EditAndContinue/RudeEditTopLevelTests.cs
@@ -3853,13 +3853,14 @@ public void StaticCtor_Partial_Delete()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- new[]
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").StaticConstructors.Single())
- });
+ },
+ expectedDeclarationError: null);
}
[Fact]
@@ -3874,13 +3875,14 @@ public void InstanceCtor_Partial_DeletePrivate()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- new[]
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").InstanceConstructors.Single())
- });
+ },
+ expectedDeclarationError: null);
}
[Fact]
@@ -3895,13 +3897,14 @@ public void InstanceCtor_Partial_DeletePublic()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- new[]
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").InstanceConstructors.Single())
- });
+ },
+ expectedDeclarationError: null);
}
[Fact]
@@ -3916,11 +3919,12 @@ public void InstanceCtor_Partial_DeletePrivateToPublic()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- null,
- Diagnostic(RudeEditKind.Delete, "partial class C", FeaturesResources.constructor));
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: null,
+ expectedDiagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", FeaturesResources.constructor) },
+ expectedDeclarationError: null);
}
[Fact]
@@ -3935,13 +3939,14 @@ public void StaticCtor_Partial_Insert()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- new[]
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").StaticConstructors.Single(), preserveLocalVariables: true)
- });
+ },
+ expectedDeclarationError: null);
}
[Fact]
@@ -3956,13 +3961,14 @@ public void InstanceCtor_Partial_InsertPublic()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- new[]
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").InstanceConstructors.Single(), preserveLocalVariables: true)
- });
+ },
+ expectedDeclarationError: null);
}
[Fact]
@@ -3977,13 +3983,14 @@ public void InstanceCtor_Partial_InsertPrivate()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- new[]
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").InstanceConstructors.Single(), preserveLocalVariables: true)
- });
+ },
+ expectedDeclarationError: null);
}
[Fact]
@@ -3998,13 +4005,14 @@ public void InstanceCtor_Partial_InsertInternal()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- new[]
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: new[]
{
SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C").InstanceConstructors.Single(), preserveLocalVariables: true)
- });
+ },
+ expectedDeclarationError: null);
}
[Fact]
@@ -4019,11 +4027,12 @@ public void InstanceCtor_Partial_InsertPrivateToPublic()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- null,
- Diagnostic(RudeEditKind.ChangingConstructorVisibility, "public C()"));
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits: null,
+ expectedDiagnostics: new[] { Diagnostic(RudeEditKind.ChangingConstructorVisibility, "public C()") },
+ expectedDeclarationError: null);
}
[Fact]
@@ -4038,11 +4047,12 @@ public void InstanceCtor_Partial_InsertPrivateToInternal()
var edits = GetTopEdits(srcA1, srcA2);
edits.VerifySemantics(
- ActiveStatementsDescription.Empty,
- new[] { srcB1 },
- new[] { srcB2 },
- null,
- Diagnostic(RudeEditKind.ChangingConstructorVisibility, "internal C()"));
+ activeStatements: ActiveStatementsDescription.Empty,
+ additionalOldSources: new[] { srcB1 },
+ additionalNewSources: new[] { srcB2 },
+ expectedSemanticEdits:null,
+ expectedDiagnostics: new[] { Diagnostic(RudeEditKind.ChangingConstructorVisibility, "internal C()") },
+ expectedDeclarationError: null);
}
[Fact]
@@ -4313,6 +4323,76 @@ public void Insert_ExternConstruct()
Diagnostic(RudeEditKind.InsertExtern, "public extern C()", FeaturesResources.constructor));
}
+ [Fact(Skip = "https://github.com/dotnet/roslyn/pull/18940")]
+ public void ParameterlessConstructor_SemanticError_Delete1()
+ {
+ string src1 = @"
+class C
+{
+ D() {}
+}
+";
+ string src2 = @"
+class C
+{
+}
+";
+ var edits = GetTopEdits(src1, src2);
+
+ edits.VerifyRudeDiagnostics();
+ }
+
+ [Fact(Skip = "https://github.com/dotnet/roslyn/pull/18940")]
+ public void ParameterlessConstructor_SemanticError_Delete_OutsideOfClass1()
+ {
+ string src1 = @"
+C() {}
+";
+ string src2 = @"
+";
+ var edits = GetTopEdits(src1, src2);
+ edits.VerifyRudeDiagnostics();
+ }
+
+ [Fact]
+ public void Constructor_SemanticError_Partial()
+ {
+ string src1 = @"
+partial class C
+{
+ partial void C(int x);
+}
+
+partial class C
+{
+ partial void C(int x)
+ {
+ System.Console.WriteLine(1);
+ }
+}
+";
+ string src2 = @"
+partial class C
+{
+ partial void C(int x);
+}
+
+partial class C
+{
+ partial void C(int x)
+ {
+ System.Console.WriteLine(2);
+ }
+}
+";
+ var edits = GetTopEdits(src1, src2);
+
+ edits.VerifySemanticDiagnostics(
+ // (4,18): error CS0542: 'C': member names cannot be the same as their enclosing type
+ // partial void C(int x);
+ Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 18));
+ }
+
#endregion
#region Fields and Properties with Initializers
@@ -5622,6 +5702,40 @@ class C
});
}
+ [Fact]
+ public void PropertyWithInitializer_SemanticError_Partial()
+ {
+ string src1 = @"
+partial class C
+{
+ partial int P => 1;
+}
+
+partial class C
+{
+ partial int P => 1;
+}
+";
+ string src2 = @"
+partial class C
+{
+ partial int P => 1;
+}
+
+partial class C
+{
+ partial int P => 1;
+
+ public C() { }
+}
+";
+ var edits = GetTopEdits(src1, src2);
+ edits.VerifySemanticDiagnostics(
+ // (4,17): error CS0753: Only methods, classes, structs, or interfaces may be partial
+ // partial int P => 1;
+ Diagnostic(ErrorCode.ERR_PartialMethodOnlyMethods, "P").WithLocation(4, 17));
+ }
+
#endregion
#region Fields
diff --git a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs
index a8e9136120885..379b276f6592c 100644
--- a/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs
+++ b/src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs
@@ -2349,6 +2349,56 @@ public int M2()
index: 1);
}
+ [WorkItem(18556, "https://github.com/dotnet/roslyn/issues/18556")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
+ public async Task TestImplementInterfaceThroughExplicitProperty()
+ {
+ await TestActionCountAsync(
+@"interface IA
+{
+ IB B { get; }
+}
+interface IB
+{
+ int M();
+}
+class AB : IA, [|IB|]
+{
+ IB IA.B => null;
+}",
+count: 3);
+ await TestWithAllCodeStyleOptionsOffAsync(
+@"interface IA
+{
+ IB B { get; }
+}
+interface IB
+{
+ int M();
+}
+class AB : IA, [|IB|]
+{
+ IB IA.B => null;
+}",
+@"interface IA
+{
+ IB B { get; }
+}
+interface IB
+{
+ int M();
+}
+class AB : IA, [|IB|]
+{
+ IB IA.B => null;
+
+ public int M()
+ {
+ return ((IA)this).B.M();
+ }
+}", index: 1);
+ }
+
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoImplementThroughIndexer()
diff --git a/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs b/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs
index 870815e7c612f..b700377c7cebf 100644
--- a/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs
+++ b/src/EditorFeatures/CSharpTest/InitializeParameter/AddParameterCheckTests.cs
@@ -704,5 +704,56 @@ public C(string s)
}
}", index: 2);
}
+
+ [WorkItem(19173, "https://github.com/dotnet/roslyn/issues/19173")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)]
+ public async Task TestMissingOnUnboundTypeWithExistingNullCheck()
+ {
+ await TestMissingAsync(
+@"
+class C
+{
+ public C(String [||]s)
+ {
+ if (s == null)
+ {
+ throw new System.Exception();
+ }
+ }
+}");
+ }
+
+ [WorkItem(19174, "https://github.com/dotnet/roslyn/issues/19174")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInitializeParameter)]
+ public async Task TestRespectPredefinedTypePreferences()
+ {
+ await TestInRegularAndScript1Async(
+@"
+using System;
+
+class Program
+{
+ static void Main([||]String bar)
+ {
+ }
+}",
+@"
+using System;
+
+class Program
+{
+ static void Main(String bar)
+ {
+ if (String.IsNullOrEmpty(bar))
+ {
+ throw new ArgumentException(""message"", nameof(bar));
+ }
+ }
+}", index: 1,
+ parameters: new TestParameters(
+ options: Option(
+ CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess,
+ CodeStyleOptions.FalseWithSuggestionEnforcement)));
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/Interactive/CodeActions/InteractiveIntroduceVariableTests.cs b/src/EditorFeatures/CSharpTest/Interactive/CodeActions/InteractiveIntroduceVariableTests.cs
index e9020f4603ee6..9e0057e717c0e 100644
--- a/src/EditorFeatures/CSharpTest/Interactive/CodeActions/InteractiveIntroduceVariableTests.cs
+++ b/src/EditorFeatures/CSharpTest/Interactive/CodeActions/InteractiveIntroduceVariableTests.cs
@@ -168,8 +168,8 @@ public static void Main()
{
for (int i = 0; i < 10; i++)
{
- int {|Rename:v|} = i + 1;
- Console.WriteLine(v);
+ int {|Rename:value|} = i + 1;
+ Console.WriteLine(value);
}
}
}
diff --git a/src/EditorFeatures/CSharpTest/UseCollectionInitializer/UseCollectionInitializerTests.cs b/src/EditorFeatures/CSharpTest/UseCollectionInitializer/UseCollectionInitializerTests.cs
index a6f091f146cdd..4b6e6b6be07aa 100644
--- a/src/EditorFeatures/CSharpTest/UseCollectionInitializer/UseCollectionInitializerTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseCollectionInitializer/UseCollectionInitializerTests.cs
@@ -981,5 +981,40 @@ public void M()
}
}");
}
+
+ [WorkItem(19253, "https://github.com/dotnet/roslyn/issues/19253")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseCollectionInitializer)]
+ public async Task TestKeepBlankLinesAfter()
+ {
+ await TestInRegularAndScript1Async(
+@"
+using System.Collections.Generic;
+
+class MyClass
+{
+ public void Main()
+ {
+ var list = [||]new List();
+ list.Add(1);
+
+ int horse = 1;
+ }
+}",
+@"
+using System.Collections.Generic;
+
+class MyClass
+{
+ public void Main()
+ {
+ var list = new List
+ {
+ 1
+ };
+
+ int horse = 1;
+ }
+}", ignoreTrivia: false);
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForAccessorsTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForAccessorsAnalyzerTests.cs
similarity index 81%
rename from src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForAccessorsTests.cs
rename to src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForAccessorsAnalyzerTests.cs
index 1e33d62be4ee3..e9b450dbbf328 100644
--- a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForAccessorsTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForAccessorsAnalyzerTests.cs
@@ -18,8 +18,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
public class UseExpressionBodyForAccessorsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (new UseExpressionBodyForAccessorsDiagnosticAnalyzer(),
- new UseExpressionBodyForAccessorsCodeFixProvider());
+ => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary UseExpressionBody =>
OptionsSet(
@@ -33,8 +32,11 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement),
SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement));
- private IDictionary UseBlockBody =>
- Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement);
+ private IDictionary UseBlockBodyIncludingPropertiesAndIndexers =>
+ OptionsSet(
+ SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement),
+ SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement),
+ SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSuggestionEnforcement));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestUseExpressionBody1()
@@ -60,9 +62,9 @@ int Foo
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
- public async Task TestMissingIfPropertyIsOn()
+ public async Task TestUpdatePropertyInsteadOfAccessor()
{
- await TestMissingInRegularAndScriptAsync(
+ await TestInRegularAndScript1Async(
@"class C
{
int Foo
@@ -72,7 +74,11 @@ int Foo
[|return|] Bar();
}
}
-}", new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers));
+}",
+@"class C
+{
+ int Foo => Bar();
+}", parameters: new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
@@ -99,9 +105,9 @@ int this[int i]
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
- public async Task TestMissingIfIndexerIsOn()
+ public async Task TestUpdateIndexerIfIndexerAndAccessorCanBeUpdated()
{
- await TestMissingInRegularAndScriptAsync(
+ await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
@@ -111,7 +117,11 @@ int this[int i]
[|return|] Bar();
}
}
-}", new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers));
+}",
+@"class C
+{
+ int this[int i] => Bar();
+}", parameters: new TestParameters(options: UseExpressionBodyIncludingPropertiesAndIndexers));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
@@ -140,31 +150,14 @@ int Foo
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestMissingWithOnlySetter()
{
- await TestActionCountAsync(
-@"class C
-{
- int Foo
- {
- set => [|Bar|]();
- }
-}", count: 1, parameters: new TestParameters(options: UseExpressionBody));
-
- // There is a hidden diagnostic that still offers to convert expression-body to block-body.
- await TestInRegularAndScriptAsync(
+ await TestMissingAsync(
@"class C
{
int Foo
{
set => [|Bar|]();
}
-}",
-@"class C
-{
- int Foo
- {
- set { Bar(); }
- }
-}", options: UseExpressionBody);
+}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
@@ -222,8 +215,8 @@ await TestInRegularAndScriptAsync(
int Foo
{
get [|=>|] Bar();
- }
- }",
+ }
+}",
@"class C
{
int Foo
@@ -233,7 +226,7 @@ int Foo
return Bar();
}
}
-}", options: UseBlockBody);
+}", options: UseBlockBodyIncludingPropertiesAndIndexers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
@@ -256,7 +249,7 @@ int Foo
Bar();
}
}
-}", options: UseBlockBody);
+}", options: UseBlockBodyIncludingPropertiesAndIndexers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
@@ -279,7 +272,7 @@ int Foo
throw new NotImplementedException();
}
}
-}", options: UseBlockBody);
+}", options: UseBlockBodyIncludingPropertiesAndIndexers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
@@ -302,7 +295,7 @@ int Foo
throw new NotImplementedException(); // comment
}
}
-}", ignoreTrivia: false, options: UseBlockBody);
+}", ignoreTrivia: false, options: UseBlockBodyIncludingPropertiesAndIndexers);
}
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForConstructorsTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForConstructorsAnalyzerTests.cs
similarity index 94%
rename from src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForConstructorsTests.cs
rename to src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForConstructorsAnalyzerTests.cs
index 179293cba2105..b4a82cbdc90de 100644
--- a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForConstructorsTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForConstructorsAnalyzerTests.cs
@@ -14,11 +14,10 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
- public class UseExpressionBodyForConstructorsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
+ public class UseExpressionBodyForConstructorsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (new UseExpressionBodyForConstructorsDiagnosticAnalyzer(),
- new UseExpressionBodyForConstructorsCodeFixProvider());
+ => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary UseExpressionBody =>
Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForConversionOperatorsTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs
similarity index 93%
rename from src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForConversionOperatorsTests.cs
rename to src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs
index e3096b8f56537..87faef0c1780c 100644
--- a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForConversionOperatorsTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForConversionOperatorsAnalyzerTests.cs
@@ -14,11 +14,10 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
- public class UseExpressionBodyForConversionOperatorsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
+ public class UseExpressionBodyForConversionOperatorsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (new UseExpressionBodyForConversionOperatorsDiagnosticAnalyzer(),
- new UseExpressionBodyForConversionOperatorsCodeFixProvider());
+ => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary UseExpressionBody =>
Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForIndexerTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForIndexersAnalyzerTests.cs
similarity index 96%
rename from src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForIndexerTests.cs
rename to src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForIndexersAnalyzerTests.cs
index 99ed686376cdf..7fad114993704 100644
--- a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForIndexerTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForIndexersAnalyzerTests.cs
@@ -14,10 +14,10 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
- public class UseExpressionBodyForIndexersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
+ public class UseExpressionBodyForIndexersAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (new UseExpressionBodyForIndexersDiagnosticAnalyzer(), new UseExpressionBodyForIndexersCodeFixProvider());
+ => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary UseExpressionBody =>
OptionsSet(
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForMethodsTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForMethodsAnalyzerTests.cs
similarity index 98%
rename from src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForMethodsTests.cs
rename to src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForMethodsAnalyzerTests.cs
index 8d07ffd193e07..a7204a1f19e08 100644
--- a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForMethodsTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForMethodsAnalyzerTests.cs
@@ -14,10 +14,10 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
- public class UseExpressionBodyForMethodsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
+ public class UseExpressionBodyForMethodsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (new UseExpressionBodyForMethodsDiagnosticAnalyzer(), new UseExpressionBodyForMethodsCodeFixProvider());
+ => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary UseExpressionBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForOperatorsTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForOperatorsAnalyzerTests.cs
similarity index 94%
rename from src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForOperatorsTests.cs
rename to src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForOperatorsAnalyzerTests.cs
index 93e0e72e657b5..0b622cf69e3b7 100644
--- a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForOperatorsTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForOperatorsAnalyzerTests.cs
@@ -14,11 +14,10 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
- public class UseExpressionBodyForOperatorsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
+ public class UseExpressionBodyForOperatorsAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (new UseExpressionBodyForOperatorsDiagnosticAnalyzer(),
- new UseExpressionBodyForOperatorsCodeFixProvider());
+ => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary UseExpressionBody =>
Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForPropertiesTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForPropertiesAnalyzerTests.cs
similarity index 69%
rename from src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForPropertiesTests.cs
rename to src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForPropertiesAnalyzerTests.cs
index c6b72054ffbfb..d2e21eb196482 100644
--- a/src/EditorFeatures/CSharpTest/UseExpressionBody/UseExpressionBodyForPropertiesTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Analyzer/UseExpressionBodyForPropertiesAnalyzerTests.cs
@@ -14,10 +14,10 @@
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
- public class UseExpressionBodyForPropertiesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
+ public class UseExpressionBodyForPropertiesAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
- => (new UseExpressionBodyForPropertiesDiagnosticAnalyzer(), new UseExpressionBodyForPropertiesCodeFixProvider());
+ => (new UseExpressionBodyDiagnosticAnalyzer(), new UseExpressionBodyCodeFixProvider());
private IDictionary UseExpressionBody =>
OptionsSet(
@@ -244,5 +244,125 @@ await TestInRegularAndScriptAsync(
public string OtherThing => ""Pickles"";
}", ignoreTrivia: false, options: UseExpressionBody);
}
+
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestDirectivesInBlockBody1()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+#if true
+ [|return|] Bar();
+#else
+ return Baz();
+#endif
+ }
+ }
+}",
+
+@"class C
+{
+ int Foo =>
+#if true
+ Bar();
+#else
+ return Baz();
+#endif
+
+}", ignoreTrivia: false,
+ parameters: new TestParameters(options: UseExpressionBody));
+ }
+
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestDirectivesInBlockBody2()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+#if false
+ return Bar();
+#else
+ [|return|] Baz();
+#endif
+ }
+ }
+}",
+
+@"class C
+{
+ int Foo =>
+#if false
+ return Bar();
+#else
+ Baz();
+#endif
+
+}", ignoreTrivia: false,
+ parameters: new TestParameters(options: UseExpressionBody));
+ }
+
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestMissingWithDirectivesInExpressionBody1()
+ {
+ await TestMissingInRegularAndScriptAsync(
+@"class C
+{
+ int Foo [|=>|]
+#if true
+ Bar();
+#else
+ Baz();
+#endif
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestMissingWithDirectivesInExpressionBody2()
+ {
+ await TestMissingInRegularAndScriptAsync(
+@"class C
+{
+ int Foo [|=>|]
+#if false
+ Bar();
+#else
+ Baz();
+#endif
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [WorkItem(19193, "https://github.com/dotnet/roslyn/issues/19193")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestMoveTriviaFromExpressionToReturnStatement()
+ {
+ await TestInRegularAndScriptAsync(
+@"class C
+{
+ int Foo(int i) [|=>|]
+ //comment
+ i * i;
+}",
+@"class C
+{
+ int Foo(int i)
+ {
+ //comment
+ return i * i;
+ }
+}", ignoreTrivia: false,
+ options: UseBlockBody);
+ }
}
}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs
new file mode 100644
index 0000000000000..8629b5840e255
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForAccessorsRefactoringTests.cs
@@ -0,0 +1,155 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
+using Microsoft.CodeAnalysis.Options;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
+{
+ public class UseExpressionBodyForAccessorsRefactoringTests : AbstractCSharpCodeActionTest
+ {
+ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
+ => new UseExpressionBodyCodeRefactoringProvider();
+
+ private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement));
+
+ private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement));
+
+ private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement));
+
+ private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement));
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestUpdatePropertyIfPropertyWantsBlockAndAccesorWantsExpression()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}",
+@"class C
+{
+ int Foo => Bar();
+}", parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody2()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}", parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ return [||]Bar();
+ }
+ }
+}",
+@"class C
+{
+ int Foo { get => Bar(); }
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferExpressionBodyForPropertyIfPropertyAndAccessorBothPreferExpressions()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ return [||]Bar();
+ }
+ }
+}",
+@"class C
+{
+ int Foo => [||]Bar();
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ int Foo { get => [||]Bar(); }
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedForPropertyIfUserPrefersBlockPropertiesAndHasBlockProperty()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo { get => [||]Bar(); }
+}",
+
+@"class C
+{
+ int Foo => Bar();
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferForPropertyIfPropertyPrefersBlockButCouldBecomeExpressionBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo { get => [||]Bar(); }
+}",
+@"class C
+{
+ int Foo => Bar();
+}", parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties));
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs
new file mode 100644
index 0000000000000..45db214ff5557
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs
@@ -0,0 +1,93 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
+using Microsoft.CodeAnalysis.Options;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
+{
+ public class UseExpressionBodyForConstructorsRefactoringTests : AbstractCSharpCodeActionTest
+ {
+ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
+ => new UseExpressionBodyCodeRefactoringProvider();
+
+ private IDictionary UseExpressionBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
+
+ private IDictionary UseBlockBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithNoneEnforcement);
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public C()
+ {
+ [||]Bar();
+ }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ public C()
+ {
+ [||]Bar();
+ }
+}",
+@"class C
+{
+ public C() => Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedInLambda()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public C()
+ {
+ return () => { [||] };
+ }
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public C() => [||]Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ public C() => [||]Bar();
+}",
+@"class C
+{
+ public C() { Bar(); }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs
new file mode 100644
index 0000000000000..9f033cf4536e1
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConversionOperatorsRefactoringTests.cs
@@ -0,0 +1,93 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
+using Microsoft.CodeAnalysis.Options;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
+{
+ public class UseExpressionBodyForConversionOperatorsRefactoringTests : AbstractCSharpCodeActionTest
+ {
+ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
+ => new UseExpressionBodyCodeRefactoringProvider();
+
+ private IDictionary UseExpressionBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
+
+ private IDictionary UseBlockBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithNoneEnforcement);
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public static implicit operator bool(C c1)
+ {
+ [||]Bar();
+ }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ public static implicit operator bool(C c1)
+ {
+ [||]Bar();
+ }
+}",
+@"class C
+{
+ public static implicit operator bool(C c1) => Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedInLambda()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public static implicit operator bool(C c1)
+ {
+ return () => { [||] };
+ }
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public static implicit operator bool(C c1) => [||]Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ public static implicit operator bool(C c1) => [||]Bar();
+}",
+@"class C
+{
+ public static implicit operator bool(C c1) { return Bar(); }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs
new file mode 100644
index 0000000000000..5941b5f57b714
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs
@@ -0,0 +1,102 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
+using Microsoft.CodeAnalysis.Options;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
+{
+ public class UseExpressionBodyForIndexersRefactoringTests : AbstractCSharpCodeActionTest
+ {
+ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
+ => new UseExpressionBodyCodeRefactoringProvider();
+
+ private IDictionary UseExpressionBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
+
+ private IDictionary UseBlockBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithNoneEnforcement);
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ int this[int i]
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+
+[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int this[int i]
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}",
+@"class C
+{
+ int this[int i] => Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedInLambda()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ Action Foo[int i]
+ {
+ get
+ {
+ return () => { [||] };
+ }
+ }
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ int this[int i] => [||]Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int this[int i] => [||]Bar();
+}",
+@"class C
+{
+ int this[int i] { get => Bar(); }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs
new file mode 100644
index 0000000000000..1c49ca1f1af05
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForMethodsRefactoringTests.cs
@@ -0,0 +1,93 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
+using Microsoft.CodeAnalysis.Options;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
+{
+ public class UseExpressionBodyForMethodsRefactoringTests : AbstractCSharpCodeActionTest
+ {
+ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
+ => new UseExpressionBodyCodeRefactoringProvider();
+
+ private IDictionary UseExpressionBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
+
+ private IDictionary UseBlockBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithNoneEnforcement);
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ void Foo()
+ {
+ [||]Bar();
+ }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ void Foo()
+ {
+ [||]Bar();
+ }
+}",
+@"class C
+{
+ void Foo() => Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedInLambda()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ Action Foo()
+ {
+ return () => { [||] };
+ }
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ void Foo() => [||]Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ void Foo() => [||]Bar();
+}",
+@"class C
+{
+ void Foo() { Bar(); }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs
new file mode 100644
index 0000000000000..93e0e4e32453c
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForOperatorsRefactoringTests.cs
@@ -0,0 +1,93 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
+using Microsoft.CodeAnalysis.Options;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
+{
+ public class UseExpressionBodyForOperatorsRefactoringTests : AbstractCSharpCodeActionTest
+ {
+ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
+ => new UseExpressionBodyCodeRefactoringProvider();
+
+ private IDictionary UseExpressionBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement);
+
+ private IDictionary UseBlockBody =>
+ this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithNoneEnforcement);
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public static bool operator +(C c1, C c2)
+ {
+ [||]Bar();
+ }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ public static bool operator +(C c1, C c2)
+ {
+ [||]Bar();
+ }
+}",
+@"class C
+{
+ public static bool operator +(C c1, C c2) => Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedInLambda()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public static bool operator +(C c1, C c2)
+ {
+ return () => { [||] };
+ }
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ public static bool operator +(C c1, C c2) => [||]Bar();
+}", parameters: new TestParameters(options: UseBlockBody));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ public static bool operator +(C c1, C c2) => [||]Bar();
+}",
+@"class C
+{
+ public static bool operator +(C c1, C c2) { return Bar(); }
+}", parameters: new TestParameters(options: UseExpressionBody));
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs
new file mode 100644
index 0000000000000..159586a930e42
--- /dev/null
+++ b/src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForPropertiesRefactoringTests.cs
@@ -0,0 +1,183 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Microsoft.CodeAnalysis.CodeRefactorings;
+using Microsoft.CodeAnalysis.CSharp.CodeStyle;
+using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
+using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
+using Microsoft.CodeAnalysis.Options;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
+{
+ public class UseExpressionBodyForPropertiesRefactoringTests : AbstractCSharpCodeActionTest
+ {
+ protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
+ => new UseExpressionBodyCodeRefactoringProvider();
+
+ private IDictionary UseExpressionBodyForAccessors_BlockBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement));
+
+ private IDictionary UseExpressionBodyForAccessors_ExpressionBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement));
+
+ private IDictionary UseBlockBodyForAccessors_ExpressionBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement));
+
+ private IDictionary UseBlockBodyForAccessors_BlockBodyForProperties =>
+ OptionsSet(
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement),
+ this.SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement));
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}", parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestUpdateAccessorIfAccessWantsBlockAndPropertyWantsExpression()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}",
+@"class C
+{
+ int Foo
+ {
+ get => Bar();
+ }
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}",
+@"class C
+{
+ int Foo => Bar();
+}", parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody2()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo
+ {
+ get
+ {
+ [||]return Bar();
+ }
+ }
+}",
+@"class C
+{
+ int Foo => Bar();
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedInLambda()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ Action Foo
+ {
+ get
+ {
+ return () => { [||] };
+ }
+ }
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ int Foo => [||]Bar();
+}", parameters: new TestParameters(options: UseExpressionBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody2()
+ {
+ await TestMissingAsync(
+@"class C
+{
+ int Foo => [||]Bar();
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_BlockBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo => [||]Bar();
+}",
+@"class C
+{
+ int Foo { get => Bar(); }
+}", parameters: new TestParameters(options: UseExpressionBodyForAccessors_ExpressionBodyForProperties));
+ }
+
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
+ public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody2()
+ {
+ await TestInRegularAndScript1Async(
+@"class C
+{
+ int Foo => [||]Bar();
+}",
+@"class C
+{
+ int Foo { get { return Bar(); } }
+}", parameters: new TestParameters(options: UseBlockBodyForAccessors_ExpressionBodyForProperties));
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/EditorFeatures/CSharpTest/UseObjectInitializer/UseObjectInitializerTests.cs b/src/EditorFeatures/CSharpTest/UseObjectInitializer/UseObjectInitializerTests.cs
index 395fbfce9252e..5d42f49353f05 100644
--- a/src/EditorFeatures/CSharpTest/UseObjectInitializer/UseObjectInitializerTests.cs
+++ b/src/EditorFeatures/CSharpTest/UseObjectInitializer/UseObjectInitializerTests.cs
@@ -534,6 +534,47 @@ public void M()
}
public string Value { get; set; }
+}", ignoreTrivia: false);
+ }
+
+ [WorkItem(19253, "https://github.com/dotnet/roslyn/issues/19253")]
+ [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)]
+ public async Task TestKeepBlankLinesAfter()
+ {
+ await TestInRegularAndScript1Async(
+@"
+class Foo
+{
+ public int Bar { get; set; }
+}
+
+class MyClass
+{
+ public void Main()
+ {
+ var foo = [||]new Foo();
+ foo.Bar = 1;
+
+ int horse = 1;
+ }
+}",
+@"
+class Foo
+{
+ public int Bar { get; set; }
+}
+
+class MyClass
+{
+ public void Main()
+ {
+ var foo = new Foo
+ {
+ Bar = 1
+ };
+
+ int horse = 1;
+ }
}", ignoreTrivia: false);
}
}
diff --git a/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs b/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs
index a14156a13a993..7ecdff7862988 100644
--- a/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs
+++ b/src/EditorFeatures/CSharpTest/Workspaces/WorkspaceTests.cs
@@ -1,6 +1,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.
using System;
+using System.Collections.Generic;
+using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -11,11 +13,10 @@
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
+using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
-using System.Composition;
-using Microsoft.VisualStudio.Composition;
namespace Microsoft.CodeAnalysis.UnitTests.Workspaces
{
@@ -1003,5 +1004,51 @@ public void TestAdditionalFile_AddRemove_FromProject()
Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name);
}
}
+
+ [Fact, WorkItem(209299, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=209299")]
+ public async Task TestLinkedFilesStayInSync()
+ {
+ var originalText = "class Program1 { }";
+ var updatedText = "class Program2 { }";
+
+ var input = $@"
+
+
+ { originalText }
+
+
+
+
+";
+
+ using (var workspace = TestWorkspace.Create(input, exportProvider: s_exportProvider.Value))
+ {
+ var eventArgs = new List();
+
+ workspace.WorkspaceChanged += (s, e) =>
+ {
+ Assert.Equal(WorkspaceChangeKind.DocumentChanged, e.Kind);
+ eventArgs.Add(e);
+ };
+
+ var originalDocumentId = workspace.GetOpenDocumentIds().Single(id => !workspace.GetTestDocument(id).IsLinkFile);
+ var linkedDocumentId = workspace.GetOpenDocumentIds().Single(id => workspace.GetTestDocument(id).IsLinkFile);
+
+ workspace.GetTestDocument(originalDocumentId).Update(SourceText.From("class Program2 { }"));
+ await WaitForWorkspaceOperationsToComplete(workspace);
+
+ Assert.Equal(2, eventArgs.Count);
+ AssertEx.SetEqual(workspace.Projects.SelectMany(p => p.Documents).Select(d => d.Id), eventArgs.Select(e => e.DocumentId));
+
+ Assert.Equal(eventArgs[0].OldSolution, eventArgs[1].OldSolution);
+ Assert.Equal(eventArgs[0].NewSolution, eventArgs[1].NewSolution);
+
+ Assert.Equal(originalText, (await eventArgs[0].OldSolution.GetDocument(originalDocumentId).GetTextAsync().ConfigureAwait(false)).ToString());
+ Assert.Equal(originalText, (await eventArgs[1].OldSolution.GetDocument(originalDocumentId).GetTextAsync().ConfigureAwait(false)).ToString());
+
+ Assert.Equal(updatedText, (await eventArgs[0].NewSolution.GetDocument(originalDocumentId).GetTextAsync().ConfigureAwait(false)).ToString());
+ Assert.Equal(updatedText, (await eventArgs[1].NewSolution.GetDocument(originalDocumentId).GetTextAsync().ConfigureAwait(false)).ToString());
+ }
+ }
}
}
diff --git a/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj b/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj
index 9547822821180..ec235f71db4fb 100644
--- a/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj
+++ b/src/EditorFeatures/CSharpTest2/CSharpEditorServicesTest2.csproj
@@ -142,6 +142,7 @@
Library
Microsoft.CodeAnalysis.Editor.CSharp.UnitTests
Roslyn.Services.Editor.CSharp2.UnitTests
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
UnitTest
diff --git a/src/EditorFeatures/Core/EditorFeatures.csproj b/src/EditorFeatures/Core/EditorFeatures.csproj
index 18b9836a0c890..3a5b371a27e54 100644
--- a/src/EditorFeatures/Core/EditorFeatures.csproj
+++ b/src/EditorFeatures/Core/EditorFeatures.csproj
@@ -466,9 +466,7 @@
-
-
diff --git a/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs b/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs
index c97332511ba64..6c70c68e4bf9c 100644
--- a/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs
+++ b/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs
@@ -150,7 +150,24 @@ await AppendFixesAsync(
{
// sort the result to the order defined by the fixers
var priorityMap = _fixerPriorityMap[document.Project.Language].Value;
- result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1);
+ result.Sort((d1, d2) =>
+ {
+ if (priorityMap.TryGetValue((CodeFixProvider)d1.Provider, out int priority1))
+ {
+ if (priorityMap.TryGetValue((CodeFixProvider)d2.Provider, out int priority2))
+ {
+ return priority1 - priority2;
+ }
+ else
+ {
+ return -1;
+ }
+ }
+ else
+ {
+ return 1;
+ }
+ });
}
// TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/FileSystem/FileSystemCompletionHelper.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/FileSystem/FileSystemCompletionHelper.cs
deleted file mode 100644
index e334b9a4a8896..0000000000000
--- a/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/FileSystem/FileSystemCompletionHelper.cs
+++ /dev/null
@@ -1,289 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.Completion;
-using Microsoft.CodeAnalysis.Shared.Extensions;
-using Microsoft.CodeAnalysis.Shared.Utilities;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem
-{
- internal sealed class FileSystemCompletionHelper
- {
- private readonly ICurrentWorkingDirectoryDiscoveryService _fileSystemDiscoveryService;
- private readonly Func _exclude;
- private readonly Glyph _folderGlyph;
- private readonly Glyph _fileGlyph;
-
- // absolute paths
- private readonly ImmutableArray _searchPaths;
-
- private readonly ISet _allowableExtensions;
-
- private readonly Lazy _lazyGetDrives;
- private readonly CompletionProvider _completionProvider;
- private readonly TextSpan _textChangeSpan;
- private readonly CompletionItemRules _itemRules;
-
- public FileSystemCompletionHelper(
- CompletionProvider completionProvider,
- TextSpan textChangeSpan,
- ICurrentWorkingDirectoryDiscoveryService fileSystemDiscoveryService,
- Glyph folderGlyph,
- Glyph fileGlyph,
- ImmutableArray searchPaths,
- IEnumerable allowableExtensions,
- Func exclude = null,
- CompletionItemRules itemRules = null)
- {
- Debug.Assert(searchPaths.All(path => PathUtilities.IsAbsolute(path)));
-
- _completionProvider = completionProvider;
- _textChangeSpan = textChangeSpan;
- _searchPaths = searchPaths;
- _allowableExtensions = allowableExtensions.Select(e => e.ToLowerInvariant()).ToSet();
- _fileSystemDiscoveryService = fileSystemDiscoveryService;
- _folderGlyph = folderGlyph;
- _fileGlyph = fileGlyph;
- _exclude = exclude;
- _itemRules = itemRules;
-
- _lazyGetDrives = new Lazy(() =>
- IOUtilities.PerformIO(Directory.GetLogicalDrives, Array.Empty()));
- }
-
- public ImmutableArray GetItems(string pathSoFar, string documentPath)
- {
- if (_exclude != null && _exclude(pathSoFar))
- {
- return ImmutableArray.Empty;
- }
-
- return GetFilesAndDirectories(pathSoFar, documentPath);
- }
-
- private CompletionItem CreateCurrentDirectoryItem()
- {
- return CommonCompletionItem.Create(".", rules: _itemRules);
- }
-
- private CompletionItem CreateParentDirectoryItem()
- {
- return CommonCompletionItem.Create("..", rules: _itemRules);
- }
-
- private CompletionItem CreateNetworkRoot(TextSpan textChangeSpan)
- {
- return CommonCompletionItem.Create("\\\\", rules: _itemRules);
- }
-
- private ImmutableArray GetFilesAndDirectories(string path, string basePath)
- {
- var result = ArrayBuilder.GetInstance();
- var pathKind = PathUtilities.GetPathKind(path);
- switch (pathKind)
- {
- case PathKind.Empty:
- result.Add(CreateCurrentDirectoryItem());
-
- if (!IsDriveRoot(_fileSystemDiscoveryService.WorkingDirectory))
- {
- result.Add(CreateParentDirectoryItem());
- }
-
- result.Add(CreateNetworkRoot(_textChangeSpan));
- result.AddRange(GetLogicalDrives());
- result.AddRange(GetFilesAndDirectoriesInSearchPaths());
- break;
-
- case PathKind.Absolute:
- case PathKind.RelativeToCurrentDirectory:
- case PathKind.RelativeToCurrentParent:
- case PathKind.RelativeToCurrentRoot:
- {
- var fullPath = FileUtilities.ResolveRelativePath(
- path,
- basePath,
- _fileSystemDiscoveryService.WorkingDirectory);
-
- if (fullPath != null)
- {
- result.AddRange(GetFilesAndDirectoriesInDirectory(fullPath));
-
- // although it is possible to type "." here, it doesn't make any sense to do so:
- if (!IsDriveRoot(fullPath) && pathKind != PathKind.Absolute)
- {
- result.Add(CreateParentDirectoryItem());
- }
-
- if (path == "\\" && pathKind == PathKind.RelativeToCurrentRoot)
- {
- // The user has typed only "\". In this case, we want to add "\\" to
- // the list. Also, the textChangeSpan needs to be backed up by one
- // so that it will consume the "\" when "\\" is inserted.
- result.Add(CreateNetworkRoot(TextSpan.FromBounds(_textChangeSpan.Start - 1, _textChangeSpan.End)));
- }
- }
- else
- {
- // invalid path
- result.Clear();
- }
- }
-
- break;
-
- case PathKind.Relative:
-
- // although it is possible to type "." here, it doesn't make any sense to do so:
- result.Add(CreateParentDirectoryItem());
-
- foreach (var searchPath in _searchPaths)
- {
- var fullPath = PathUtilities.CombineAbsoluteAndRelativePaths(searchPath, path);
-
- // search paths are always absolute:
- Debug.Assert(PathUtilities.IsAbsolute(fullPath));
- result.AddRange(GetFilesAndDirectoriesInDirectory(fullPath));
- }
-
- break;
-
- case PathKind.RelativeToDriveDirectory:
- // these paths are not supported
- break;
-
- default:
- throw ExceptionUtilities.UnexpectedValue(pathKind);
- }
-
- return result.ToImmutableAndFree();
- }
-
- private static bool IsDriveRoot(string fullPath)
- {
- return IOUtilities.PerformIO(() => new DirectoryInfo(fullPath).Parent == null);
- }
-
- private IEnumerable GetFilesAndDirectoriesInDirectory(string fullDirectoryPath)
- {
- Debug.Assert(PathUtilities.IsAbsolute(fullDirectoryPath));
- if (IOUtilities.PerformIO(() => Directory.Exists(fullDirectoryPath)))
- {
- var directoryInfo = IOUtilities.PerformIO(() => new DirectoryInfo(fullDirectoryPath));
- if (directoryInfo != null)
- {
- return from child in GetFileSystemInfos(directoryInfo)
- where ShouldShow(child)
- where CanAccess(child)
- select this.CreateCompletion(child);
- }
- }
-
- return SpecializedCollections.EmptyEnumerable();
- }
-
- private CompletionItem CreateCompletion(FileSystemInfo child)
- {
- return CommonCompletionItem.Create(
- child.Name,
- glyph: child is DirectoryInfo ? _folderGlyph : _fileGlyph,
- description: child.FullName.ToSymbolDisplayParts(),
- rules: _itemRules);
- }
-
- private bool ShouldShow(FileSystemInfo child)
- {
- // Get the attributes. If we can't, assume it's hidden.
- var attributes = IOUtilities.PerformIO(() => child.Attributes, FileAttributes.Hidden);
-
- // Don't show hidden/system files.
- if ((attributes & FileAttributes.Hidden) != 0 ||
- (attributes & FileAttributes.System) != 0)
- {
- return false;
- }
-
- if (child is DirectoryInfo)
- {
- return true;
- }
-
- if (child is FileInfo)
- {
- return
- _allowableExtensions.Count == 0 ||
- _allowableExtensions.Contains(Path.GetExtension(child.Name).ToLowerInvariant());
- }
-
- return false;
- }
-
- private bool CanAccess(FileSystemInfo info)
- {
- switch (info)
- {
- case DirectoryInfo d: return CanAccessDirectory(d);
- case FileInfo f: return CanAccessFile(f);
- }
-
- return false;
- }
-
- private bool CanAccessFile(FileInfo file)
- {
- var accessControl = IOUtilities.PerformIO(file.GetAccessControl);
-
- // Quick and dirty check. If we can't even get the access control object, then we
- // can't access the file.
- if (accessControl == null)
- {
- return false;
- }
-
- // TODO(cyrusn): Actually add checks here.
- return true;
- }
-
- private bool CanAccessDirectory(DirectoryInfo directory)
- {
- var accessControl = IOUtilities.PerformIO(directory.GetAccessControl);
-
- // Quick and dirty check. If we can't even get the access control object, then we
- // can't access the file.
- if (accessControl == null)
- {
- return false;
- }
-
- // TODO(cyrusn): Do more checks here.
- return true;
- }
-
- private IEnumerable GetFilesAndDirectoriesInSearchPaths()
- {
- return _searchPaths.SelectMany(GetFilesAndDirectoriesInDirectory);
- }
-
- private IEnumerable GetLogicalDrives()
- {
- // First, we may have a filename, so let's include all drives
- return from d in _lazyGetDrives.Value
- where d.Length > 0 && (d.Last() == Path.DirectorySeparatorChar || d.Last() == Path.AltDirectorySeparatorChar)
- let text = d.Substring(0, d.Length - 1)
- select CommonCompletionItem.Create(text, glyph: _folderGlyph, rules: _itemRules);
- }
-
- private static FileSystemInfo[] GetFileSystemInfos(DirectoryInfo directoryInfo)
- {
- return IOUtilities.PerformIO(directoryInfo.GetFileSystemInfos, Array.Empty());
- }
- }
-}
diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/FileSystem/PathCompletionUtilities.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/FileSystem/PathCompletionUtilities.cs
deleted file mode 100644
index 2f6774440b78c..0000000000000
--- a/src/EditorFeatures/Core/Implementation/IntelliSense/Completion/FileSystem/PathCompletionUtilities.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-using System;
-using Microsoft.CodeAnalysis.Completion;
-using Microsoft.CodeAnalysis.Text;
-using Roslyn.Utilities;
-
-namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem
-{
- internal static class PathCompletionUtilities
- {
- internal static bool IsTriggerCharacter(SourceText text, int characterPosition)
- {
- // Bring up completion when the user types a quote (i.e.: #r "), or if they type a slash
- // path separator character, or if they type a comma (#r "foo,version...").
- //
- // Also, if they're starting a word. i.e. #r "c:\W
- var ch = text[characterPosition];
- return ch == '"' || ch == '\\' || ch == ',' ||
- CommonCompletionUtilities.IsStartingNewWord(text, characterPosition, char.IsLetter, char.IsLetterOrDigit);
- }
-
- internal static bool IsFilterCharacter(CompletionItem item, char ch, string textTypedSoFar)
- {
- // If the user types something that matches what is in the completion list, then just
- // count it as a filter character.
-
- // For example, if they type "Program " and "Program Files" is in the list, the
- // should be counted as a filter character and not a commit character.
- return item.DisplayText.StartsWith(textTypedSoFar, StringComparison.OrdinalIgnoreCase);
- }
-
- internal static bool IsCommitcharacter(CompletionItem item, char ch, string textTypedSoFar)
- {
- return ch == '"' || ch == '\\' || ch == ',';
- }
-
- internal static bool SendEnterThroughToEditor(CompletionItem item, string textTypedSoFar)
- {
- return false;
- }
-
- internal static string GetPathThroughLastSlash(string quotedPath, int quotedPathStart, int position)
- {
- Contract.ThrowIfTrue(quotedPath[0] != '"');
-
- const int QuoteLength = 1;
-
- var positionInQuotedPath = position - quotedPathStart;
- var path = quotedPath.Substring(QuoteLength, positionInQuotedPath - QuoteLength).Trim();
- var afterLastSlashIndex = AfterLastSlashIndex(path, path.Length);
-
- // We want the portion up to, and including the last slash if there is one. That way if
- // the user pops up completion in the middle of a path (i.e. "C:\Win") then we'll
- // consider the path to be "C:\" and we will show appropriate completions.
- return afterLastSlashIndex >= 0 ? path.Substring(0, afterLastSlashIndex) : path;
- }
-
- internal static TextSpan GetTextChangeSpan(string quotedPath, int quotedPathStart, int position)
- {
- // We want the text change to be from after the last slash to the end of the quoted
- // path. If there is no last slash, then we want it from right after the start quote
- // character.
- var positionInQuotedPath = position - quotedPathStart;
-
- // Where we want to start tracking is right after the slash (if we have one), or else
- // right after the string starts.
- var afterLastSlashIndex = PathCompletionUtilities.AfterLastSlashIndex(quotedPath, positionInQuotedPath);
- var afterFirstQuote = 1;
-
- var startIndex = Math.Max(afterLastSlashIndex, afterFirstQuote);
- var endIndex = quotedPath.Length;
-
- // If the string ends with a quote, the we do not want to consume that.
- if (EndsWithQuote(quotedPath))
- {
- endIndex--;
- }
-
- return TextSpan.FromBounds(startIndex + quotedPathStart, endIndex + quotedPathStart);
- }
-
- internal static bool EndsWithQuote(string quotedPath)
- {
- return quotedPath.Length >= 2 && quotedPath[quotedPath.Length - 1] == '"';
- }
-
- ///
- /// Returns the index right after the last slash that precedes 'position'. If there is no
- /// slash in the string, -1 is returned.
- ///
- private static int AfterLastSlashIndex(string text, int position)
- {
- // Position might be out of bounds of the string (if the string is unterminated. Make
- // sure it's within bounds.
- position = Math.Min(position, text.Length - 1);
-
- int index;
- if ((index = text.LastIndexOf('/', position)) >= 0 ||
- (index = text.LastIndexOf('\\', position)) >= 0)
- {
- return index + 1;
- }
-
- return -1;
- }
- }
-}
diff --git a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs
index 6aea6a5cfd0cb..c55a80cabbe01 100644
--- a/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs
+++ b/src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ProduceTags.cs
@@ -600,28 +600,28 @@ private void ProcessNewTagTrees(
var bufferToChanges = new Dictionary();
using (Logger.LogBlock(FunctionId.Tagger_TagSource_ProcessNewTags, cancellationToken))
{
- foreach (var latestBuffer in newTagTrees.Keys)
+ foreach (var (latestBuffer, latestSpans) in newTagTrees)
{
var snapshot = spansToTag.First(s => s.SnapshotSpan.Snapshot.TextBuffer == latestBuffer).SnapshotSpan.Snapshot;
- if (oldTagTrees.ContainsKey(latestBuffer))
+ if (oldTagTrees.TryGetValue(latestBuffer, out var previousSpans))
{
- var difference = ComputeDifference(snapshot, newTagTrees[latestBuffer], oldTagTrees[latestBuffer]);
+ var difference = ComputeDifference(snapshot, latestSpans, previousSpans);
bufferToChanges[latestBuffer] = difference;
}
else
{
// It's a new buffer, so report all spans are changed
- bufferToChanges[latestBuffer] = new DiffResult(added: newTagTrees[latestBuffer].GetSpans(snapshot).Select(t => t.Span), removed: null);
+ bufferToChanges[latestBuffer] = new DiffResult(added: latestSpans.GetSpans(snapshot).Select(t => t.Span), removed: null);
}
}
- foreach (var oldBuffer in oldTagTrees.Keys)
+ foreach (var (oldBuffer, previousSpans) in oldTagTrees)
{
if (!newTagTrees.ContainsKey(oldBuffer))
{
// This buffer disappeared, so let's notify that the old tags are gone
- bufferToChanges[oldBuffer] = new DiffResult(added: null, removed: oldTagTrees[oldBuffer].GetSpans(oldBuffer.CurrentSnapshot).Select(t => t.Span));
+ bufferToChanges[oldBuffer] = new DiffResult(added: null, removed: previousSpans.GetSpans(oldBuffer.CurrentSnapshot).Select(t => t.Span));
}
}
}
diff --git a/src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs b/src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs
new file mode 100644
index 0000000000000..75c0a5a0af3a0
--- /dev/null
+++ b/src/EditorFeatures/Test/Completion/FileSystemCompletionHelperTests.cs
@@ -0,0 +1,234 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Immutable;
+using System.Linq;
+using System.Threading;
+using Microsoft.CodeAnalysis.Completion;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion
+{
+ public class FileSystemCompletionHelperTests
+ {
+ private void AssertItemsEqual(ImmutableArray actual, params string[] expected)
+ {
+ AssertEx.Equal(
+ expected,
+ actual.Select(c => $"'{c.DisplayText}', {string.Join(", ", c.Tags)}, '{c.Properties["Description"]}'"),
+ itemInspector: c => $"@\"{c}\"");
+
+ Assert.True(actual.All(i => i.Rules == TestFileSystemCompletionHelper.CompletionRules));
+ }
+
+ [ConditionalFact(typeof(WindowsOnly))]
+ public void GetItems_Windows1()
+ {
+ var fsc = new TestFileSystemCompletionHelper(
+ searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"),
+ baseDirectoryOpt: @"Z:\C",
+ allowableExtensions: ImmutableArray.Create(".abc", ".def"),
+ drives: new[] { @"X:\", @"Z:\" },
+ directories: new[]
+ {
+ @"X:",
+ @"X:\A",
+ @"X:\A\1",
+ @"X:\A\2",
+ @"X:\A\3",
+ @"X:\B",
+ @"Z:",
+ @"Z:\C",
+ @"Z:\D",
+ },
+ files: new[]
+ {
+ @"X:\A\1\file1.abc",
+ @"X:\A\2\file2.abc",
+ @"X:\B\file4.x",
+ @"X:\B\file5.abc",
+ @"X:\B\hidden.def",
+ @"Z:\C\file6.def",
+ @"Z:\C\file.7.def",
+ });
+
+ // Note backslashes in description are escaped
+ AssertItemsEqual(fsc.GetItems("", CancellationToken.None),
+ @"'file6.def', File, C#, 'Text|Z:\5CC\5Cfile6.def'",
+ @"'file.7.def', File, C#, 'Text|Z:\5CC\5Cfile.7.def'",
+ @"'X:', Folder, 'Text|X:'",
+ @"'Z:', Folder, 'Text|Z:'",
+ @"'\\', , 'Text|\5C\5C'",
+ @"'1', Folder, 'Text|X:\5CA\5C1'",
+ @"'2', Folder, 'Text|X:\5CA\5C2'",
+ @"'3', Folder, 'Text|X:\5CA\5C3'",
+ @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'");
+
+ AssertItemsEqual(fsc.GetItems(@"X:\A\", CancellationToken.None),
+ @"'1', Folder, 'Text|X:\5CA\5C1'",
+ @"'2', Folder, 'Text|X:\5CA\5C2'",
+ @"'3', Folder, 'Text|X:\5CA\5C3'");
+
+ AssertItemsEqual(fsc.GetItems(@"X:\B\", CancellationToken.None),
+ @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'");
+
+ AssertItemsEqual(fsc.GetItems(@"Z:\", CancellationToken.None),
+ @"'C', Folder, 'Text|Z:\5CC'",
+ @"'D', Folder, 'Text|Z:\5CD'");
+
+ AssertItemsEqual(fsc.GetItems(@"Z:", CancellationToken.None),
+ @"'Z:', Folder, 'Text|Z:'");
+
+ AssertItemsEqual(fsc.GetItems(@"\", CancellationToken.None),
+ @"'\\', , 'Text|\5C\5C'");
+ }
+
+ [ConditionalFact(typeof(WindowsOnly))]
+ public void GetItems_Windows_NoBaseDirectory()
+ {
+ var fsc = new TestFileSystemCompletionHelper(
+ searchPaths: ImmutableArray.Create(@"X:\A", @"X:\B"),
+ baseDirectoryOpt: null,
+ allowableExtensions: ImmutableArray.Create(".abc", ".def"),
+ drives: new[] { @"X:\" },
+ directories: new[]
+ {
+ @"X:",
+ @"X:\A",
+ @"X:\A\1",
+ @"X:\A\2",
+ @"X:\A\3",
+ @"X:\B",
+ },
+ files: new[]
+ {
+ @"X:\A\1\file1.abc",
+ @"X:\A\2\file2.abc",
+ @"X:\B\file4.x",
+ @"X:\B\file5.abc",
+ @"X:\B\hidden.def",
+ });
+
+ // Note backslashes in description are escaped
+ AssertItemsEqual(fsc.GetItems(@"", CancellationToken.None),
+ @"'X:', Folder, 'Text|X:'",
+ @"'\\', , 'Text|\5C\5C'",
+ @"'1', Folder, 'Text|X:\5CA\5C1'",
+ @"'2', Folder, 'Text|X:\5CA\5C2'",
+ @"'3', Folder, 'Text|X:\5CA\5C3'",
+ @"'file5.abc', File, C#, 'Text|X:\5CB\5Cfile5.abc'");
+ }
+
+ [ConditionalFact(typeof(WindowsOnly))]
+ public void GetItems_Windows_NoSearchPaths()
+ {
+ var fsc = new TestFileSystemCompletionHelper(
+ searchPaths: ImmutableArray.Empty,
+ baseDirectoryOpt: null,
+ allowableExtensions: ImmutableArray.Create(".abc", ".def"),
+ drives: new[] { @"X:\" },
+ directories: new[]
+ {
+ @"X:",
+ @"X:\A",
+ @"X:\A\1",
+ @"X:\A\2",
+ @"X:\A\3",
+ @"X:\B",
+ },
+ files: new[]
+ {
+ @"X:\A\1\file1.abc",
+ @"X:\A\2\file2.abc",
+ @"X:\B\file4.x",
+ @"X:\B\file5.abc",
+ @"X:\B\hidden.def",
+ });
+
+ // Note backslashes in description are escaped
+ AssertItemsEqual(fsc.GetItems(@"", CancellationToken.None),
+ @"'X:', Folder, 'Text|X:'",
+ @"'\\', , 'Text|\5C\5C'");
+ }
+
+ [ConditionalFact(typeof(WindowsOnly))]
+ public void GetItems_Windows_Network()
+ {
+ var fsc = new TestFileSystemCompletionHelper(
+ searchPaths: ImmutableArray.Empty,
+ baseDirectoryOpt: null,
+ allowableExtensions: ImmutableArray.Create(".cs"),
+ drives: Array.Empty(),
+ directories: new[]
+ {
+ @"\\server\share",
+ @"\\server\share\C",
+ @"\\server\share\D",
+ },
+ files: new[]
+ {
+ @"\\server\share\C\b.cs",
+ @"\\server\share\C\c.cs",
+ @"\\server\share\D\e.cs",
+ });
+
+ AssertItemsEqual(fsc.GetItems(@"\\server\share\", CancellationToken.None),
+ @"'C', Folder, 'Text|\5C\5Cserver\5Cshare\5CC'",
+ @"'D', Folder, 'Text|\5C\5Cserver\5Cshare\5CD'");
+
+ AssertItemsEqual(fsc.GetItems(@"\\server\share\C\", CancellationToken.None),
+ @"'b.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cb.cs'",
+ @"'c.cs', File, C#, 'Text|\5C\5Cserver\5Cshare\5CC\5Cc.cs'");
+ }
+
+ [ConditionalFact(typeof(UnixLikeOnly))]
+ public void GetItems_Unix1()
+ {
+ var fsc = new TestFileSystemCompletionHelper(
+ searchPaths: ImmutableArray.Create(@"/A", @"/B"),
+ baseDirectoryOpt: @"/C",
+ allowableExtensions: ImmutableArray.Create(".abc", ".def"),
+ drives: Array.Empty(),
+ directories: new[]
+ {
+ @"/A",
+ @"/A/1",
+ @"/A/2",
+ @"/A/3",
+ @"/B",
+ @"/C",
+ @"/D",
+ },
+ files: new[]
+ {
+ @"/A/1/file1.abc",
+ @"/A/2/file2.abc",
+ @"/B/file4.x",
+ @"/B/file5.abc",
+ @"/B/hidden.def",
+ @"/C/file6.def",
+ @"/C/file.7.def",
+ });
+
+ // Note backslashes in description are escaped
+ AssertItemsEqual(fsc.GetItems(@"", CancellationToken.None),
+ @"'file6.def', File, C#, 'Text|/C/file6.def'",
+ @"'file.7.def', File, C#, 'Text|/C/file.7.def'",
+ @"'/', Folder, 'Text|/'",
+ @"'1', Folder, 'Text|/A/1'",
+ @"'2', Folder, 'Text|/A/2'",
+ @"'3', Folder, 'Text|/A/3'",
+ @"'file5.abc', File, C#, 'Text|/B/file5.abc'");
+
+ AssertItemsEqual(fsc.GetItems(@"/", CancellationToken.None),
+ @"'A', Folder, 'Text|/A'",
+ @"'B', Folder, 'Text|/B'",
+ @"'C', Folder, 'Text|/C'",
+ @"'D', Folder, 'Text|/D'");
+
+ AssertItemsEqual(fsc.GetItems(@"/B/", CancellationToken.None),
+ @"'file5.abc', File, C#, 'Text|/B/file5.abc'");
+ }
+ }
+}
diff --git a/src/EditorFeatures/Test/Completion/GlobalAssemblyCacheCompletionHelperTests.cs b/src/EditorFeatures/Test/Completion/GlobalAssemblyCacheCompletionHelperTests.cs
new file mode 100644
index 0000000000000..ce5abe28ef17a
--- /dev/null
+++ b/src/EditorFeatures/Test/Completion/GlobalAssemblyCacheCompletionHelperTests.cs
@@ -0,0 +1,44 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Completion;
+using Microsoft.CodeAnalysis.Editor.Completion.FileSystem;
+using Microsoft.CodeAnalysis.Text;
+using Roslyn.Test.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntelliSense.CompletionSetSources
+{
+ [Trait(Traits.Feature, Traits.Features.Completion)]
+ public class GlobalAssemblyCacheCompletionHelperTests
+ {
+ [ConditionalFact(typeof(WindowsOnly))]
+ public void ExistingReference()
+ {
+ var code = "System.Windows";
+ VerifyPresence(code, "System.Windows.Forms");
+ }
+
+ [ConditionalFact(typeof(WindowsOnly))]
+ public void FullReferenceIdentity()
+ {
+ var code = "System,";
+ VerifyPresence(code, typeof(System.Diagnostics.Process).Assembly.FullName);
+ }
+
+ private static void VerifyPresence(string pathSoFar, string completionItem)
+ {
+ var completions = GetItems(pathSoFar);
+ Assert.True(completions.Any(c => c.DisplayText == completionItem));
+ }
+
+ private static IEnumerable GetItems(string pathSoFar)
+ {
+ var helper = new GlobalAssemblyCacheCompletionHelper(CompletionItemRules.Default);
+ return helper.GetItems(pathSoFar, CancellationToken.None);
+ }
+ }
+}
diff --git a/src/EditorFeatures/Test/Completion/TestFileSystemCompletionHelper.cs b/src/EditorFeatures/Test/Completion/TestFileSystemCompletionHelper.cs
new file mode 100644
index 0000000000000..c1a8d9d180256
--- /dev/null
+++ b/src/EditorFeatures/Test/Completion/TestFileSystemCompletionHelper.cs
@@ -0,0 +1,62 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using Microsoft.CodeAnalysis.Completion;
+using Roslyn.Utilities;
+using Xunit;
+
+namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion
+{
+ internal sealed class TestFileSystemCompletionHelper : FileSystemCompletionHelper
+ {
+ internal static readonly CompletionItemRules CompletionRules = CompletionItemRules.Default;
+
+ private readonly ImmutableArray _directories;
+ private readonly ImmutableArray _files;
+ private readonly ImmutableArray _drives;
+
+ public TestFileSystemCompletionHelper(
+ ImmutableArray searchPaths,
+ string baseDirectoryOpt,
+ ImmutableArray allowableExtensions,
+ IEnumerable drives,
+ IEnumerable directories,
+ IEnumerable files)
+ : base(Glyph.OpenFolder, Glyph.CSharpFile, searchPaths, baseDirectoryOpt, allowableExtensions, CompletionRules)
+ {
+ Assert.True(drives.All(d => d.EndsWith(PathUtilities.DirectorySeparatorStr)));
+ Assert.True(directories.All(d => !d.EndsWith(PathUtilities.DirectorySeparatorStr)));
+
+ _drives = ImmutableArray.CreateRange(drives);
+ _directories = ImmutableArray.CreateRange(directories);
+ _files = ImmutableArray.CreateRange(files);
+ }
+
+ protected override string[] GetLogicalDrives() =>
+ _drives.ToArray();
+
+ protected override bool IsVisibleFileSystemEntry(string fullPath) =>
+ !fullPath.Contains("hidden");
+
+ protected override bool DirectoryExists(string fullPath) =>
+ _directories.Contains(fullPath.TrimEnd(PathUtilities.DirectorySeparatorChar));
+
+ protected override IEnumerable EnumerateDirectories(string fullDirectoryPath) =>
+ Enumerate(_directories, fullDirectoryPath);
+
+ protected override IEnumerable EnumerateFiles(string fullDirectoryPath) =>
+ Enumerate(_files, fullDirectoryPath);
+
+ private IEnumerable Enumerate(ImmutableArray entries, string fullDirectoryPath)
+ {
+ var withTrailingSeparator = fullDirectoryPath.TrimEnd(PathUtilities.DirectorySeparatorChar) + PathUtilities.DirectorySeparatorChar;
+ return from d in entries
+ where d.StartsWith(withTrailingSeparator)
+ let nextSeparator = d.IndexOf(PathUtilities.DirectorySeparatorChar, withTrailingSeparator.Length)
+ select d.Substring(0, (nextSeparator >= 0) ? nextSeparator : d.Length);
+ }
+ }
+}
diff --git a/src/EditorFeatures/Test/EditorServicesTest.csproj b/src/EditorFeatures/Test/EditorServicesTest.csproj
index 3e97cdf6e5b5e..5fd0df6032926 100644
--- a/src/EditorFeatures/Test/EditorServicesTest.csproj
+++ b/src/EditorFeatures/Test/EditorServicesTest.csproj
@@ -13,6 +13,7 @@
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
UnitTest
@@ -224,6 +225,9 @@
+
+
+
diff --git a/src/EditorFeatures/Test2/EditorServicesTest2.vbproj b/src/EditorFeatures/Test2/EditorServicesTest2.vbproj
index d0b690759a7a0..53a950f293939 100644
--- a/src/EditorFeatures/Test2/EditorServicesTest2.vbproj
+++ b/src/EditorFeatures/Test2/EditorServicesTest2.vbproj
@@ -13,6 +13,7 @@
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}
UnitTest
diff --git a/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb b/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb
index acc436b8b6db9..e7a15b31985d4 100644
--- a/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb
+++ b/src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb
@@ -3585,6 +3585,31 @@ partial class {|current:$$C|} { }
result.AssertLabeledSpansAre("current", type:=RelatedLocationType.NoConflict)
End Using
End Sub
+
+
+
+
+ Public Sub RenameMethodToFinalizeWithDestructorPresent()
+ Using result = RenameEngineResult.Create(_outputHelper,
+
+
+
+class C
+{
+ ~{|Conflict:C|}() { }
+ void $$[|M|]()
+ {
+ int x = 7;
+ int y = ~x;
+ }
+}
+
+
+ , renameTo:="Finalize")
+
+ result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
+ End Using
+ End Sub
End Class
End Namespace
diff --git a/src/EditorFeatures/TestUtilities/EditAndContinue/EditAndContinueTestHelpers.cs b/src/EditorFeatures/TestUtilities/EditAndContinue/EditAndContinueTestHelpers.cs
index c64ac7fd1b24d..c3865e799b69d 100644
--- a/src/EditorFeatures/TestUtilities/EditAndContinue/EditAndContinueTestHelpers.cs
+++ b/src/EditorFeatures/TestUtilities/EditAndContinue/EditAndContinueTestHelpers.cs
@@ -205,6 +205,7 @@ internal void VerifySemantics(
IEnumerable additionalOldSources = null,
IEnumerable additionalNewSources = null,
SemanticEditDescription[] expectedSemanticEdits = null,
+ DiagnosticDescription expectedDeclarationError = null,
RudeEditDiagnosticDescription[] expectedDiagnostics = null)
{
var editMap = Analyzer.BuildEditMap(editScript);
@@ -234,18 +235,6 @@ internal void VerifySemantics(
var oldCompilation = CreateLibraryCompilation("Old", oldTrees);
var newCompilation = CreateLibraryCompilation("New", newTrees);
- if (oldCompilation is CSharpCompilation)
- {
- oldCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
- newCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
- }
- else
- {
- // TODO: verify all compilation diagnostics like C# does (tests need to be updated)
- oldTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
- newTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
- }
-
var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree);
var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);
@@ -297,8 +286,13 @@ internal void VerifySemantics(
newModel,
actualSemanticEdits,
diagnostics,
+ out var firstDeclarationErrorOpt,
default(CancellationToken));
+ var actualDeclarationErrors = (firstDeclarationErrorOpt != null) ? new[] { firstDeclarationErrorOpt } : Array.Empty();
+ var expectedDeclarationErrors = (expectedDeclarationError != null) ? new[] { expectedDeclarationError } : Array.Empty();
+ actualDeclarationErrors.Verify(expectedDeclarationErrors);
+
diagnostics.Verify(newSource, expectedDiagnostics);
if (expectedSemanticEdits == null)
diff --git a/src/EditorFeatures/TestUtilities/ServicesTestUtilities.csproj b/src/EditorFeatures/TestUtilities/ServicesTestUtilities.csproj
index e72245fa212ed..af02f007d3e4b 100644
--- a/src/EditorFeatures/TestUtilities/ServicesTestUtilities.csproj
+++ b/src/EditorFeatures/TestUtilities/ServicesTestUtilities.csproj
@@ -287,6 +287,7 @@
+
diff --git a/src/EditorFeatures/TestUtilities/TestExportProvider.cs b/src/EditorFeatures/TestUtilities/TestExportProvider.cs
index 5451bfbcc8d90..47ded14219e30 100644
--- a/src/EditorFeatures/TestUtilities/TestExportProvider.cs
+++ b/src/EditorFeatures/TestUtilities/TestExportProvider.cs
@@ -72,6 +72,8 @@ private static Type[] GetNeutralAndCSharpAndVisualBasicTypes()
typeof(CodeAnalysis.VisualBasic.CodeGeneration.VisualBasicSyntaxGenerator),
typeof(CSharp.LanguageServices.CSharpContentTypeLanguageService),
typeof(VisualBasic.LanguageServices.VisualBasicContentTypeLanguageService),
+ typeof(CodeAnalysis.CSharp.Execution.CSharpOptionsSerializationService),
+ typeof(CodeAnalysis.VisualBasic.Execution.VisualBasicOptionsSerializationService),
typeof(TestExportProvider)
};
diff --git a/src/EditorFeatures/TestUtilities/Workspaces/TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.cs b/src/EditorFeatures/TestUtilities/Workspaces/TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.cs
new file mode 100644
index 0000000000000..cbd71aef192f9
--- /dev/null
+++ b/src/EditorFeatures/TestUtilities/Workspaces/TestSymbolRenamedCodeActionOperationFactoryWorkspaceService.cs
@@ -0,0 +1,34 @@
+// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System.Composition;
+using Microsoft.CodeAnalysis.CodeActions;
+using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices;
+using Microsoft.CodeAnalysis.Host.Mef;
+
+namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
+{
+ [ExportWorkspaceService(typeof(ISymbolRenamedCodeActionOperationFactoryWorkspaceService), TestWorkspace.WorkspaceName), Shared]
+ public class TestSymbolRenamedCodeActionOperationFactoryWorkspaceService : ISymbolRenamedCodeActionOperationFactoryWorkspaceService
+ {
+ public CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution)
+ {
+ return new Operation(symbol, newName, startingSolution, updatedSolution);
+ }
+
+ public class Operation : CodeActionOperation
+ {
+ public ISymbol _symbol;
+ public string _newName;
+ public Solution _startingSolution;
+ public Solution _updatedSolution;
+
+ public Operation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution)
+ {
+ _symbol = symbol;
+ _newName = newName;
+ _startingSolution = startingSolution;
+ _updatedSolution = updatedSolution;
+ }
+ }
+ }
+}
diff --git a/src/EditorFeatures/VisualBasicTest/BasicEditorServicesTest.vbproj b/src/EditorFeatures/VisualBasicTest/BasicEditorServicesTest.vbproj
index 800d051d8af7b..5960dd18eb7f3 100644
--- a/src/EditorFeatures/VisualBasicTest/BasicEditorServicesTest.vbproj
+++ b/src/EditorFeatures/VisualBasicTest/BasicEditorServicesTest.vbproj
@@ -14,6 +14,7 @@
v4.6
win7
+ {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}
UnitTest
diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/InlineTemporary/InlineTemporaryTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/InlineTemporary/InlineTemporaryTests.vb
index ee0735d40dc86..5d369567f276e 100644
--- a/src/EditorFeatures/VisualBasicTest/CodeActions/InlineTemporary/InlineTemporaryTests.vb
+++ b/src/EditorFeatures/VisualBasicTest/CodeActions/InlineTemporary/InlineTemporaryTests.vb
@@ -4397,6 +4397,29 @@ Class C
}
End Sub
End Class
+"
+ Await TestInRegularAndScriptAsync(code, expected, ignoreTrivia:=False)
+ End Function
+
+
+
+ Public Async Function TupleElementNameIsNotReplaced() As Task
+ ' The name of the named element has bad symbol info and gets replaced with (1 + 2)
+ Dim code = "
+Class C
+ Sub M()
+ Dim [||]i = 1 + 2
+ Dim t = (i, i:=3)
+ End Sub
+End Class
+"
+
+ Dim expected = "
+Class C
+ Sub M()
+ Dim t = (1 + 2, i:=3)
+ End Sub
+End Class
"
Await TestInRegularAndScriptAsync(code, expected, ignoreTrivia:=False)
End Function
diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/IntroduceVariable/IntroduceVariableTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/IntroduceVariable/IntroduceVariableTests.vb
index b3680cdeb1b2c..82c174427f336 100644
--- a/src/EditorFeatures/VisualBasicTest/CodeActions/IntroduceVariable/IntroduceVariableTests.vb
+++ b/src/EditorFeatures/VisualBasicTest/CodeActions/IntroduceVariable/IntroduceVariableTests.vb
@@ -28,8 +28,8 @@ Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
- Const {|Rename:V|} As Integer = 1 + 1
- Console.WriteLine(V)
+ Const {|Rename:Value|} As Integer = 1 + 1
+ Console.WriteLine(Value)
End Sub
End Module",
index:=2)
@@ -51,8 +51,8 @@ Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
- Const {|Rename:V|} As Integer = 1 + 1
- Console.WriteLine(V)
+ Const {|Rename:Value|} As Integer = 1 + 1
+ Console.WriteLine(Value)
End Sub
End Module",
index:=3)
@@ -826,9 +826,9 @@ End Class")
End Sub
End Class",
"Class Foo
- Private Const {|Rename:V|} As Integer = 42
+ Private Const {|Rename:X|} As Integer = 42
Sub New()
- MyClass.New(V)
+ MyClass.New(X)
End Sub
Sub New(x As Integer)
End Sub
@@ -1158,8 +1158,8 @@ Module Program
If True Then
If True Then
- Const {|Rename:V|} As Integer = 1
- Console.WriteLine(V)
+ Const {|Rename:Value|} As Integer = 1
+ Console.WriteLine(Value)
Else
Console.WriteLine(2)
End If
@@ -1198,8 +1198,8 @@ Module Program
If True Then
Console.WriteLine(1)
Else
- Const {|Rename:V|} As Integer = 2
- Console.WriteLine(V)
+ Const {|Rename:Value|} As Integer = 2
+ Console.WriteLine(Value)
End If
Else
Console.WriteLine(3)
@@ -1234,8 +1234,8 @@ Module Program
If True Then
If True Then Console.WriteLine(1) Else Console.WriteLine(2)
Else
- Const {|Rename:V|} As Integer = 3
- Console.WriteLine(V)
+ Const {|Rename:Value|} As Integer = 3
+ Console.WriteLine(Value)
End If
End Sub
End Module
@@ -1258,8 +1258,8 @@ End Module",
Module Program
Sub Main
Dim a = Sub(x As Integer)
- Dim {|Rename:v|} As Integer = x + 1
- Console.WriteLine(v) ' Introduce local
+ Dim {|Rename:value|} As Integer = x + 1
+ Console.WriteLine(value) ' Introduce local
End Sub
End Sub
End Module")
@@ -1280,8 +1280,8 @@ Module Program
Sub Main
Dim a = Sub(x As Integer)
If True Then
- Dim {|Rename:v|} As Integer = x + 1
- Console.WriteLine(v)
+ Dim {|Rename:value|} As Integer = x + 1
+ Console.WriteLine(value)
Else
Console.WriteLine()
End If
@@ -1307,8 +1307,8 @@ Module Program
If True Then
Console.WriteLine()
Else
- Dim {|Rename:v|} As Integer = x + 1
- Console.WriteLine(v)
+ Dim {|Rename:value|} As Integer = x + 1
+ Console.WriteLine(value)
End If
End Sub
End Sub
@@ -1329,8 +1329,8 @@ End Module",
Module Program
Sub Main
Dim a = Sub(x As Integer)
- Dim {|Rename:v|} As Integer = x + 1
- If True Then Console.WriteLine(v) Else Console.WriteLine(v)
+ Dim {|Rename:value|} As Integer = x + 1
+ If True Then Console.WriteLine(value) Else Console.WriteLine(value)
End Sub
End Sub
End Module",
@@ -1351,10 +1351,10 @@ End Module",
"Module Program
Sub Main(args As String())
Dim query = Sub(a)
- Dim {|Rename:v|} As Object = a Or a
+ Dim {|Rename:arg1|} As Object = a Or a
a = New With {Key .Key = Function(ByVal arg As Integer) As Integer
Return arg
- End Function}.Key.Invoke(v)
+ End Function}.Key.Invoke(arg1)
End Sub
End Sub
End Module")
@@ -2093,8 +2093,8 @@ End Class",
Class C
Private Shared Sub Main(args As String())
Dim hSet = New HashSet(Of String)()
- Dim {|Rename:v|} As String = hSet.ToString()
- hSet.Add(v)
+ Dim {|Rename:item|} As String = hSet.ToString()
+ hSet.Add(item)
End Sub
End Class")
End Function
@@ -2175,8 +2175,8 @@ Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
- Dim {|Rename:enumerable1|} As IEnumerable(Of Char) = From x In """"
- [Take](enumerable1)
+ Dim {|Rename:x1|} As IEnumerable(Of Char) = From x In """"
+ [Take](x1)
End Sub
Sub Take(x)
End Sub
@@ -2621,8 +2621,8 @@ Imports System
Namespace N
Class C
Public Sub M()
- Dim {|Rename:v|} As FormattableString = $""""
- Dim f = FormattableString.Invariant(v)
+ Dim {|Rename:formattable|} As FormattableString = $""""
+ Dim f = FormattableString.Invariant(formattable)
End Sub
End Class
End Namespace"
@@ -2889,5 +2889,58 @@ End Class
Await TestInRegularAndScriptAsync(code, expected, ignoreTrivia:=False)
End Function
+
+
+ Public Async Function TestPickNameBasedOnArgument1() As Task
+ Await TestInRegularAndScriptAsync(
+"class C
+ public sub new(a as string, b as string)
+ dim c = new TextSpan([|integer.Parse(a)|], integer.Parse(b))
+ end sub
+end class
+
+structure TextSpan
+ public sub new(start as integer, length as integer)
+ end sub
+end structure",
+"class C
+ public sub new(a as string, b as string)
+ Dim {|Rename:start|} As Integer = integer.Parse(a)
+ dim c = new TextSpan(start, integer.Parse(b))
+ end sub
+end class
+
+structure TextSpan
+ public sub new(start as integer, length as integer)
+ end sub
+end structure")
+ End Function
+
+
+
+ Public Async Function TestPickNameBasedOnArgument2() As Task
+ Await TestInRegularAndScriptAsync(
+"class C
+ public sub new(a as string, b as string)
+ dim c = new TextSpan(integer.Parse(a), [|integer.Parse(b)|])
+ end sub
+end class
+
+structure TextSpan
+ public sub new(start as integer, length as integer)
+ end sub
+end structure",
+"class C
+ public sub new(a as string, b as string)
+ Dim {|Rename:length|} As Integer = integer.Parse(b)
+ dim c = new TextSpan(integer.Parse(a), length)
+ end sub
+end class
+
+structure TextSpan
+ public sub new(start as integer, length as integer)
+ end sub
+end structure")
+ End Function
End Class
-End Namespace
+End Namespace
\ No newline at end of file
diff --git a/src/EditorFeatures/VisualBasicTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb b/src/EditorFeatures/VisualBasicTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb
index 7b5de5152a9cb..43dc0b88e8055 100644
--- a/src/EditorFeatures/VisualBasicTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb
+++ b/src/EditorFeatures/VisualBasicTest/CodeActions/ReplacePropertyWithMethods/ReplacePropertyWithMethodsTests.vb
@@ -415,7 +415,7 @@ end class",
end class")
End Function
-
+
Public Async Function TestDocumentationComment1() As Task
Await TestInRegularAndScriptAsync(
@@ -439,13 +439,13 @@ End Interface",
End Interface", ignoreTrivia:=False)
End Function
-
+
Public Async Function TestDocumentationComment2() As Task
Await TestInRegularAndScriptAsync(
"Interface ILanguageServiceHost
'''
- ''' Gets the active workspace project context that provides access to the language service for the active configured project.
+ ''' Sets the active workspace project context that provides access to the language service for the active configured project.
'''
'''
''' An that provides access to the language service for the active configured project.
@@ -454,22 +454,22 @@ End Interface", ignoreTrivia:=False)
End Interface",
"Interface ILanguageServiceHost
'''
- ''' Gets the active workspace project context that provides access to the language service for the active configured project.
+ ''' Sets the active workspace project context that provides access to the language service for the active configured project.
'''
- '''
+ '''
''' An that provides access to the language service for the active configured project.
- '''
+ '''
Sub SetActiveProjectContext(Value As Object)
End Interface", ignoreTrivia:=False)
End Function
-
+
Public Async Function TestDocumentationComment3() As Task
Await TestInRegularAndScriptAsync(
"Interface ILanguageServiceHost
'''
- ''' Gets the active workspace project context that provides access to the language service for the active configured project.
+ ''' Gets or sets the active workspace project context that provides access to the language service for the active configured project.
'''
'''
''' An that provides access to the language service for the active configured project.
@@ -478,14 +478,103 @@ End Interface", ignoreTrivia:=False)
End Interface",
"Interface ILanguageServiceHost
'''
- ''' Gets the active workspace project context that provides access to the language service for the active configured project.
+ ''' Gets or sets the active workspace project context that provides access to the language service for the active configured project.
'''
'''
''' An that provides access to the language service for the active configured project.
'''
Function GetActiveProjectContext() As Object
+ '''
+ ''' Gets or sets the active workspace project context that provides access to the language service for the active configured project.
+ '''
+ '''
+ ''' An that provides access to the language service for the active configured project.
+ '''
Sub SetActiveProjectContext(Value As Object)
End Interface", ignoreTrivia:=False)
End Function
+
+
+
+ Public Async Function TestDocumentationComment4() As Task
+ Await TestInRegularAndScriptAsync(
+"Interface ILanguageServiceHost
+ '''
+ ''' Sets .
+ '''
+ '''
+ WriteOnly Property [||]ActiveProjectContext As Object
+End Interface
+Structure AStruct
+ '''
+ Private X As Integer
+End Structure",
+"Interface ILanguageServiceHost
+ '''
+ ''' Sets .
+ '''
+ '''
+ Sub SetActiveProjectContext(Value As Object)
+End Interface
+Structure AStruct
+ '''
+ Private X As Integer
+End Structure", ignoreTrivia:=False)
+ End Function
+
+
+
+ Public Async Function TestDocumentationComment5() As Task
+ Await TestInRegularAndScriptAsync(
+"Interface ILanguageServiceHost
+ '''
+ ''' Gets or sets .
+ '''
+ '''
+ Property [||]ActiveProjectContext As Object
+End Interface
+Structure AStruct
+ '''
+ Private X As Integer
+End Structure",
+"Interface ILanguageServiceHost
+ '''
+ ''' Gets or sets .
+ '''
+ '''
+ Function GetActiveProjectContext() As Object
+ '''
+ ''' Gets or sets .
+ '''
+ '''
+ Sub SetActiveProjectContext(Value As Object)
+End Interface
+Structure AStruct
+ '''
+ Private X As Integer
+End Structure", ignoreTrivia:=False)
+ End Function
+
+
+
+ Public Async Function TestDocumentationComment6() As Task
+ Await TestInRegularAndScriptAsync(
+"Interface ISomeInterface(Of T)
+ '''
+ WriteOnly Property [||]Context As ISomeInterface(Of T)
+End Interface
+Structure AStruct
+ '''
+ Private X As Integer
+End Structure",
+"Interface ISomeInterface(Of T)
+ '''
+ Sub SetContext(Value As ISomeInterface(Of T))
+End Interface
+Structure AStruct
+ '''
+ Private X As Integer
+End Structure", ignoreTrivia:=False)
+ End Function
End Class
End Namespace
\ No newline at end of file
diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/AddImport/AddImportTests_NuGet.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/AddImport/AddImportTests_NuGet.vb
index 92d7484321008..fff18f70367c7 100644
--- a/src/EditorFeatures/VisualBasicTest/Diagnostics/AddImport/AddImportTests_NuGet.vb
+++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/AddImport/AddImportTests_NuGet.vb
@@ -44,7 +44,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImp
' Make a loose mock for the installer service. We don't care what this test
' calls on it.
Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Loose)
- installerServiceMock.SetupGet(Function(i) i.IsEnabled).Returns(True)
+ installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True)
installerServiceMock.SetupGet(Function(i) i.PackageSources).Returns(NugetPackageSources)
installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of CancellationToken))).
Returns(True)
@@ -71,7 +71,7 @@ End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packa
' Make a loose mock for the installer service. We don't care what this test
' calls on it.
Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Loose)
- installerServiceMock.SetupGet(Function(i) i.IsEnabled).Returns(True)
+ installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True)
installerServiceMock.SetupGet(Function(i) i.PackageSources).Returns(NugetPackageSources)
installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of CancellationToken))).
Returns(True)
@@ -98,7 +98,7 @@ End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packa
' Make a loose mock for the installer service. We don't care what this test
' calls on it.
Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Loose)
- installerServiceMock.SetupGet(Function(i) i.IsEnabled).Returns(True)
+ installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True)
installerServiceMock.SetupGet(Function(i) i.PackageSources).Returns(NugetPackageSources)
installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of CancellationToken))).
Returns(False)
@@ -123,7 +123,7 @@ End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packa
' Make a loose mock for the installer service. We don't care what this test
' calls on it.
Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Loose)
- installerServiceMock.SetupGet(Function(i) i.IsEnabled).Returns(True)
+ installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True)
installerServiceMock.SetupGet(Function(i) i.PackageSources).Returns(NugetPackageSources)
installerServiceMock.Setup(Function(s) s.IsInstalled(It.IsAny(Of Workspace)(), It.IsAny(Of ProjectId)(), "NuGetPackage")).
Returns(True)
@@ -145,7 +145,7 @@ New TestParameters(fixProviderData:=New ProviderData(installerServiceMock.Object
' Make a loose mock for the installer service. We don't care what this test
' calls on it.
Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Loose)
- installerServiceMock.SetupGet(Function(i) i.IsEnabled).Returns(True)
+ installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True)
installerServiceMock.SetupGet(Function(i) i.PackageSources).Returns(NugetPackageSources)
installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")).
Returns(ImmutableArray.Create("1.0", "2.0"))
@@ -185,7 +185,7 @@ parameters:=New TestParameters(fixProviderData:=data))
Public Async Function TestInstallGetsCalledNoVersion() As Task
Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Loose)
- installerServiceMock.SetupGet(Function(i) i.IsEnabled).Returns(True)
+ installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True)
installerServiceMock.SetupGet(Function(i) i.PackageSources).Returns(NugetPackageSources)
installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", Nothing, It.IsAny(Of Boolean), It.IsAny(Of CancellationToken))).
Returns(True)
@@ -211,7 +211,7 @@ End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packa