提交 2763f99b 编写于 作者: C CyrusNajmabadi 提交者: GitHub

Merge pull request #15396 from CyrusNajmabadi/generateMembersOrdering

Don't attempt to keep members sorted by name.
......@@ -275,10 +275,10 @@
<Compile Include="Diagnostics\GenerateType\GenerateTypeTests_Dialog.cs" />
<Compile Include="Diagnostics\GenerateVariable\GenerateVariableTests.cs" />
<Compile Include="Diagnostics\HideBase\HideBaseTests.cs" />
<Compile Include="Diagnostics\ImplementAbstractClass\ImplementAbstractClassTests.cs" />
<Compile Include="Diagnostics\ImplementAbstractClass\ImplementAbstractClassTests_FixAllTests.cs" />
<Compile Include="Diagnostics\ImplementInterface\ImplementInterfaceTests_FixAllTests.cs" />
<Compile Include="Diagnostics\ImplementInterface\ImplementInterfaceTests.cs" />
<Compile Include="ImplementAbstractClass\ImplementAbstractClassTests.cs" />
<Compile Include="ImplementAbstractClass\ImplementAbstractClassTests_FixAllTests.cs" />
<Compile Include="ImplementInterface\ImplementInterfaceTests_FixAllTests.cs" />
<Compile Include="ImplementInterface\ImplementInterfaceTests.cs" />
<Compile Include="Diagnostics\Iterator\AddYieldTests.cs" />
<Compile Include="Diagnostics\Iterator\ChangeToIEnumerableTests.cs" />
<Compile Include="Diagnostics\MockDiagnosticAnalyzerTests.cs" />
......
......@@ -112,14 +112,14 @@ class Z
int a;
string b;
public Z(string b)
public Z(int a)
{
this.b = b;
this.a = a;
}
public Z(int a)
public Z(string b)
{
this.a = a;
this.b = b;
}
}",
index: 0);
......
......@@ -1283,9 +1283,9 @@ void M()
class Delta
{
private bool v;
private string v1;
private int v2;
private bool v;
public Delta(string v1, int v2)
{
......@@ -1447,9 +1447,9 @@ void M()
class Delta
{
private bool v;
private string v1;
private int v2;
private bool v;
public Delta(string v1, int v2)
{
......@@ -1666,17 +1666,17 @@ void Main()
struct Apartment
{
private string v;
private int v1;
private string v;
public Apartment(string v) : this()
public Apartment(int v1)
{
this.v = v;
this.v1 = v1;
}
public Apartment(int v1)
public Apartment(string v) : this()
{
this.v1 = v1;
this.v = v;
}
}");
}
......@@ -1765,13 +1765,13 @@ class D
private int u;
private D v;
public D(D v)
public D(int u)
{
this.v = v;
}
public D(int u)
public D(D v)
{
this.v = v;
}
}");
}
......@@ -1871,9 +1871,9 @@ class D
[AttributeUsage(AttributeTargets.Class)]
class MyAttribute : Attribute
{
private string topic;
private bool v1;
private int v2;
private string topic;
public MyAttribute(bool v1, int v2, string topic)
{
......@@ -1968,14 +1968,14 @@ class MyAttribute : Attribute
private int v;
private bool v1;
public MyAttribute(bool v1)
public MyAttribute(int v)
{
this.v1 = v1;
this.v = v;
}
public MyAttribute(int v)
public MyAttribute(bool v1)
{
this.v = v;
this.v1 = v1;
}
}
......@@ -2014,22 +2014,22 @@ class D
[AttributeUsage(AttributeTargets.Class)]
class MyAttrAttribute : Attribute
{
private int v;
private bool v1;
private int v2;
private int v;
private bool v3;
public MyAttrAttribute(int v, bool v3)
{
this.v = v;
this.v3 = v3;
}
public MyAttrAttribute(bool v1, int v2)
{
this.v1 = v1;
this.v2 = v2;
}
public MyAttrAttribute(int v, bool v3)
{
this.v = v;
this.v3 = v3;
}
}
[MyAttrAttribute(1, true)]
......@@ -2069,9 +2069,8 @@ enum A
[AttributeUsage(AttributeTargets.Class)]
class MyAttrAttribute : Attribute
{
private A a1;
private int[] v1;
private string v10;
private A a1;
private bool v2;
private byte v3;
private char v4;
......@@ -2080,6 +2079,7 @@ class MyAttrAttribute : Attribute
private long v7;
private double v8;
private float v9;
private string v10;
public MyAttrAttribute(int[] v1, A a1, bool v2, byte v3, char v4, short v5, int v6, long v7, double v8, float v9, string v10)
{
......
......@@ -515,13 +515,13 @@ public ExType()
{
}
public ExType(string message) : base(message)
public ExType(int v)
{
this.v = v;
}
public ExType(int v)
public ExType(string message) : base(message)
{
this.v = v;
}
public ExType(string message, Exception innerException) : base(message, innerException)
......@@ -4397,7 +4397,7 @@ class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = ""John"",Age = DateTime.Today};
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = ""John"", Age = DateTime.Today};
}
}";
......@@ -4407,7 +4407,7 @@ class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = ""John"",Age = DateTime.Today};
var c = new Customer(x: 1, y: ""Hello"") {Name = ""John"", Age = DateTime.Today};
}
}
......@@ -4422,8 +4422,8 @@ public Customer(int x, string y)
this.y = y;
}
public DateTime Age { get; set; }
public string Name { get; set; }
public DateTime Age { get; set; }
}";
await TestAsync(code, expected, index: 1);
......@@ -4439,7 +4439,7 @@ class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = null,Age = DateTime.Today};
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = null, Age = DateTime.Today};
}
}";
......@@ -4449,7 +4449,7 @@ class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = null,Age = DateTime.Today};
var c = new Customer(x: 1, y: ""Hello"") {Name = null, Age = DateTime.Today};
}
}
......@@ -4464,8 +4464,8 @@ public Customer(int x, string y)
this.y = y;
}
public DateTime Age { get; set; }
public object Name { get; set; }
public DateTime Age { get; set; }
}";
await TestAsync(code, expected, index: 1);
......@@ -4481,7 +4481,7 @@ class Program
{
static void Main(string[] args)
{
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = Foo,Age = DateTime.Today};
var c = new [|Customer|](x: 1, y: ""Hello"") {Name = Foo, Age = DateTime.Today};
}
}";
......@@ -4491,7 +4491,7 @@ class Program
{
static void Main(string[] args)
{
var c = new Customer(x: 1, y: ""Hello"") {Name = Foo,Age = DateTime.Today};
var c = new Customer(x: 1, y: ""Hello"") {Name = Foo, Age = DateTime.Today};
}
}
......@@ -4506,8 +4506,8 @@ public Customer(int x, string y)
this.y = y;
}
public DateTime Age { get; set; }
public object Name { get; set; }
public DateTime Age { get; set; }
}";
await TestAsync(code, expected, index: 1);
......@@ -4523,7 +4523,7 @@ class Program
{
static void Main(string[] args)
{
var c = new [|Customer|] {Name = ""John"",Age = DateTime.Today};
var c = new [|Customer|] {Name = ""John"", Age = DateTime.Today};
}
}";
......@@ -4533,14 +4533,14 @@ class Program
{
static void Main(string[] args)
{
var c = new Customer {Name = ""John"",Age = DateTime.Today};
var c = new Customer {Name = ""John"", Age = DateTime.Today};
}
}
internal class Customer
{
public DateTime Age { get; set; }
public string Name { get; set; }
public DateTime Age { get; set; }
}";
await TestAsync(code, expected, index: 1);
......
......@@ -965,8 +965,8 @@ void Method()
}",
@"class Class
{
private object foo;
int i;
private object foo;
void Method()
{
......@@ -2419,8 +2419,8 @@ static void Main(string[] args)
}",
@"class Program
{
private static int A;
private static int P;
private static int A;
static void Main(string[] args)
{
......@@ -2449,8 +2449,8 @@ static void Main(string[] args)
}",
@"class Program
{
public static int A { get; private set; }
public static int P { get; private set; }
public static int A { get; private set; }
static void Main(string[] args)
{
......@@ -2506,7 +2506,12 @@ public async Task TestGeneratePropertyInScript()
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)]
public async Task TestConstantInParameterValue()
{
const string Initial = @"class C { const int y = 1 ; public void Foo ( bool x = [|undeclared|] ) { } } ";
const string Initial =
@"class C
{
const int y = 1 ;
public void Foo ( bool x = [|undeclared|] ) { }
} ";
await TestActionCountAsync(
Initial,
......@@ -2516,8 +2521,8 @@ public async Task TestConstantInParameterValue()
Initial,
@"class C
{
private const bool undeclared;
const int y = 1;
private const bool undeclared;
public void Foo(bool x = undeclared)
{
......@@ -6279,9 +6284,9 @@ public async Task TestGeneratePropertyInExpressionBodyMember()
}",
@"class Program
{
public int y { get; private set; }
public int Y => y;
public int y { get; private set; }
}",
index: 2);
}
......
......@@ -545,12 +545,12 @@ abstract class MyClass$$
var expectedInterfaceCode = @"interface IMyClass
{
int ExtractableProp { get; set; }
int ExtractableProp_GetInternal { set; }
int ExtractableProp_GetOnly { get; }
int ExtractableProp_GetPrivate { set; }
int ExtractableProp_SetInternal { get; }
int ExtractableProp_SetOnly { set; }
int ExtractableProp_SetPrivate { get; }
int ExtractableProp_GetPrivate { set; }
int ExtractableProp_SetInternal { get; }
int ExtractableProp_GetInternal { set; }
int NotActuallyUnsafeProp { get; set; }
unsafe int* UnsafeProp { get; set; }
}";
......@@ -574,9 +574,9 @@ abstract class MyClass$$
var expectedInterfaceCode = @"interface IMyClass
{
int this[double x] { get; set; }
int this[string x] { get; }
int this[int x] { set; }
int this[string x] { get; }
int this[double x] { get; set; }
int this[int? x, string y = ""42""] { get; set; }
}";
......
......@@ -3,25 +3,25 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.ImplementAbstractClass;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.ImplementAbstractClass
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass
{
public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
null, new ImplementAbstractClassCodeFixProvider());
}
=> new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
null, new CSharpImplementAbstractClassCodeFixProvider());
private static readonly Dictionary<OptionKey, object> AllOptionsOff =
new Dictionary<OptionKey, object>
{
......@@ -1035,7 +1035,7 @@ public override int[] Eras
}
}
internal override EraInfo[] CalEraInfo
internal override int MinCalendarYear
{
get
{
......@@ -1051,7 +1051,7 @@ internal override int MaxCalendarYear
}
}
internal override DateTime MaxDate
internal override EraInfo[] CalEraInfo
{
get
{
......@@ -1059,7 +1059,7 @@ internal override DateTime MaxDate
}
}
internal override int MinCalendarYear
internal override DateTime MinDate
{
get
{
......@@ -1067,7 +1067,7 @@ internal override int MinCalendarYear
}
}
internal override DateTime MinDate
internal override DateTime MaxDate
{
get
{
......@@ -1488,5 +1488,34 @@ public override int M
}
}", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.TrueWithNoneEnforcement));
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)]
public async Task TestWithGroupingOff1()
{
await TestAsync(
@"abstract class Base
{
public abstract int Prop { get; }
}
class [|Derived|] : Base
{
void Foo() { }
}",
@"using System;
abstract class Base
{
public abstract int Prop { get; }
}
class Derived : Base
{
void Foo() { }
public override int Prop => throw new NotImplementedException();
}", options: Option(ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd));
}
}
}
\ No newline at end of file
// 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.Tasks;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.ImplementAbstractClass;
using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.ImplementAbstractClass
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass
{
public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
public partial class ImplementAbstractClassTests
{
#region "Fix all occurrences tests"
......@@ -16,7 +16,7 @@ public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProvi
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument()
{
var fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var fixAllActionId = CSharpImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var input = @"
<Workspace>
......@@ -121,7 +121,7 @@ class C3 : A1, I1
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProject()
{
var fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var fixAllActionId = CSharpImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var input = @"
<Workspace>
......@@ -237,7 +237,7 @@ class C3 : A1, I1
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution()
{
var fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var fixAllActionId = CSharpImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var input = @"
<Workspace>
......@@ -366,7 +366,7 @@ public override void F1()
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_DifferentAssemblyWithSameTypeName()
{
var fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var fixAllActionId = CSharpImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "global::A1");
var input = @"
<Workspace>
......
......@@ -6,22 +6,22 @@
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.ImplementInterface;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.ImplementInterface;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.ImplementInterface
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface
{
public partial class ImplementInterfaceTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, CodeFixProvider>(null, new ImplementInterfaceCodeFixProvider());
}
=> new Tuple<DiagnosticAnalyzer, CodeFixProvider>(null, new CSharpImplementInterfaceCodeFixProvider());
private static readonly Dictionary<OptionKey, object> AllOptionsOff =
new Dictionary<OptionKey, object>
......@@ -541,13 +541,13 @@ interface IInterface1
class Class : IInterface1
{
public void Method1(int i)
public void Method1(string i)
{
throw new NotImplementedException();
}
public void Method1(string i)
public void Method1(int i)
{
throw new NotImplementedException();
}
}");
}
......@@ -930,6 +930,8 @@ interface I1
class Test : I1
{
int Prop { get; set; }
int I1.Prop
{
get
......@@ -942,8 +944,6 @@ int I1.Prop
throw new NotImplementedException();
}
}
int Prop { get; set; }
}
interface I1
......@@ -1057,12 +1057,12 @@ interface @IInterface
class Class : @IInterface
{
string M();
void IInterface.M()
{
throw new NotImplementedException();
}
string M();
}");
}
......@@ -1089,12 +1089,12 @@ interface @IInterface
class Class : @IInterface
{
string M();
void IInterface.M()
{
throw new NotImplementedException();
}
string M();
}");
}
......@@ -1121,12 +1121,12 @@ interface @int
class Class : @int
{
string M();
void @int.M()
{
throw new NotImplementedException();
}
string M();
}");
}
......@@ -1153,12 +1153,12 @@ interface @int
class Class : @int
{
string @bool();
void @int.@bool()
{
throw new NotImplementedException();
}
string @bool();
}");
}
......@@ -6107,13 +6107,13 @@ public void Dispose(bool flag)
class Program : IDisposable
{
public void Dispose()
public void Dispose(bool flag)
{
throw new NotImplementedException();
}
public void Dispose(bool flag)
public void Dispose()
{
throw new NotImplementedException();
}
}", index: 0);
}
......@@ -6690,5 +6690,35 @@ class Class : IInterface<(int, string), int>
}",
parseOptions: TestOptions.Regular, withScriptOption: true);
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithGroupingOff1()
{
await TestAsync(
@"interface IInterface
{
int Prop { get; }
}
class Class : [|IInterface|]
{
void M() { }
}",
@"using System;
interface IInterface
{
int Prop { get; }
}
class Class : IInterface
{
void M() { }
public int Prop => throw new NotImplementedException();
}", options: Option(ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd));
}
}
}
......@@ -5,9 +5,9 @@
using Xunit;
using ImplementInterfaceCodeAction = Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService.ImplementInterfaceCodeAction;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.ImplementInterface
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface
{
public partial class ImplementInterfaceTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
public partial class ImplementInterfaceTests
{
#region "Fix all occurrences tests"
......@@ -503,4 +503,4 @@ class C3 : I1, I2
#endregion
}
}
}
\ No newline at end of file
// 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.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
......@@ -142,9 +136,9 @@ public class C
{
public const string FConst;
public static string FStatic;
public string FAccessE;
public string FNotConst;
public string FNotStatic;
public string FNotConst;
public string FAccessE;
protected string FAccessC;
protected internal string FAccessD;
internal string FAccessB;
......@@ -162,16 +156,16 @@ public class C
public int this[int index1, int index2] { get; }
public static int PStatic { get; }
public int PAccessE { get; }
public int PNotStatic { get; }
public int PAccessE { get; }
protected int PAccessD { get; }
protected internal int PAccessC { get; }
internal int PAccessB { get; }
private int PAccessA { get; }
public static event Action EFStatic;
public event Action EFAccessE;
public event Action EFNotStatic;
public event Action EFAccessE;
protected event Action EFAccessC;
protected internal event Action EFAccessD;
internal event Action EFAccessB;
......@@ -180,14 +174,14 @@ public class C
public static int M2Static();
public static void MStatic();
public int M2AccessE();
public int M2Generic<T>();
public int M2Generic<T>(int param);
public int M2Generic<T1, T2>();
public int M2Generic<T>(int param);
public int M2Generic<T>();
public int M2NotStatic();
public void MAccessE();
public void MGeneric<T>();
public void MGeneric<T>(int param);
public void MGeneric<T1, T2>();
public void MGeneric<T>(int param);
public void MGeneric<T>();
public void MNotStatic();
protected int M2AccessD();
protected void MAccessD();
......@@ -201,48 +195,146 @@ public class C
public static C operator +(C c);
public static C operator !(C c);
public enum EAccessE { }
public enum ENameA { }
public enum ENameB { }
protected enum EAccessD { }
protected internal enum EAccessC { }
internal enum EAccessB { }
private enum EAccessA { }
public enum EAccessE
{
}
public interface IAccessE { }
public interface IGeneric<T> { }
public interface IGeneric<T1, T2> { }
protected interface IAccessD { }
protected internal interface IAccessC { }
internal interface IAccessB { }
private interface IAccessA { }
public enum ENameB
{
}
public struct SAccessE { }
public struct SGeneric<T> { }
public struct SGeneric<T1, T2> { }
public struct SNameA { }
public struct SNameB { }
protected struct SAccessD { }
protected internal struct SAccessC { }
internal struct SAccessB { }
private struct SAccessA { }
public enum ENameA
{
}
public static class CStatic { }
public class CAccessE { }
public class CGeneric<T> { }
public class CGeneric<T1, T2> { }
public class CNotStatic { }
protected class CAccessD { }
protected internal class CAccessC { }
internal class CAccessB { }
private class CAccessA { }
protected enum EAccessD
{
}
protected internal enum EAccessC
{
}
internal enum EAccessB
{
}
private enum EAccessA
{
}
public interface IAccessE
{
}
public interface IGeneric<T1, T2>
{
}
public interface IGeneric<T>
{
}
protected interface IAccessD
{
}
protected internal interface IAccessC
{
}
internal interface IAccessB
{
}
private interface IAccessA
{
}
public struct SAccessE
{
}
public struct SGeneric<T1, T2>
{
}
public struct SGeneric<T>
{
}
public struct SNameB
{
}
public struct SNameA
{
}
protected struct SAccessD
{
}
protected internal struct SAccessC
{
}
internal struct SAccessB
{
}
private struct SAccessA
{
}
public static class CStatic
{
}
public class CNotStatic
{
}
public class CAccessE
{
}
public class CGeneric<T1, T2>
{
}
public class CGeneric<T>
{
}
protected class CAccessD
{
}
protected internal class CAccessC
{
}
internal class CAccessB
{
}
private class CAccessA
{
}
public delegate void DAccessE();
public delegate void DGeneric<T>(T t, int i);
public delegate void DGeneric<T1, T2>(T1 a, T2 b);
public delegate void DGeneric<T>(T t, int i);
protected delegate void DAccessD();
protected internal delegate void DAccessC();
internal delegate void DAccessB();
private delegate void DAccessA();
}
}";
......@@ -256,14 +348,13 @@ Namespace N
Public Class C
Public Const FConst As String
Public Shared FStatic As String
Public FAccessE As String
Public FNotConst As String
Public FNotStatic As String
Public FNotConst As String
Public FAccessE As String
Protected FAccessC As String
Protected Friend FAccessD As String
Friend FAccessB As String
Private FAccessA As String
Public Sub New()
Public Sub New(a As Integer)
Public Sub New(a As Integer, b As Integer)
......@@ -271,121 +362,144 @@ Namespace N
Protected Friend Sub New(s As Short)
Friend Sub New(l As Long)
Private Sub New(s As String)
Public Shared ReadOnly Property PStatic As Integer
Public ReadOnly Property PAccessE As Integer
Public ReadOnly Property PNotStatic As Integer
Default Public ReadOnly Property this[](index As Integer) As Integer
Public ReadOnly Property PAccessE As Integer
Default Public ReadOnly Property this[](index1 As Integer, index2 As Integer) As Integer
Default Public ReadOnly Property this[](index As Integer) As Integer
Protected ReadOnly Property PAccessD As Integer
Protected Friend ReadOnly Property PAccessC As Integer
Friend ReadOnly Property PAccessB As Integer
Private ReadOnly Property PAccessA As Integer
Public Shared Event EFStatic As Action
Public Event EFAccessE As Action
Public Event EFNotStatic As Action
Public Event EFAccessE As Action
Protected Event EFAccessC As Action
Protected Friend Event EFAccessD As Action
Friend Event EFAccessB As Action
Private Event EFAccessA As Action
Public Shared Sub MStatic()
Public Sub MNotStatic()
Public Sub MAccessE()
Public Sub MGeneric(Of T)()
Public Sub MGeneric(Of T)(param As Integer)
Public Sub MGeneric(Of T1, T2)()
Public Sub MNotStatic()
Public Sub MGeneric(Of T)(param As Integer)
Public Sub MGeneric(Of T)()
Protected Sub MAccessD()
Protected Friend Sub MAccessC()
Friend Sub MAccessB()
Private Sub MAccessA()
Public Shared Function M2Static() As Integer
Public Function M2NotStatic() As Integer
Public Function M2AccessE() As Integer
Public Function M2Generic(Of T)() As Integer
Public Function M2Generic(Of T)(param As Integer) As Integer
Public Function M2Generic(Of T1, T2)() As Integer
Public Function M2NotStatic() As Integer
Public Function M2Generic(Of T)(param As Integer) As Integer
Public Function M2Generic(Of T)() As Integer
Protected Function M2AccessD() As Integer
Protected Friend Function M2AccessC() As Integer
Friend Function M2AccessB() As Integer
Private Function M2AccessA() As Integer
Public Shared Operator +(c As C) As C
Public Shared Operator Not(c As C) As C
Public Enum EAccessE
End Enum
Public Enum ENameA
End Enum
Public Enum ENameB
End Enum
Public Enum ENameA
End Enum
Protected Enum EAccessD
End Enum
Protected Friend Enum EAccessC
End Enum
Friend Enum EAccessB
End Enum
Private Enum EAccessA
End Enum
Public Interface IAccessE
End Interface
Public Interface IGeneric(Of T)
End Interface
Public Interface IGeneric(Of T1, T2)
End Interface
Public Interface IGeneric(Of T)
End Interface
Protected Interface IAccessD
End Interface
Protected Friend Interface IAccessC
End Interface
Friend Interface IAccessB
End Interface
Private Interface IAccessA
End Interface
Public Structure SAccessE
End Structure
Public Structure SGeneric(Of T)
End Structure
Public Structure SGeneric(Of T1, T2)
End Structure
Public Structure SNameA
Public Structure SGeneric(Of T)
End Structure
Public Structure SNameB
End Structure
Public Structure SNameA
End Structure
Protected Structure SAccessD
End Structure
Protected Friend Structure SAccessC
End Structure
Friend Structure SAccessB
End Structure
Private Structure SAccessA
End Structure
Public Class CAccessE
Public Class CNotStatic
End Class
Public Class CGeneric(Of T)
Public Class CStatic
End Class
Public Class CGeneric(Of T1, T2)
Public Class CAccessE
End Class
Public Class CNotStatic
Public Class CGeneric(Of T1, T2)
End Class
Public Class CStatic
Public Class CGeneric(Of T)
End Class
Protected Class CAccessD
End Class
Protected Friend Class CAccessC
End Class
Friend Class CAccessB
End Class
Private Class CAccessA
End Class
Public Delegate Sub DAccessE()
Public Delegate Sub DGeneric(Of T)(t As T, i As Integer)
Public Delegate Sub DGeneric(Of T1, T2)(a As T1, b As T2)
Public Delegate Sub DGeneric(Of T)(t As T, i As Integer)
Protected Delegate Sub DAccessD()
Protected Friend Delegate Sub DAccessC()
Friend Delegate Sub DAccessB()
......@@ -594,12 +708,11 @@ public class C
var initialVB = "Namespace [|N|] End Namespace";
var expectedVB = @"
Namespace N
Namespace N
Namespace N
Public Class A
Public Class A
Public Shared MustOverride ReadOnly Property Property1 As String
Public Overridable ReadOnly Property [Property] As String
Public MustOverride Shared Sub Method2()
Public Overridable Sub Method1()
End Class
......@@ -615,4 +728,4 @@ End Namespace
}
}
}
}
}
\ No newline at end of file
......@@ -908,15 +908,21 @@ public void Dispose()
if (!_ignoreResult)
{
this.Document = this.Result;
if (_compareTokens)
{
var actual = string.Join(" ", Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result.GetSyntaxRootAsync().Result.DescendantTokens());
var reduced = Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result;
var formatted = Formatter.FormatAsync(reduced).Result.GetSyntaxRootAsync().Result;
var root = reduced.GetSyntaxRootAsync().Result;
var actual = string.Join(" ", root.DescendantTokens());
TokenUtilities.AssertTokensEqual(_expected, actual, _language);
}
else
{
var actual = Formatter.FormatAsync(Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result, Formatter.Annotation).Result
.GetSyntaxRootAsync().Result.ToFullString();
Assert.Equal(_expected, actual);
}
}
......
......@@ -38,6 +38,7 @@ public async Task BracketedIdentifierSimplificationTest()
var expected = $@"#Region ""{FeaturesResources.Assembly} mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""
' mscorlib.v4_0_30319_17626.dll
#End Region
Imports System.Runtime
Imports System.Runtime.InteropServices
......@@ -52,10 +53,11 @@ Inherits Attribute
Public Sub New(message As String)
<__DynamicallyInvokableAttribute> <TargetedPatchingOptOut(""Performance critical to inline this type of method across NGen image boundaries"")>
Public Sub New(message As String, [error] As Boolean)
<__DynamicallyInvokableAttribute>
Public ReadOnly Property IsError As Boolean
<__DynamicallyInvokableAttribute>
Public ReadOnly Property Message As String
<__DynamicallyInvokableAttribute>
Public ReadOnly Property IsError As Boolean
End Class
End Namespace";
......
......@@ -912,37 +912,40 @@ public class [|C|]
#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null""
' {CodeAnalysisResources.InMemoryAssembly}
#End Region
Imports System
Imports System.Reflection
Imports System.Runtime.CompilerServices
<DefaultMember(""Item"")>
<Obsolete>
<DefaultMember(""Item"")> <Obsolete>
Public Class [|C|]
<Obsolete>
<ThreadStatic>
<Obsolete> <ThreadStatic>
Public field1 As Integer
<Obsolete>
Public Sub New()
<Obsolete>
Default Public Property Item(x As Integer) As Integer
<Obsolete>
Public Property prop1 As Integer
<Obsolete>
Public Property prop2 As Integer
<Obsolete>
Default Public Property Item(x As Integer) As Integer
<Obsolete>
Public Event event1 As Action
<Obsolete>
Public Event event2 As Action
<Obsolete>
Public Sub method1()
Public Sub method2(<CallerMemberName> Optional name As String = """")
<Obsolete>
Protected Overrides Sub Finalize()
<Obsolete>
Public Shared Operator +(c1 As C, c2 As C) As C
End Class
";
End Class";
await GenerateAndVerifySourceAsync(metadataSource, symbolName, LanguageNames.VisualBasic, expectedVB);
}
......@@ -1020,9 +1023,9 @@ Imports System.Runtime.CompilerServices
Public Sub New()
Default Public Property Item(x As Integer) As Integer
Public Property prop1 As Integer
Public Property prop2 As Integer
Default Public Property Item(x As Integer) As Integer
Public Event event1 As Action
Public Event event2 As Action
......
......@@ -3,6 +3,7 @@
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.ImplementInterface
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.ImplementInterface
......@@ -15,7 +16,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.ImplementInterface
Else
Return Tuple.Create(Of DiagnosticAnalyzer, CodeFixProvider)(
Nothing,
New CodeAnalysis.VisualBasic.CodeFixes.ImplementInterface.ImplementInterfaceCodeFixProvider())
New VisualBasicImplementInterfaceCodeFixProvider())
End If
End Function
......
......@@ -537,6 +537,9 @@ protected static IList<CodeAction> FlattenActions(IEnumerable<CodeAction> codeAc
protected (OptionKey, object) SingleOption(Option<bool> option, bool enabled)
=> (new OptionKey(option), enabled);
protected (OptionKey, object) SingleOption<T>(PerLanguageOption<T> option, T value)
=> (new OptionKey(option, this.GetLanguage()), value);
protected (OptionKey, object) SingleOption(Option<CodeStyleOption<bool>> option, bool enabled, NotificationOption notification)
=> SingleOption(option, new CodeStyleOption<bool>(enabled, notification));
......@@ -561,6 +564,9 @@ protected static (OptionKey, object) SingleOption(PerLanguageOption<CodeStyleOpt
protected IDictionary<OptionKey, object> Option(PerLanguageOption<CodeStyleOption<bool>> option, bool enabled, NotificationOption notification)
=> OptionsSet(SingleOption(option, enabled, notification));
protected IDictionary<OptionKey, object> Option<T>(PerLanguageOption<T> option, T value)
=> OptionsSet(SingleOption(option, value));
protected IDictionary<OptionKey, object> Option(PerLanguageOption<CodeStyleOption<bool>> option, CodeStyleOption<bool> codeStyle)
=> OptionsSet(SingleOption(option, codeStyle));
......
......@@ -205,8 +205,8 @@
<Compile Include="CodeLens\VisualBasicCodeLensTests.vb" />
<Compile Include="Completion\CompletionServiceTests.vb" />
<Compile Include="Diagnostics\AddImport\AddImportTests_NuGet.vb" />
<Compile Include="Diagnostics\ImplementAbstractClass\ImplementAbstractClassTests_FixAllTests.vb" />
<Compile Include="Diagnostics\ImplementInterface\ImplementInterfaceTests_FixAllTests.vb" />
<Compile Include="ImplementAbstractClass\ImplementAbstractClassTests_FixAllTests.vb" />
<Compile Include="ImplementInterface\ImplementInterfaceTests_FixAllTests.vb" />
<Compile Include="Diagnostics\Iterator\IteratorTests.vb" />
<Compile Include="CommentSelection\VisualBasicCommentSelectionTests.vb" />
<Compile Include="Completion\CompletionProviders\AbstractContextTests.vb" />
......@@ -245,10 +245,10 @@
<Compile Include="Diagnostics\GenerateType\GenerateTypeTests.vb" />
<Compile Include="Diagnostics\GenerateType\GenerateTypeTests_Dialog.vb" />
<Compile Include="Diagnostics\GenerateVariable\GenerateVariableTests.vb" />
<Compile Include="Diagnostics\ImplementAbstractClass\ImplementAbstractClassCommandHandlerTests.vb" />
<Compile Include="Diagnostics\ImplementAbstractClass\ImplementAbstractClassTests.vb" />
<Compile Include="Diagnostics\ImplementInterface\ImplementInterfaceCommandHandlerTests.vb" />
<Compile Include="Diagnostics\ImplementInterface\ImplementInterfaceTests.vb" />
<Compile Include="ImplementAbstractClass\ImplementAbstractClassCommandHandlerTests.vb" />
<Compile Include="ImplementAbstractClass\ImplementAbstractClassTests.vb" />
<Compile Include="ImplementInterface\ImplementInterfaceCommandHandlerTests.vb" />
<Compile Include="ImplementInterface\ImplementInterfaceTests.vb" />
<Compile Include="Diagnostics\InsertMissingCast\InsertMissingCastTests.vb" />
<Compile Include="Diagnostics\MakeMethodSynchronous\MakeMethodSynchronousTests.vb" />
<Compile Include="Diagnostics\MoveToTopOfFile\MoveToTopOfFileTests.vb" />
......
......@@ -618,12 +618,14 @@ End Module
Class C
Public v1 As Integer
Private i As Char
Public Sub New(v1 As Integer)
Me.v1 = v1
End Sub
Public Sub New(i As Char)
Me.i = i
End Sub Public Sub New(v1 As Integer)
Me.v1 = v1
End Sub
End Class")
End Function
......@@ -921,12 +923,12 @@ End Class")
End Class",
"Class C
Private v As Integer
Public Sub New(v As Integer)
Me.v = v
End Sub
Sub New
Me.New(1)
End Sub
Public Sub New(v As Integer)
Me.v = v
End Sub
End Class")
End Function
......@@ -956,12 +958,12 @@ End Class")
End Class",
"Class C
Private v As Integer
Public Sub New(v As Integer)
Me.v = v
End Sub
Sub New
MyClass.New(1)
End Sub
Public Sub New(v As Integer)
Me.v = v
End Sub
End Class")
End Function
......@@ -1045,8 +1047,9 @@ End Class",
End Class
Class C
Inherits B
Private u1 As Integer
Private x As String
Private u1 As Integer
Public Sub New(u As Integer)
u1 = u
End Sub
......@@ -1258,9 +1261,11 @@ End Class",
"<AttributeUsage(AttributeTargets.Class)>
Public Class MyAttribute
Inherits System.Attribute
Private Topic As String
Private v1 As Boolean
Private v2 As Integer
Private Topic As String
Public Sub New(v1 As Boolean, v2 As Integer, Topic As String)
Me.v1 = v1
Me.v2 = v2
......@@ -1324,9 +1329,8 @@ End Enum
<AttributeUsage(AttributeTargets.Class)>
Public Class MyAttribute
Inherits System.Attribute
Private a1 As A
Private v1 As Short()
Private v10 As String
Private a1 As A
Private v2 As Boolean
Private v3 As Integer
Private v4 As Char
......@@ -1335,6 +1339,7 @@ Public Class MyAttribute
Private v7 As Long
Private v8 As Double
Private v9 As Single
Private v10 As String
Public Sub New(v1() As Short, a1 As A, v2 As Boolean, v3 As Integer, v4 As Char, v5 As Short, v6 As Integer, v7 As Long, v8 As Double, v9 As Single, v10 As String)
Me.v1 = v1
Me.a1 = a1
......@@ -1427,12 +1432,12 @@ Module Module1
Class Classic
Private int As Integer
Private obj As Object
Public Sub New(obj As Object)
Me.obj = obj
End Sub
Public Sub New(int As Integer)
Me.int = int
End Sub
Public Sub New(obj As Object)
Me.obj = obj
End Sub
End Class
End Module")
End Function
......
......@@ -237,8 +237,8 @@ Public Class Test
End Sub
End Class",
"Class EventClass
Public Event XEvent()
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
......@@ -266,8 +266,8 @@ Public Class Test
End Sub
End Class",
"Class EventClass
Public Event XEvent()
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
......@@ -295,8 +295,8 @@ Public Class Test
End Sub
End Class",
"Class EventClass
Public Event XEvent()
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
......@@ -324,8 +324,8 @@ Public Class Test
End Sub
End Class",
"Class EventClass
Public Event XEvent()
Public Event ZEvent()
Public Event XEvent()
End Class
Public Class Test
WithEvents EClass As New EventClass
......
......@@ -1325,8 +1325,8 @@ Friend Class Customer
Me.x = x
Me.y = y
End Sub
Public Property Age As Date
Public Property Name As String
Public Property Age As Date
End Class",
index:=1)
End Function
......@@ -1354,8 +1354,8 @@ Friend Class Customer
Me.x = x
Me.y = y
End Sub
Public Property Age As Date
Public Property Name As Object
Public Property Age As Date
End Class",
index:=1)
End Function
......@@ -1383,8 +1383,8 @@ Friend Class Customer
Me.x = x
Me.y = y
End Sub
Public Property Age As Date
Public Property Name As Object
Public Property Age As Date
End Class",
index:=1)
End Function
......@@ -1406,8 +1406,8 @@ Module Program
End Sub
End Module
Friend Class Customer
Public Property Age As Date
Public Property Name As String
Public Property Age As Date
End Class",
index:=1)
End Function
......
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Option Strict Off
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
......@@ -11,7 +10,8 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Genera
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(Nothing, New GenerateVariableCodeFixProvider())
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(
Nothing, New GenerateVariableCodeFixProvider())
End Function
Protected Overrides Function MassageActions(actions As IList(Of CodeAction)) As IList(Of CodeAction)
......@@ -2027,8 +2027,8 @@ End Class",
End Sub
End Module
Friend Class Customer
Public Property Age As Object
Public Property Name As String
Public Property Age As Object
End Class")
End Function
......
......@@ -554,7 +554,8 @@ End Interface
<WpfFact, Trait(Traits.Feature, Traits.Features.ExtractInterface)>
Public Async Function TestExtractInterface_CodeGen_TypeParameters1() As Task
Dim markup = <text>Imports System.Collections.Generic
Dim markup =
"Imports System.Collections.Generic
Public Class TestClass(Of A, B, C, D, E As F, F, G, H, NO1)$$
Public Sub Foo1(a As A)
End Sub
......@@ -581,8 +582,10 @@ Public Class TestClass(Of A, B, C, D, E As F, F, G, H, NO1)$$
Public Sub Bar1()
Dim x As NO1 = Nothing
End Sub
End Class</text>.NormalizedValue()
Dim expectedInterfaceCode = <text>Imports System.Collections.Generic
End Class"
Dim expectedInterfaceCode =
"Imports System.Collections.Generic
Public Interface ITestClass(Of A, B, C, E As F, F, G, H)
WriteOnly Property Prop As List(Of E)
......@@ -590,10 +593,11 @@ Public Interface ITestClass(Of A, B, C, E As F, F, G, H)
Event Foo4 As Action
Sub Foo1(a As A)
Sub Foo3(list As List(Of C))
Function Foo2() As B
Sub Bar1()
Function Foo2() As B
End Interface
</text>.NormalizedValue()
"
Await TestExtractInterfaceCommandVisualBasicAsync(markup, expectedSuccess:=True, expectedInterfaceCode:=expectedInterfaceCode)
End Function
......
......@@ -9,7 +9,7 @@ Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass
Public Class ImplementAbstractClassCommandHandlerTests
<WorkItem(530553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530553")>
......
......@@ -2,15 +2,16 @@
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.ImplementAbstractClass
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass
Partial Public Class ImplementAbstractClassTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(
Nothing, New ImplementAbstractClassCodeFixProvider)
Nothing, New VisualBasicImplementAbstractClassCodeFixProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
......@@ -517,46 +518,56 @@ End Class",
Imports System.Globalization
Class x
Inherits EastAsianLunisolarCalendar
Public Overrides ReadOnly Property Eras As Integer()
Get
Throw New NotImplementedException()
End Get
End Property
Friend Overrides ReadOnly Property CalEraInfo As EraInfo()
Friend Overrides ReadOnly Property MinCalendarYear As Integer
Get
Throw New NotImplementedException()
End Get
End Property
Friend Overrides ReadOnly Property MaxCalendarYear As Integer
Get
Throw New NotImplementedException()
End Get
End Property
Friend Overrides ReadOnly Property MaxDate As Date
Friend Overrides ReadOnly Property CalEraInfo As EraInfo()
Get
Throw New NotImplementedException()
End Get
End Property
Friend Overrides ReadOnly Property MinCalendarYear As Integer
Friend Overrides ReadOnly Property MinDate As Date
Get
Throw New NotImplementedException()
End Get
End Property
Friend Overrides ReadOnly Property MinDate As Date
Friend Overrides ReadOnly Property MaxDate As Date
Get
Throw New NotImplementedException()
End Get
End Property
Public Overrides Function GetEra(time As Date) As Integer
Throw New NotImplementedException()
End Function
Friend Overrides Function GetGregorianYear(year As Integer, era As Integer) As Integer
Friend Overrides Function GetYearInfo(LunarYear As Integer, Index As Integer) As Integer
Throw New NotImplementedException()
End Function
Friend Overrides Function GetYear(year As Integer, time As Date) As Integer
Throw New NotImplementedException()
End Function
Friend Overrides Function GetYearInfo(LunarYear As Integer, Index As Integer) As Integer
Friend Overrides Function GetGregorianYear(year As Integer, era As Integer) As Integer
Throw New NotImplementedException()
End Function
End Class")
......
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Option Strict Off
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.ImplementAbstractClass
Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass
Partial Public Class ImplementAbstractClassTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInDocument() As Task
Dim fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
......@@ -126,7 +124,7 @@ End Class]]>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInProject() As Task
Dim fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
......@@ -249,7 +247,7 @@ End Class]]>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInSolution() As Task
Dim fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
......@@ -380,7 +378,7 @@ End Class]]>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInSolution_DifferentAssemblyWithSameTypeName() As Task
Dim fixAllActionId = ImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
......
......@@ -11,7 +11,7 @@ Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Text.Operations
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.ImplementInterface
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementInterface
Public Class ImplementInterfaceCommandHandlerTests
Private Async Function TestAsync(code As XElement, expectedText As XElement, nextHandler As Action(Of IWpfTextView, TestWorkspace), assertion As Action(Of String, String, IWpfTextView)) As Threading.Tasks.Task
......
......@@ -2,14 +2,16 @@
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.ImplementInterface
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.ImplementInterface
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.ImplementInterface
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementInterface
Partial Public Class ImplementInterfaceTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(Nothing, New ImplementInterfaceCodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(
Nothing, New VisualBasicImplementInterfaceCodeFixProvider)
End Function
<WorkItem(540085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540085")>
......@@ -160,19 +162,21 @@ Interface I
End Interface
Class C
Implements I
Private Property I_M As Integer Implements I.M
Private Property M As Integer
Get
Throw New NotImplementedException()
Return 5
End Get
Set(value As Integer)
Throw New NotImplementedException()
End Set
End Property
Private Property M As Integer
Private Property I_M As Integer Implements I.M
Get
Return 5
Throw New NotImplementedException()
End Get
Set(value As Integer)
Throw New NotImplementedException()
End Set
End Property
End Class")
......@@ -933,24 +937,24 @@ End Class",
Imports System.Collections.Generic
Class A
Implements IReadOnlyList(Of Integer)
Private field As Integer()
Public ReadOnly Property Count As Integer Implements IReadOnlyCollection(Of Integer).Count
Default Public ReadOnly Property Item(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Return DirectCast(field, IReadOnlyList(Of Integer)).Count
Return DirectCast(field, IReadOnlyList(Of Integer))(index)
End Get
End Property
Default Public ReadOnly Property Item(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Public ReadOnly Property Count As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Return DirectCast(field, IReadOnlyList(Of Integer))(index)
Return DirectCast(field, IReadOnlyList(Of Integer)).Count
End Get
End Property
Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Return DirectCast(field, IReadOnlyList(Of Integer)).GetEnumerator()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return DirectCast(field, IReadOnlyList(Of Integer)).GetEnumerator()
End Function
......@@ -972,15 +976,15 @@ Imports System.Collections.Generic
Class A
Implements IReadOnlyList(Of Integer)
Public ReadOnly Property Count As Integer Implements IReadOnlyCollection(Of Integer).Count
Default Public ReadOnly Property Item(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Return DirectCast(field, IReadOnlyList(Of Integer)).Count
Return DirectCast(field, IReadOnlyList(Of Integer))(index)
End Get
End Property
Default Public ReadOnly Property Item(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Public ReadOnly Property Count As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Return DirectCast(field, IReadOnlyList(Of Integer))(index)
Return DirectCast(field, IReadOnlyList(Of Integer)).Count
End Get
End Property
......@@ -989,6 +993,7 @@ Class A
Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Return DirectCast(field, IReadOnlyList(Of Integer)).GetEnumerator()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return DirectCast(field, IReadOnlyList(Of Integer)).GetEnumerator()
End Function
......@@ -3767,27 +3772,24 @@ compareTokens:=False)
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)>
Public Async Function TestImplementInterfaceForIDisposableNonApplicable2() As Task
Await TestAsync(
<Text>Imports System
"Imports System
Class Program
Implements [|IDisposable|]
Public Sub Dispose(flag As Boolean)
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Imports System
End Class",
"Imports System
Class Program
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
Public Sub Dispose(flag As Boolean)
End Sub
Public Sub Dispose(flag As Boolean)
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf),
compareTokens:=False)
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)>
......@@ -4071,14 +4073,14 @@ Interface I : Inherits IDisposable
End Interface
Class C : Implements I
Public Sub Dispose() Implements IDisposable.Dispose
Public Sub F() Implements I.F
Throw New NotImplementedException()
End Sub
Public Sub F() Implements I.F
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class", index:=0, compareTokens:=False)
End Class", index:=0)
End Function
<WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")>
......@@ -4173,23 +4175,55 @@ Class _
C
Implements I(Of System.Exception, System.AggregateException)
Public Function Equals(other As Integer) As Boolean Implements IEquatable(Of Integer).Equals
Public Function M(a As Dictionary(Of Exception, List(Of AggregateException)), b As Exception, c As AggregateException) As List(Of AggregateException) Implements I(Of Exception, AggregateException).M
Throw New NotImplementedException()
End Function
Public Function M(a As Dictionary(Of Exception, List(Of AggregateException)), b As Exception, c As AggregateException) As List(Of AggregateException) Implements I(Of Exception, AggregateException).M
Public Function M(Of TT, UU As TT)(a As Dictionary(Of TT, List(Of UU)), b As TT, c As UU) As List(Of UU) Implements I(Of Exception, AggregateException).M
Throw New NotImplementedException()
End Function
Public Function M(Of TT, UU As TT)(a As Dictionary(Of TT, List(Of UU)), b As TT, c As UU) As List(Of UU) Implements I(Of Exception, AggregateException).M
Public Function Equals(other As Integer) As Boolean Implements IEquatable(Of Integer).Equals
Throw New NotImplementedException()
End Function
{DisposePattern("Overridable ")}
#Region ""IDisposable Support""
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
' TODO: uncomment the following line if Finalize() is overridden above.
' GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Partial Class C
Implements IDisposable
End Class", index:=1, compareTokens:=False)
End Class",
index:=1, compareTokens:=False)
End Function
<WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")>
......@@ -4218,24 +4252,56 @@ Partial Class C
Implements I(Of System.Exception, System.AggregateException)
Implements IDisposable
Public Function Equals(other As Integer) As Boolean Implements IEquatable(Of Integer).Equals
Public Function M(a As Dictionary(Of Exception, List(Of AggregateException)), b As Exception, c As AggregateException) As List(Of AggregateException) Implements I(Of Exception, AggregateException).M
Throw New NotImplementedException()
End Function
Public Function M(a As Dictionary(Of Exception, List(Of AggregateException)), b As Exception, c As AggregateException) As List(Of AggregateException) Implements I(Of Exception, AggregateException).M
Public Function M(Of TT, UU As TT)(a As Dictionary(Of TT, List(Of UU)), b As TT, c As UU) As List(Of UU) Implements I(Of Exception, AggregateException).M
Throw New NotImplementedException()
End Function
Public Function M(Of TT, UU As TT)(a As Dictionary(Of TT, List(Of UU)), b As TT, c As UU) As List(Of UU) Implements I(Of Exception, AggregateException).M
Public Function Equals(other As Integer) As Boolean Implements IEquatable(Of Integer).Equals
Throw New NotImplementedException()
End Function
{DisposePattern("Overridable ")}
#Region ""IDisposable Support""
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
' TODO: uncomment the following line if Finalize() is overridden above.
' GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Interface I(Of T, U As T) : Inherits System.IDisposable, System.IEquatable(Of Integer)
Function M(a As System.Collections.Generic.Dictionary(Of T, System.Collections.Generic.List(Of U)), b As T, c As U) As System.Collections.Generic.List(Of U)
Function M(Of TT, UU As TT)(a As System.Collections.Generic.Dictionary(Of TT, System.Collections.Generic.List(Of UU)), b As TT, c As UU) As System.Collections.Generic.List(Of UU)
End Interface", index:=1, compareTokens:=False)
End Interface",
index:=1)
End Function
Private Shared Function DisposePattern(disposeMethodModifiers As String, Optional simplifySystem As Boolean = True) As String
......@@ -4337,51 +4403,64 @@ Imports System.Collections.Generic
Class Program(Of T)
Implements IList(Of Object)
Private Shared innerList As List(Of Object) = New List(Of Object)
Default Public Property Item(index As Integer) As Object Implements IList(Of Object).Item
Get
Return DirectCast(innerList, IList(Of Object))(index)
End Get
Set(value As Object)
DirectCast(innerList, IList(Of Object))(index) = value
End Set
End Property
Public ReadOnly Property Count As Integer Implements ICollection(Of Object).Count
Get
Return DirectCast(innerList, IList(Of Object)).Count
End Get
End Property
Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of Object).IsReadOnly
Get
Return DirectCast(innerList, IList(Of Object)).IsReadOnly
End Get
End Property
Default Public Property Item(index As Integer) As Object Implements IList(Of Object).Item
Get
Return DirectCast(innerList, IList(Of Object))(index)
End Get
Set(value As Object)
DirectCast(innerList, IList(Of Object))(index) = value
End Set
End Property
Public Sub Insert(index As Integer, item As Object) Implements IList(Of Object).Insert
DirectCast(innerList, IList(Of Object)).Insert(index, item)
End Sub
Public Sub RemoveAt(index As Integer) Implements IList(Of Object).RemoveAt
DirectCast(innerList, IList(Of Object)).RemoveAt(index)
End Sub
Public Sub Add(item As Object) Implements ICollection(Of Object).Add
DirectCast(innerList, IList(Of Object)).Add(item)
End Sub
Public Sub Clear() Implements ICollection(Of Object).Clear
DirectCast(innerList, IList(Of Object)).Clear()
End Sub
Public Sub CopyTo(array() As Object, arrayIndex As Integer) Implements ICollection(Of Object).CopyTo
DirectCast(innerList, IList(Of Object)).CopyTo(array, arrayIndex)
End Sub
Public Sub Insert(index As Integer, item As Object) Implements IList(Of Object).Insert
DirectCast(innerList, IList(Of Object)).Insert(index, item)
End Sub
Public Sub RemoveAt(index As Integer) Implements IList(Of Object).RemoveAt
DirectCast(innerList, IList(Of Object)).RemoveAt(index)
End Sub
Public Function Contains(item As Object) As Boolean Implements ICollection(Of Object).Contains
Return DirectCast(innerList, IList(Of Object)).Contains(item)
End Function
Public Function GetEnumerator() As IEnumerator(Of Object) Implements IEnumerable(Of Object).GetEnumerator
Return DirectCast(innerList, IList(Of Object)).GetEnumerator()
End Function
Public Function IndexOf(item As Object) As Integer Implements IList(Of Object).IndexOf
Return DirectCast(innerList, IList(Of Object)).IndexOf(item)
End Function
Public Function Contains(item As Object) As Boolean Implements ICollection(Of Object).Contains
Return DirectCast(innerList, IList(Of Object)).Contains(item)
End Function
Public Function Remove(item As Object) As Boolean Implements ICollection(Of Object).Remove
Return DirectCast(innerList, IList(Of Object)).Remove(item)
End Function
Public Function GetEnumerator() As IEnumerator(Of Object) Implements IEnumerable(Of Object).GetEnumerator
Return DirectCast(innerList, IList(Of Object)).GetEnumerator()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return DirectCast(innerList, IList(Of Object)).GetEnumerator()
End Function
......@@ -4409,8 +4488,8 @@ End Interface
Public MustInherit Class C
Implements IFace
Public MustOverride Sub IFace_M() Implements IFace.M
Public MustOverride Sub M()
Public MustOverride Sub IFace_M() Implements IFace.M
End Class",
index:=1)
End Function
......
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Option Strict Off
Imports ImplementInterfaceCodeAction = Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService.ImplementInterfaceCodeAction
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.ImplementInterface
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementInterface
Partial Public Class ImplementInterfaceTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)>
......
......@@ -57,6 +57,8 @@
<Link>InternalUtilities\LambdaUtilities.cs</Link>
</Compile>
<Compile Include="AddPackage\CSharpAddSpecificPackageCodeFixProvider.cs" />
<Compile Include="ImplementAbstractClass\CSharpImplementAbstractClassCodeFixProvider.cs" />
<Compile Include="ImplementInterface\CSharpImplementInterfaceCodeFixProvider.cs" />
<Compile Include="Structure\Providers\ArrowExpressionClauseStructureProvider.cs" />
<Compile Include="ConvertToInterpolatedString\CSharpConvertConcatenationToInterpolatedStringRefactoringProvider.cs" />
<Compile Include="RemoveUnnecessaryImports\CSharpRemoveUnnecessaryImportsService.cs" />
......@@ -103,8 +105,6 @@
<Compile Include="CodeFixes\GenerateVariable\GenerateVariableCodeFixProvider.cs" />
<Compile Include="CodeFixes\HideBase\HideBaseCodeFixProvider.AddNewKeywordAction.cs" />
<Compile Include="CodeFixes\HideBase\HideBaseCodeFixProvider.cs" />
<Compile Include="CodeFixes\ImplementAbstractClass\ImplementAbstractClassCodeFixProvider.cs" />
<Compile Include="CodeFixes\ImplementInterface\ImplementInterfaceCodeFixProvider.cs" />
<Compile Include="CodeFixes\Iterator\CSharpAddYieldCodeFixProvider.cs" />
<Compile Include="CodeFixes\Iterator\CSharpChangeToIEnumerableCodeFixProvider.cs" />
<Compile Include="QualifyMemberAccess\CSharpQualifyMemberAccessCodeFixProvider.cs" />
......
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeActions.Providers;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ImplementAbstractClass;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeActions.ImplementAbstractClass
{
[ExportCodeIssueProvider(PredefinedCodeActionProviderNames.ImplementAbstractClass, LanguageNames.CSharp)]
[ExtensionOrder(After = PredefinedCodeActionProviderNames.GenerateType)]
internal partial class ImplementAbstractClassCodeIssueProvider : AbstractCSharpCodeIssueProvider
{
public override IEnumerable<Type> SyntaxNodeTypes
{
get
{
yield return typeof(TypeSyntax);
}
}
protected override async Task<CodeIssue> GetIssueAsync(
Document document,
SyntaxNode node,
CancellationToken cancellationToken)
{
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return null;
}
var service = document.GetLanguageService<IImplementAbstractClassService>();
var result = await service.ImplementAbstractClassAsync(document, node, cancellationToken).ConfigureAwait(false);
var changes = await result.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(false);
if (!changes.Any())
{
return null;
}
return new CodeIssue(
CodeIssueKind.Error,
node.Span,
SpecializedCollections.SingletonEnumerable(new CodeAction(result)));
}
}
}
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ImplementInterface;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ImplementInterface
{
[ExportDiagnosticProvider(PredefinedDiagnosticProviderNames.ImplementInterface, LanguageNames.CSharp)]
internal sealed class ImplementInterfaceDiagnosticProvider : DocumentDiagnosticProvider
{
internal const string DiagnosticId = "ImplementInterface";
internal static readonly DiagnosticDescriptor DiagnosticMD = new DiagnosticDescriptor(DiagnosticId,
DiagnosticKind.Hidden,
CSharpFeaturesResources.ImplementInterface,
CSharpFeaturesResources.ImplementInterface,
"Internal",
DiagnosticSeverity.None);
internal const string CS0535 = "CS0535"; // 'Program' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'
internal const string CS0737 = "CS0737"; // 'Class' does not implement interface member 'IInterface.M()'. 'Class.M()' cannot implement an interface member because it is not public.
internal const string CS0738 = "CS0738"; // 'C' does not implement interface member 'I.Method1()'. 'B.Method1()' cannot implement 'I.Method1()' because it does not have the matching return type of 'void'.
public override IEnumerable<DiagnosticDescriptor> GetSupportedDiagnostics()
{
return SpecializedCollections.SingletonEnumerable(DiagnosticMD);
}
protected override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(Document document, CancellationToken cancellationToken)
{
if (!document.IsOpen())
{
return null;
}
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = model.SyntaxTree.GetRoot(cancellationToken);
var infos = model.GetDeclarationDiagnostics(cancellationToken).Where(d =>
d.Id == CS0535 ||
d.Id == CS0737 ||
d.Id == CS0738).GroupBy(d => d.Location.SourceSpan).Select(g => g.First());
var service = document.GetLanguageService<IImplementInterfaceService>();
var diagnostics = new List<Diagnostic>();
foreach (var error in infos)
{
cancellationToken.ThrowIfCancellationRequested();
var espan = error.Location.SourceSpan;
var token = root.FindToken(espan.Start);
if (!token.Span.IntersectsWith(espan))
{
continue;
}
var typeNode = token.Parent as TypeDeclarationSyntax;
if (typeNode == null)
{
continue;
}
IEnumerable<TypeSyntax> baseListTypes = typeNode.GetAllBaseListTypes(model, cancellationToken);
foreach (var node in baseListTypes)
{
if (service.GetCodeActions(
document,
model,
node,
cancellationToken).Any())
{
diagnostics.Add(CreateUserDiagnostic(document, node, cancellationToken));
}
}
}
return diagnostics;
}
private Diagnostic CreateUserDiagnostic(Document document, TypeSyntax node, CancellationToken cancellationToken)
{
var span = node.Span;
var tree = node.SyntaxTree;
return Diagnostic.Create(DiagnosticMD, tree.GetLocation(span));
}
}
}
......@@ -5,16 +5,17 @@
using Microsoft.CodeAnalysis.CodeFixes.ImplementAbstractClass;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ImplementAbstractClass
namespace Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ImplementAbstractClass), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateType)]
internal class ImplementAbstractClassCodeFixProvider :
internal class CSharpImplementAbstractClassCodeFixProvider :
AbstractImplementAbstractClassCodeFixProvider<ClassDeclarationSyntax>
{
private const string CS0534 = nameof(CS0534); // 'Program' does not implement inherited abstract member 'Foo.bar()'
public ImplementAbstractClassCodeFixProvider() : base(CS0534)
public CSharpImplementAbstractClassCodeFixProvider()
: base(CS0534)
{
}
}
......
......@@ -12,11 +12,11 @@
using Microsoft.CodeAnalysis.ImplementInterface;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ImplementInterface
namespace Microsoft.CodeAnalysis.CSharp.ImplementInterface
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ImplementInterface), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.ImplementAbstractClass)]
internal class ImplementInterfaceCodeFixProvider : CodeFixProvider
internal class CSharpImplementInterfaceCodeFixProvider : CodeFixProvider
{
private readonly Func<TypeSyntax, bool> _interfaceName = n => n.Parent is BaseTypeSyntax && n.Parent.Parent is BaseListSyntax && ((BaseTypeSyntax)n.Parent).Type == n;
private readonly Func<IEnumerable<CodeAction>, bool> _codeActionAvailable = actions => actions != null && actions.Any();
......@@ -25,10 +25,8 @@ internal class ImplementInterfaceCodeFixProvider : CodeFixProvider
private const string CS0737 = nameof(CS0737); // 'Class' does not implement interface member 'IInterface.M()'. 'Class.M()' cannot implement an interface member because it is not public.
private const string CS0738 = nameof(CS0738); // 'C' does not implement interface member 'I.Method1()'. 'B.Method1()' cannot implement 'I.Method1()' because it does not have the matching return type of 'void'.
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CS0535, CS0737, CS0738); }
}
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; }
= ImmutableArray.Create(CS0535, CS0737, CS0738);
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
......
......@@ -112,6 +112,8 @@
</Compile>
<Compile Include="CodeFixes\FixAllOccurrences\FixSomeCodeAction.cs" />
<Compile Include="AddPackage\InstallPackageDirectlyCodeAction.cs" />
<Compile Include="ImplementType\ImplementTypeOptions.cs" />
<Compile Include="ImplementType\ImplementTypeOptionsProvider.cs" />
<Compile Include="RemoveUnnecessaryImports\AbstractRemoveUnnecessaryImportsCodeFixProvider.cs" />
<Compile Include="RemoveUnnecessaryImports\IUnnecessaryImportsService.cs" />
<Compile Include="NavigateTo\AbstractNavigateToSearchService.SearchResult.cs" />
......
......@@ -7,6 +7,7 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
......@@ -39,15 +40,19 @@ public async Task<Document> GetEditAsync(CancellationToken cancellationToken)
unimplementedMembers,
cancellationToken);
var result = await CodeGenerator.AddMemberDeclarationsAsync(
var options = await _document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var insertionBehavior = options.GetOption(ImplementTypeOptions.InsertionBehavior);
var groupMembers = insertionBehavior == ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind;
return await CodeGenerator.AddMemberDeclarationsAsync(
_document.Project.Solution,
_state.ClassType,
memberDefinitions,
new CodeGenerationOptions(_state.Location.GetLocation()),
cancellationToken)
.ConfigureAwait(false);
return result;
new CodeGenerationOptions(
_state.Location.GetLocation(),
autoInsertionLocation: groupMembers,
sortMembers: groupMembers),
cancellationToken).ConfigureAwait(false);
}
private IList<ISymbol> GenerateMembers(
......
......@@ -9,6 +9,7 @@
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
......@@ -168,11 +169,11 @@ public Task<Document> GetUpdatedDocumentAsync(CancellationToken cancellationToke
}
public virtual async Task<Document> GetUpdatedDocumentAsync(
Document document,
IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
INamedTypeSymbol classOrStructType,
SyntaxNode classOrStructDecl,
CancellationToken cancellationToken)
Document document,
IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
INamedTypeSymbol classOrStructType,
SyntaxNode classOrStructDecl,
CancellationToken cancellationToken)
{
var result = document;
var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
......@@ -182,9 +183,16 @@ public Task<Document> GetUpdatedDocumentAsync(CancellationToken cancellationToke
unimplementedMembers,
cancellationToken);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var insertionBehavior = options.GetOption(ImplementTypeOptions.InsertionBehavior);
var groupMembers = insertionBehavior == ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind;
result = await CodeGenerator.AddMemberDeclarationsAsync(
result.Project.Solution, classOrStructType, memberDefinitions,
new CodeGenerationOptions(contextLocation: classOrStructDecl.GetLocation()),
new CodeGenerationOptions(
contextLocation: classOrStructDecl.GetLocation(),
autoInsertionLocation: groupMembers,
sortMembers: groupMembers),
cancellationToken).ConfigureAwait(false);
return result;
......
......@@ -35,9 +35,9 @@ public async Task<Document> ImplementInterfaceAsync(Document document, SyntaxNod
// While implementing just one default action, like in the case of pressing enter after interface name in VB,
// choose to implement with the dispose pattern as that's the Dev12 behavior.
var action = ShouldImplementDisposePattern(document, state, explicitly: false) ?
ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state) :
ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
var action = ShouldImplementDisposePattern(document, state, explicitly: false)
? ImplementInterfaceWithDisposePatternCodeAction.CreateImplementWithDisposePatternCodeAction(this, document, state)
: ImplementInterfaceCodeAction.CreateImplementCodeAction(this, document, state);
return await action.GetUpdatedDocumentAsync(cancellationToken).ConfigureAwait(false);
}
......
// 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 Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.ImplementType
{
internal enum ImplementTypeInsertionBehavior
{
WithOtherMembersOfTheSameKind = 0,
AtTheEnd = 1,
}
internal static class ImplementTypeOptions
{
public static readonly PerLanguageOption<ImplementTypeInsertionBehavior> InsertionBehavior =
new PerLanguageOption<ImplementTypeInsertionBehavior>(
nameof(ImplementTypeOptions),
nameof(InsertionBehavior),
defaultValue: ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind,
storageLocations: new RoamingProfileStorageLocation(
$"TextEditor.%LANGUAGE%.{nameof(ImplementTypeOptions)}.{nameof(InsertionBehavior)}"));
}
}
\ No newline at end of file
// 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.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.ImplementType
{
[ExportOptionProvider, Shared]
internal class ImplementTypeOptionsProvider : IOptionProvider
{
private readonly IEnumerable<IOption> _options = ImmutableArray.Create<IOption>(
ImplementTypeOptions.InsertionBehavior);
public IEnumerable<IOption> GetOptions() => _options;
}
}
\ No newline at end of file
......@@ -102,8 +102,7 @@
<Compile Include="CodeFixes\GenerateParameterizedMember\GenerateParameterizedMemberCodeFixProvider.vb" />
<Compile Include="CodeFixes\GenerateType\GenerateTypeCodeFixProvider.vb" />
<Compile Include="CodeFixes\GenerateVariable\GenerateVariableCodeFixProvider.vb" />
<Compile Include="CodeFixes\ImplementAbstractClass\ImplementAbstractClassCodeFixProvider.vb" />
<Compile Include="CodeFixes\ImplementInterface\ImplementInterfaceCodeFixProvider.vb" />
<Compile Include="ImplementAbstractClass\VisualBasicImplementAbstractClassCodeFixProvider.vb" />
<Compile Include="CodeFixes\IncorrectExitContinue\IncorrectExitContinueCodeFixProvider.AddKeywordCodeAction.vb" />
<Compile Include="CodeFixes\IncorrectExitContinue\IncorrectExitContinueCodeFixProvider.ReplaceKeywordCodeAction.vb" />
<Compile Include="CodeFixes\IncorrectExitContinue\IncorrectExitContinueCodeFixProvider.ReplaceTokenKeywordCodeAction.vb" />
......@@ -113,6 +112,7 @@
<Compile Include="CodeFixes\MoveToTopOfFile\MoveToTopOfFileCodeFixProvider.vb" />
<Compile Include="CodeFixes\OverloadBase\OverloadBaseCodeFixProvider.AddOverloads.vb" />
<Compile Include="CodeFixes\OverloadBase\OverloadBaseCodeFixProvider.vb" />
<Compile Include="ImplementInterface\VisualBasicImplementInterfaceCodeFixProvider.vb" />
<Compile Include="Structure\Providers\CollectionInitializerStructureProvider.vb" />
<Compile Include="Structure\Providers\ObjectCreationInitializerStructureProvider.vb" />
<Compile Include="QualifyMemberAccess\VisualBasicQualifyMemberAccessCodeFixProvider.vb" />
......
' 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 System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeActions.Providers
Imports Microsoft.CodeAnalysis.ImplementAbstractClass
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeActions.ImplementAbstractClass
<ExportCodeIssueProvider(PredefinedCodeActionProviderNames.ImplementAbstractClass, LanguageNames.VisualBasic)>
<ExtensionOrder(After:=PredefinedCodeActionProviderNames.GenerateType)>
Partial Friend Class ImplementAbstractClassCodeIssueProvider
Inherits AbstractVisualBasicCodeIssueProvider
Public Overrides ReadOnly Property SyntaxNodeTypes As IEnumerable(Of Type)
Get
Return {GetType(TypeSyntax)}
End Get
End Property
Protected Overrides Async Function GetIssueAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of CodeIssue)
Dim workspace = document.Project.Solution.Workspace
If workspace.Kind = WorkspaceKind.MiscellaneousFiles Then
Return Nothing
End If
Dim service = document.GetLanguageService(Of IImplementAbstractClassService)()
Dim result = Await service.ImplementAbstractClassAsync(document, node, cancellationToken).ConfigureAwait(False)
Dim textChanges = Await result.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(False)
If textChanges.Count = 0 Then
Return Nothing
End If
Return New CodeIssue(CodeIssueKind.Error, node.Span, {New CodeAction(result)})
End Function
End Class
End Namespace
......@@ -5,11 +5,11 @@ Imports Microsoft.CodeAnalysis.CodeFixes
Imports System.Composition
Imports Microsoft.CodeAnalysis.CodeFixes.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass
<ExportCodeFixProvider(LanguageNames.VisualBasic,
Name:=PredefinedCodeFixProviderNames.ImplementAbstractClass), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateType)>
Friend Class ImplementAbstractClassCodeFixProvider
Friend Class VisualBasicImplementAbstractClassCodeFixProvider
Inherits AbstractImplementAbstractClassCodeFixProvider(Of ClassBlockSyntax)
Friend Const BC30610 As String = "BC30610" ' Class 'foo' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
......
......@@ -6,11 +6,11 @@ Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.ImplementInterface
Imports System.Composition
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.ImplementInterface
Namespace Microsoft.CodeAnalysis.VisualBasic.ImplementInterface
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ImplementInterface), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementAbstractClass)>
Friend Class ImplementInterfaceCodeFixProvider
Friend Class VisualBasicImplementInterfaceCodeFixProvider
Inherits CodeFixProvider
Friend Const BC30149 As String = "BC30149" ' Class 'bar' must implement 'Sub foo()' for interface 'ifoo'.
......
......@@ -85,6 +85,22 @@
Visibility="Collapsed" />
</StackPanel>
</GroupBox>
<GroupBox x:Uid="Implement_Interface_or_Abstract_Class_GroupBox"
Header="{x:Static local:AdvancedOptionPageStrings.Option_Implement_Interface_or_Abstract_Class}">
<StackPanel Margin="0, -5, 0, 5">
<Label Content="{x:Static local:AdvancedOptionPageStrings.Option_When_inserting_properties_events_and_methods_place_them}"/>
<StackPanel Margin="15, 0, 0, 0">
<RadioButton GroupName="Insertion_behavior"
x:Name="with_other_members_of_the_same_kind"
Content="{x:Static local:AdvancedOptionPageStrings.Option_with_other_members_of_the_same_kind}"/>
<RadioButton GroupName="Insertion_behavior"
x:Name="at_the_end"
Content="{x:Static local:AdvancedOptionPageStrings.Option_at_the_end}"/>
</StackPanel>
</StackPanel>
</GroupBox>
</StackPanel>
</ScrollViewer>
</options:AbstractOptionPageControl>
......@@ -6,6 +6,7 @@
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.SymbolSearch;
......@@ -40,9 +41,13 @@ public AdvancedOptionPageControl(IServiceProvider serviceProvider) : base(servic
BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp);
BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp);
BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp);
BindToFullSolutionAnalysisOption(ClosedFileDiagnostics, LanguageNames.CSharp);
BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp);
BindToOption(AllowMovingDeclaration, ExtractMethodOptions.AllowMovingDeclaration, LanguageNames.CSharp);
BindToFullSolutionAnalysisOption(ClosedFileDiagnostics, LanguageNames.CSharp);
BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp);
BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp);
}
}
}
}
\ No newline at end of file
......@@ -48,9 +48,19 @@ public static string Option_EnterOutliningMode
}
public static string Option_ExtractMethod
{
get { return CSharpVSResources.Extract_Method; }
}
=> CSharpVSResources.Extract_Method;
public static string Option_Implement_Interface_or_Abstract_Class
=> ServicesVSResources.Implement_Interface_or_Abstract_Class;
public static string Option_When_inserting_properties_events_and_methods_place_them
=> ServicesVSResources.When_inserting_properties_events_and_methods_place_them;
public static string Option_with_other_members_of_the_same_kind
=> ServicesVSResources.with_other_members_of_the_same_kind;
public static string Option_at_the_end
=> ServicesVSResources.at_the_end;
public static string Option_GenerateXmlDocCommentsForTripleSlash
{
......
......@@ -244,6 +244,15 @@ internal class ServicesVSResources {
}
}
/// <summary>
/// Looks up a localized string similar to at the end.
/// </summary>
internal static string at_the_end {
get {
return ResourceManager.GetString("at_the_end", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Base Types.
/// </summary>
......@@ -914,6 +923,15 @@ internal class ServicesVSResources {
}
}
/// <summary>
/// Looks up a localized string similar to Implement Interface or Abstract Class.
/// </summary>
internal static string Implement_Interface_or_Abstract_Class {
get {
return ResourceManager.GetString("Implement_Interface_or_Abstract_Class", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Implemented By.
/// </summary>
......@@ -2124,6 +2142,24 @@ internal class ServicesVSResources {
}
}
/// <summary>
/// Looks up a localized string similar to When inserting properties, events and methods, place them:.
/// </summary>
internal static string When_inserting_properties_events_and_methods_place_them {
get {
return ResourceManager.GetString("When_inserting_properties_events_and_methods_place_them", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to with other members of the same kind.
/// </summary>
internal static string with_other_members_of_the_same_kind {
get {
return ResourceManager.GetString("with_other_members_of_the_same_kind", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Word Separator:.
/// </summary>
......
......@@ -825,7 +825,19 @@ Additional information: {1}</value>
<data name="Preference" xml:space="preserve">
<value>Preference</value>
</data>
<data name="Implement_Interface_or_Abstract_Class" xml:space="preserve">
<value>Implement Interface or Abstract Class</value>
</data>
<data name="For_a_given_symbol_only_the_topmost_rule_with_a_matching_Specification_will_be_applied_Violation_of_that_rules_Required_Style_will_be_reported_at_the_chosen_Severity_level" xml:space="preserve">
<value>For a given symbol, only the topmost rule with a matching 'Specification' will be applied. Violation of that rule's 'Required Style' will be reported at the chosen 'Severity' level.</value>
</data>
<data name="at_the_end" xml:space="preserve">
<value>at the end</value>
</data>
<data name="When_inserting_properties_events_and_methods_place_them" xml:space="preserve">
<value>When inserting properties, events and methods, place them:</value>
</data>
<data name="with_other_members_of_the_same_kind" xml:space="preserve">
<value>with other members of the same kind</value>
</data>
</root>
\ No newline at end of file
......@@ -95,6 +95,23 @@
Content="{x:Static local:AdvancedOptionPageStrings.Option_AllowMovingDeclaration}" />
</StackPanel>
</GroupBox>
<GroupBox x:Uid="Implement_Interface_or_Abstract_Class_GroupBox"
Header="{x:Static local:AdvancedOptionPageStrings.Option_Implement_Interface_or_Abstract_Class}">
<StackPanel Margin="0, -5, 0, 5">
<Label Content="{x:Static local:AdvancedOptionPageStrings.Option_When_inserting_properties_events_and_methods_place_them}"/>
<StackPanel Margin="15, 0, 0, 0">
<RadioButton GroupName="Insertion_behavior"
x:Name="with_other_members_of_the_same_kind"
Content="{x:Static local:AdvancedOptionPageStrings.Option_with_other_members_of_the_same_kind}"/>
<RadioButton GroupName="Insertion_behavior"
x:Name="at_the_end"
Content="{x:Static local:AdvancedOptionPageStrings.Option_at_the_end}"/>
</StackPanel>
</StackPanel>
</GroupBox>
</StackPanel>
</ScrollViewer>
</options:AbstractOptionPageControl>
......@@ -4,6 +4,7 @@ Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Editor.Shared.Options
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.ImplementType
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.SymbolSearch
Imports Microsoft.VisualStudio.LanguageServices.Implementation
......@@ -37,9 +38,13 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic)
BindToOption(GenerateXmlDocCommentsForTripleApostrophes, FeatureOnOffOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic)
BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic)
BindToFullSolutionAnalysisOption(ClosedFileDiagnostics, LanguageNames.VisualBasic)
BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic)
BindToOption(AllowMovingDeclaration, ExtractMethodOptions.AllowMovingDeclaration, LanguageNames.VisualBasic)
BindToFullSolutionAnalysisOption(ClosedFileDiagnostics, LanguageNames.VisualBasic)
BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic)
BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic)
End Sub
End Class
End Namespace
End Namespace
\ No newline at end of file
......@@ -75,6 +75,18 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
End Get
End Property
Public ReadOnly Property Option_Implement_Interface_or_Abstract_Class As String =
ServicesVSResources.Implement_Interface_or_Abstract_Class
Public ReadOnly Property Option_When_inserting_properties_events_and_methods_place_them As String =
ServicesVSResources.When_inserting_properties_events_and_methods_place_them
Public ReadOnly Property Option_with_other_members_of_the_same_kind As String =
ServicesVSResources.with_other_members_of_the_same_kind
Public ReadOnly Property Option_at_the_end As String =
ServicesVSResources.at_the_end
Public ReadOnly Property Option_GenerateXmlDocCommentsForTripleApostrophes As String
Get
Return BasicVSResources.Generate_XML_documentation_comments_for
......
......@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
......@@ -173,8 +174,11 @@ public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationS
where TDeclaration : SyntaxNode
{
var index = GetInsertionIndex(
declarationList, declaration, options, availableIndices,
CSharpDeclarationComparer.Instance, after, before);
declarationList, declaration, options, availableIndices,
CSharpDeclarationComparer.WithoutNamesInstance,
CSharpDeclarationComparer.WithNamesInstance,
after, before);
if (availableIndices != null)
{
availableIndices.Insert(index, true);
......
......@@ -32,9 +32,7 @@ public override CodeGenerationDestination GetDestination(SyntaxNode node)
}
protected override IComparer<SyntaxNode> GetMemberComparer()
{
return CSharpDeclarationComparer.Instance;
}
=> CSharpDeclarationComparer.WithoutNamesInstance;
protected override AbstractImportsAdder CreateImportsAdder(
Document document)
......
......@@ -10,8 +10,6 @@ namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal class CSharpDeclarationComparer : IComparer<SyntaxNode>
{
public static readonly IComparer<SyntaxNode> Instance = new CSharpDeclarationComparer();
private static readonly Dictionary<SyntaxKind, int> s_kindPrecedenceMap = new Dictionary<SyntaxKind, int>(SyntaxFacts.EqualityComparer)
{
{ SyntaxKind.FieldDeclaration, 0 },
......@@ -57,17 +55,22 @@ internal class CSharpDeclarationComparer : IComparer<SyntaxNode>
{ SyntaxKind.FalseKeyword, 21 },
};
private CSharpDeclarationComparer()
public static readonly CSharpDeclarationComparer WithNamesInstance = new CSharpDeclarationComparer(includeName: true);
public static readonly CSharpDeclarationComparer WithoutNamesInstance = new CSharpDeclarationComparer(includeName: false);
private readonly bool _includeName;
private CSharpDeclarationComparer(bool includeName)
{
_includeName = includeName;
}
public int Compare(SyntaxNode x, SyntaxNode y)
{
if (x.Kind() != y.Kind())
{
int xPrecedence, yPrecedence;
if (!s_kindPrecedenceMap.TryGetValue(x.Kind(), out xPrecedence) ||
!s_kindPrecedenceMap.TryGetValue(y.Kind(), out yPrecedence))
if (!s_kindPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence) ||
!s_kindPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence))
{
// The containing declaration is malformed and contains a node kind we did not expect.
// Ignore comparisons with those unexpected nodes and sort them to the end of the declaration.
......@@ -131,29 +134,32 @@ public int Compare(SyntaxNode x, SyntaxNode y)
}
}
private static int Compare(DelegateDeclarationSyntax x, DelegateDeclarationSyntax y)
private int Compare(DelegateDeclarationSyntax x, DelegateDeclarationSyntax y)
{
int result;
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result) &&
EqualIdentifierName(x.Identifier, y.Identifier, out result))
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result))
{
EqualTypeParameterCount(x.TypeParameterList, y.TypeParameterList, out result);
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static int Compare(BaseFieldDeclarationSyntax x, BaseFieldDeclarationSyntax y)
private int Compare(BaseFieldDeclarationSyntax x, BaseFieldDeclarationSyntax y)
{
int result;
if (EqualConstness(x.Modifiers, y.Modifiers, out result) &&
if (EqualConstness(x.Modifiers, y.Modifiers, out var result) &&
EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualIdentifierName(
x.Declaration.Variables.FirstOrDefault().Identifier,
y.Declaration.Variables.FirstOrDefault().Identifier,
out result);
if (_includeName)
{
EqualIdentifierName(
x.Declaration.Variables.FirstOrDefault().Identifier,
y.Declaration.Variables.FirstOrDefault().Identifier,
out result);
}
}
return result;
......@@ -171,15 +177,15 @@ private static int Compare(ConstructorDeclarationSyntax x, ConstructorDeclaratio
return result;
}
private static int Compare(MethodDeclarationSyntax x, MethodDeclarationSyntax y)
private int Compare(MethodDeclarationSyntax x, MethodDeclarationSyntax y)
{
int result;
if (EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result) &&
EqualIdentifierName(x.Identifier, y.Identifier, out result) &&
EqualTypeParameterCount(x.TypeParameterList, y.TypeParameterList, out result))
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualParameterCount(x.ParameterList, y.ParameterList, out result);
if (!_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
......@@ -209,13 +215,15 @@ private static int Compare(OperatorDeclarationSyntax x, OperatorDeclarationSynta
return result;
}
private static int Compare(EventDeclarationSyntax x, EventDeclarationSyntax y)
private int Compare(EventDeclarationSyntax x, EventDeclarationSyntax y)
{
int result;
if (EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
......@@ -233,56 +241,41 @@ private static int Compare(IndexerDeclarationSyntax x, IndexerDeclarationSyntax
return result;
}
private static int Compare(PropertyDeclarationSyntax x, PropertyDeclarationSyntax y)
private int Compare(PropertyDeclarationSyntax x, PropertyDeclarationSyntax y)
{
int result;
if (EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static int Compare(EnumDeclarationSyntax x, EnumDeclarationSyntax y)
private int Compare(EnumDeclarationSyntax x, EnumDeclarationSyntax y)
{
int result;
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result))
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static int Compare(BaseTypeDeclarationSyntax x, BaseTypeDeclarationSyntax y)
private int Compare(BaseTypeDeclarationSyntax x, BaseTypeDeclarationSyntax y)
{
int result;
if (EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result) &&
EqualIdentifierName(x.Identifier, y.Identifier, out result))
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (x.Kind() == SyntaxKind.ClassDeclaration)
{
EqualTypeParameterCount(
((ClassDeclarationSyntax)x).TypeParameterList,
((ClassDeclarationSyntax)y).TypeParameterList,
out result);
}
else if (x.Kind() == SyntaxKind.StructDeclaration)
if (_includeName)
{
EqualTypeParameterCount(
((StructDeclarationSyntax)x).TypeParameterList,
((StructDeclarationSyntax)y).TypeParameterList,
out result);
}
else
{
EqualTypeParameterCount(
((InterfaceDeclarationSyntax)x).TypeParameterList,
((InterfaceDeclarationSyntax)y).TypeParameterList,
out result);
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
......
......@@ -220,58 +220,83 @@ protected static T Cast<T>(object value)
options = CreateOptionsForMultipleMembers(options);
}
var currentDestination = destination;
// Filter out the members that are implicitly declared. They're implicit, hence we do
// not want an explicit declaration.
var filteredMembers = membersList.Where(m => !m.IsImplicitlyDeclared);
if (options.AutoInsertionLocation)
return options.AutoInsertionLocation
? AddMembersToAppropiateLocationInDestination(destination, filteredMembers, availableIndices, options, cancellationToken)
: AddMembersToEndOfDestination(destination, filteredMembers, availableIndices, options, cancellationToken);
}
private TDeclarationSyntax AddMembersToEndOfDestination<TDeclarationSyntax>(
TDeclarationSyntax destination,
IEnumerable<ISymbol> members,
IList<bool> availableIndices,
CodeGenerationOptions options,
CancellationToken cancellationToken)
where TDeclarationSyntax : SyntaxNode
{
var newMembers = new List<SyntaxNode>();
var codeGenerationDestination = GetDestination(destination);
foreach (var member in members)
{
foreach (var member in filteredMembers)
cancellationToken.ThrowIfCancellationRequested();
var newMember = GetNewMember(options, codeGenerationDestination, member, cancellationToken);
if (newMember != null)
{
cancellationToken.ThrowIfCancellationRequested();
currentDestination = UpdateDestination(availableIndices, options, currentDestination, member, cancellationToken);
newMembers.Add(newMember);
}
}
else
// Metadata as source generates complete declarations and doesn't modify
// existing ones. We can take the members to generate, sort them once,
// and then add them in that order to the end of the destination.
if (!GeneratingEnum(members) && options.SortMembers)
{
var newMembers = new List<SyntaxNode>();
var codeGenerationDestination = GetDestination(destination);
foreach (var member in filteredMembers)
{
cancellationToken.ThrowIfCancellationRequested();
var newMember = (SyntaxNode)null;
switch (member)
{
case IEventSymbol @event: newMember = this.CreateEventDeclaration(@event, codeGenerationDestination, options); break;
case IFieldSymbol field: newMember = this.CreateFieldDeclaration(field, codeGenerationDestination, options); break;
case IPropertySymbol property: newMember = this.CreatePropertyDeclaration(property, codeGenerationDestination, options); break;
case IMethodSymbol method: newMember = this.CreateMethodDeclaration(method, codeGenerationDestination, options); break;
case INamedTypeSymbol namedType: newMember = this.CreateNamedTypeDeclaration(namedType, codeGenerationDestination, options, cancellationToken); break;
case INamespaceSymbol @namespace: newMember = this.CreateNamespaceDeclaration(@namespace, codeGenerationDestination, options, cancellationToken); break;
}
newMembers.Sort(GetMemberComparer());
}
if (newMember != null)
{
newMembers.Add(newMember);
}
}
return this.AddMembers(destination, newMembers);
}
// Metadata as source generates complete declarations and doesn't modify
// existing ones. We can take the members to generate, sort them once,
// and then add them in that order to the end of the destination.
if (!GeneratingEnum(members))
{
newMembers.Sort(GetMemberComparer());
}
private TDeclarationSyntax AddMembersToAppropiateLocationInDestination<TDeclarationSyntax>(
TDeclarationSyntax destination,
IEnumerable<ISymbol> members,
IList<bool> availableIndices,
CodeGenerationOptions options,
CancellationToken cancellationToken)
where TDeclarationSyntax : SyntaxNode
{
var currentDestination = destination;
currentDestination = this.AddMembers(currentDestination, newMembers);
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
currentDestination = UpdateDestination(availableIndices, options, currentDestination, member, cancellationToken);
}
return currentDestination;
}
private SyntaxNode GetNewMember(
CodeGenerationOptions options, CodeGenerationDestination codeGenerationDestination,
ISymbol member, CancellationToken cancellationToken)
{
switch (member)
{
case IEventSymbol @event: return this.CreateEventDeclaration(@event, codeGenerationDestination, options);
case IFieldSymbol field: return this.CreateFieldDeclaration(field, codeGenerationDestination, options);
case IPropertySymbol property: return this.CreatePropertyDeclaration(property, codeGenerationDestination, options);
case IMethodSymbol method: return this.CreateMethodDeclaration(method, codeGenerationDestination, options);
case INamedTypeSymbol namedType: return this.CreateNamedTypeDeclaration(namedType, codeGenerationDestination, options, cancellationToken);
case INamespaceSymbol @namespace: return this.CreateNamespaceDeclaration(@namespace, codeGenerationDestination, options, cancellationToken);
}
return null;
}
private TDeclarationNode UpdateDestination<TDeclarationNode>(
IList<bool> availableIndices,
CodeGenerationOptions options,
......
......@@ -2,6 +2,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
......@@ -234,7 +235,8 @@ public static T GetReuseableSyntaxNodeForAttribute<T>(AttributeData attribute, C
TDeclaration declaration,
CodeGenerationOptions options,
IList<bool> availableIndices,
IComparer<TDeclaration> comparer,
IComparer<TDeclaration> comparerWithoutNameCheck,
IComparer<TDeclaration> comparerWithNameCheck,
Func<SyntaxList<TDeclaration>, TDeclaration> after = null,
Func<SyntaxList<TDeclaration>, TDeclaration> before = null)
where TDeclaration : SyntaxNode
......@@ -279,14 +281,13 @@ public static T GetReuseableSyntaxNodeForAttribute<T>(AttributeData attribute, C
{
return 0;
}
else if (declarationList.IsSorted(comparer))
var desiredIndex = TryGetDesiredIndexIfGrouped(
declarationList, declaration, availableIndices,
comparerWithoutNameCheck, comparerWithNameCheck);
if (desiredIndex.HasValue)
{
var result = Array.BinarySearch(declarationList.ToArray(), declaration, comparer);
var index = GetPreferredIndex(result < 0 ? ~result : result, availableIndices, forward: true);
if (index != -1)
{
return index;
}
return desiredIndex.Value;
}
if (after != null)
......@@ -337,5 +338,106 @@ public static T GetReuseableSyntaxNodeForAttribute<T>(AttributeData attribute, C
return declarationList.Count;
}
public static int? TryGetDesiredIndexIfGrouped<TDeclarationSyntax>(
SyntaxList<TDeclarationSyntax> declarationList,
TDeclarationSyntax declaration,
IList<bool> availableIndices,
IComparer<TDeclarationSyntax> comparerWithoutNameCheck,
IComparer<TDeclarationSyntax> comparerWithNameCheck)
where TDeclarationSyntax : SyntaxNode
{
var result = TryGetDesiredIndexIfGroupedWorker(
declarationList, declaration, availableIndices,
comparerWithoutNameCheck, comparerWithNameCheck);
if (result == null)
{
return null;
}
result = GetPreferredIndex(result.Value, availableIndices, forward: true);
if (result == -1)
{
return null;
}
return result;
}
private static int? TryGetDesiredIndexIfGroupedWorker<TDeclarationSyntax>(
SyntaxList<TDeclarationSyntax> declarationList,
TDeclarationSyntax declaration,
IList<bool> availableIndices,
IComparer<TDeclarationSyntax> comparerWithoutNameCheck,
IComparer<TDeclarationSyntax> comparerWithNameCheck)
where TDeclarationSyntax : SyntaxNode
{
if (!declarationList.IsSorted(comparerWithoutNameCheck))
{
// Existing declarations weren't grouped. Don't try to find a location
// to this declaration into.
return null;
}
// The list was grouped (by type, staticness, accessibility). Try to find a location
// to put the new declaration into.
var result = Array.BinarySearch(declarationList.ToArray(), declaration, comparerWithoutNameCheck);
var desiredGroupIndex = result < 0 ? ~result : result;
Debug.Assert(desiredGroupIndex >= 0);
Debug.Assert(desiredGroupIndex <= declarationList.Count);
// Now, walk forward until we hit the last member of this group.
while (desiredGroupIndex < declarationList.Count)
{
// Stop walking forward if we hit an unavailable index.
if (availableIndices != null && !availableIndices[desiredGroupIndex])
{
break;
}
if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[desiredGroupIndex]))
{
// Found the index of an item not of our group.
break;
}
desiredGroupIndex++;
}
// Now, walk backward until we find the last member with the same name
// as us. We want to keep overloads together, so we'll place ourselves
// after that member.
var currentIndex = desiredGroupIndex;
while (currentIndex > 0)
{
var previousIndex = currentIndex - 1;
// Stop walking backward if we hit an unavailable index.
if (availableIndices != null && !availableIndices[previousIndex])
{
break;
}
if (0 != comparerWithoutNameCheck.Compare(declaration, declarationList[previousIndex]))
{
// Hit the previous group of items.
break;
}
// Still in the same group. If we find something with the same name
// then place ourselves after it.
if (0 == comparerWithNameCheck.Compare(declaration, declarationList[previousIndex]))
{
// Found something with the same name. Generate after this item.
return currentIndex;
}
currentIndex--;
}
// Couldn't find anything with our name. Just place us at the end of this group.
return desiredGroupIndex;
}
}
}
}
\ No newline at end of file
......@@ -116,6 +116,12 @@ internal class CodeGenerationOptions
/// </summary>
public bool AutoInsertionLocation { get; }
/// <summary>
/// If <see cref="AutoInsertionLocation"/> is <code>false</code>, determines if members will be
/// sorted before being added to the end of the list of members.
/// </summary>
public bool SortMembers { get; }
/// <summary>
/// True if the code generator should attempt to reuse the syntax of the constituent entities, such as members, access modifier tokens, etc. while attempting to generate code.
/// If any of the member symbols have zero declaring syntax references (non-source symbols) OR two or more declaring syntax references (partial definitions), then syntax is not reused.
......@@ -139,6 +145,7 @@ internal class CodeGenerationOptions
bool generateMethodBodies = true,
bool generateDocumentationComments = false,
bool autoInsertionLocation = true,
bool sortMembers = true,
bool reuseSyntax = false,
ParseOptions parseOptions = null)
{
......@@ -159,6 +166,7 @@ internal class CodeGenerationOptions
this.GenerateMethodBodies = generateMethodBodies;
this.GenerateDocumentationComments = generateDocumentationComments;
this.AutoInsertionLocation = autoInsertionLocation;
this.SortMembers = sortMembers;
this.ReuseSyntax = reuseSyntax;
this.ParseOptions = parseOptions ?? this.BestLocation?.SourceTree.Options;
......
......@@ -249,9 +249,7 @@ public static Task<Document> AddNamespaceOrTypeDeclarationAsync(Solution solutio
/// Returns the document in the new solution where the destination symbol is declared.
/// </summary>
public static Task<Document> AddMemberDeclarationsAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions options = default(CodeGenerationOptions), CancellationToken cancellationToken = default(CancellationToken))
{
return GetCodeGenerationService(solution.Workspace, destination.Language).AddMembersAsync(solution, destination, members, options, cancellationToken);
}
=> GetCodeGenerationService(solution.Workspace, destination.Language).AddMembersAsync(solution, destination, members, options, cancellationToken);
/// <summary>
/// Returns <c>true</c> if additional declarations can be added to the destination symbol's declaration.
......
......@@ -196,8 +196,8 @@ private static bool IsAbstractPropertyImplemented(INamedTypeSymbol classOrStruct
}
public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembersInThis(
this INamedTypeSymbol classOrStructType,
IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
this INamedTypeSymbol classOrStructType,
IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
CancellationToken cancellationToken)
{
return classOrStructType.GetAllUnimplementedMembers(
......@@ -232,21 +232,6 @@ private static bool IsAbstractPropertyImplemented(INamedTypeSymbol classOrStruct
cancellationToken: cancellationToken);
}
public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembers(
this INamedTypeSymbol classOrStructType,
IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter,
CancellationToken cancellationToken)
{
return classOrStructType.GetAllUnimplementedMembers(
interfacesOrAbstractClasses,
IsImplemented,
ImplementationExists,
interfaceMemberGetter,
allowReimplementation: false,
cancellationToken: cancellationToken);
}
public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedExplicitMembers(
this INamedTypeSymbol classOrStructType,
IEnumerable<INamedTypeSymbol> interfaces,
......@@ -261,21 +246,6 @@ private static bool IsAbstractPropertyImplemented(INamedTypeSymbol classOrStruct
cancellationToken: cancellationToken);
}
public static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedExplicitMembers(
this INamedTypeSymbol classOrStructType,
IEnumerable<INamedTypeSymbol> interfaces,
Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter,
CancellationToken cancellationToken)
{
return classOrStructType.GetAllUnimplementedMembers(
interfaces,
IsExplicitlyImplemented,
ImplementationExists,
interfaceMemberGetter,
allowReimplementation: false,
cancellationToken: cancellationToken);
}
private static IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> GetAllUnimplementedMembers(
this INamedTypeSymbol classOrStructType,
IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses,
......
......@@ -150,7 +150,9 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Dim index = GetInsertionIndex(
declarationList, declaration, options, availableIndices,
VisualBasicDeclarationComparer.Instance, after, before)
VisualBasicDeclarationComparer.WithoutNamesInstance,
VisualBasicDeclarationComparer.WithNamesInstance,
after, before)
If availableIndices IsNot Nothing Then
availableIndices.Insert(index, True)
......
......@@ -28,7 +28,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
End Function
Protected Overrides Function GetMemberComparer() As IComparer(Of SyntaxNode)
Return VisualBasicDeclarationComparer.Instance
Return VisualBasicDeclarationComparer.WithoutNamesInstance
End Function
Protected Overrides Function GetAvailableInsertionIndices(destination As SyntaxNode, cancellationToken As CancellationToken) As IList(Of Boolean)
......
......@@ -7,8 +7,6 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class VisualBasicDeclarationComparer
Implements IComparer(Of SyntaxNode)
Public Shared ReadOnly Instance As IComparer(Of SyntaxNode) = New VisualBasicDeclarationComparer()
Private Shared ReadOnly s_kindPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From
{
{SyntaxKind.FieldDeclaration, 0},
......@@ -61,7 +59,13 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
{SyntaxKind.CTypeKeyword, 24}
}
Private Sub New()
Public Shared ReadOnly WithNamesInstance As New VisualBasicDeclarationComparer(includeName:=True)
Public Shared ReadOnly WithoutNamesInstance As New VisualBasicDeclarationComparer(includeName:=False)
Private ReadOnly _includeName As Boolean
Private Sub New(includeName As Boolean)
_includeName = includeName
End Sub
Public Function Compare(x As SyntaxNode, y As SyntaxNode) As Integer Implements IComparer(Of SyntaxNode).Compare
......@@ -152,27 +156,30 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Return node
End Function
Private Shared Function Compare(x As DelegateStatementSyntax, y As DelegateStatementSyntax) As Integer
Private Function Compare(x As DelegateStatementSyntax, y As DelegateStatementSyntax) As Integer
Dim result = 0
If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) AndAlso
EqualIdentifierName(x.Identifier, y.Identifier, result) Then
If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualTypeParameterCount(x.TypeParameterList, y.TypeParameterList, result)
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As FieldDeclarationSyntax, y As FieldDeclarationSyntax) As Integer
Private Function Compare(x As FieldDeclarationSyntax, y As FieldDeclarationSyntax) As Integer
Dim result = 0
If EqualConstness(x.Modifiers, y.Modifiers, result) AndAlso
EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualIdentifierName(
If _includeName Then
EqualIdentifierName(
x.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier,
y.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier,
result)
End If
End If
Return result
......@@ -189,36 +196,40 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Return result
End Function
Private Shared Function Compare(x As MethodStatementSyntax, y As MethodStatementSyntax) As Integer
Private Function Compare(x As MethodStatementSyntax, y As MethodStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) AndAlso
EqualIdentifierName(x.Identifier, y.Identifier, result) AndAlso
EqualTypeParameterCount(x.TypeParameterList, y.TypeParameterList, result) Then
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualParameterLists(x.ParameterList, y.ParameterList, result)
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As EventStatementSyntax, y As EventStatementSyntax) As Integer
Private Function Compare(x As EventStatementSyntax, y As EventStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As PropertyStatementSyntax, y As PropertyStatementSyntax) As Integer
Private Function Compare(x As PropertyStatementSyntax, y As PropertyStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
......@@ -233,22 +244,25 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Return result
End Function
Private Shared Function Compare(x As EnumStatementSyntax, y As EnumStatementSyntax) As Integer
Private Function Compare(x As EnumStatementSyntax, y As EnumStatementSyntax) As Integer
Dim result = 0
If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As TypeStatementSyntax, y As TypeStatementSyntax) As Integer
Private Function Compare(x As TypeStatementSyntax, y As TypeStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) AndAlso
EqualIdentifierName(x.Identifier, y.Identifier, result) Then
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualTypeParameterCount(x.TypeParameterList, y.TypeParameterList, result)
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册