未验证 提交 807f6d9c 编写于 作者: A Andy Gocke 提交者: GitHub

Merge pull request #38179 from dotnet/merges/master-to-master-vs-deps

Merge master to master-vs-deps
...@@ -26,7 +26,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T ...@@ -26,7 +26,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{ {
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider(performExperimentCheck: false)); new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider());
} }
public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests
......
...@@ -40,7 +40,7 @@ internal enum UnusedValuePreference ...@@ -40,7 +40,7 @@ internal enum UnusedValuePreference
} }
*/ */
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider(performExperimentCheck: false)); new CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider());
} }
public class UnusedLocalVariableConfigurationTests : EnumCodeStyleOptionConfigurationTests public class UnusedLocalVariableConfigurationTests : EnumCodeStyleOptionConfigurationTests
......
...@@ -42,7 +42,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T ...@@ -42,7 +42,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T
csharp_style_var_when_type_is_apparent csharp_style_var_when_type_is_apparent
*/ */
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpUseExplicitTypeDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider(performExperimentCheck: false)); new CSharpUseExplicitTypeDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider());
} }
public class VarElsewhere_TrueConfigurationTests : MultipleCodeStyleOptionConfigurationTests public class VarElsewhere_TrueConfigurationTests : MultipleCodeStyleOptionConfigurationTests
......
...@@ -26,7 +26,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T ...@@ -26,7 +26,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{ {
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider(performExperimentCheck: false)); new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider());
} }
public class NoneConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests public class NoneConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests
......
...@@ -47,7 +47,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T ...@@ -47,7 +47,7 @@ protected override TestWorkspace CreateWorkspaceFromFile(string initialMarkup, T
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{ {
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider(performExperimentCheck: false)); new CustomDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider());
} }
public class NoneConfigurationTests : DotNetDiagnosticSeverityBasedSeverityConfigurationTests public class NoneConfigurationTests : DotNetDiagnosticSeverityBasedSeverityConfigurationTests
......
...@@ -24,7 +24,7 @@ private async Task TestAllowUnsafeEnabledIfDisabledAsync(string initialMarkup) ...@@ -24,7 +24,7 @@ private async Task TestAllowUnsafeEnabledIfDisabledAsync(string initialMarkup)
using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters))
{ {
var (_, action) = await GetCodeActionsAsync(workspace, parameters); var (_, action) = await GetCodeActionsAsync(workspace, parameters);
var operations = await VerifyActionAndGetOperationsAsync(action, default); var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
var (oldSolution, newSolution) = ApplyOperationsAndGetSolution(workspace, operations); var (oldSolution, newSolution) = ApplyOperationsAndGetSolution(workspace, operations);
Assert.True(((CSharpCompilationOptions)newSolution.Projects.Single().CompilationOptions).AllowUnsafe); Assert.True(((CSharpCompilationOptions)newSolution.Projects.Single().CompilationOptions).AllowUnsafe);
......
...@@ -31,7 +31,7 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider ...@@ -31,7 +31,7 @@ internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProvider
using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters))
{ {
var (_, action) = await GetCodeActionsAsync(workspace, parameters); var (_, action) = await GetCodeActionsAsync(workspace, parameters);
var operations = await VerifyActionAndGetOperationsAsync(action, default); var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
var oldSolution = appliedChanges.Item1; var oldSolution = appliedChanges.Item1;
......
...@@ -22,9 +22,6 @@ public class GenerateEqualsAndGetHashCodeFromMembersTests : AbstractCSharpCodeAc ...@@ -22,9 +22,6 @@ public class GenerateEqualsAndGetHashCodeFromMembersTests : AbstractCSharpCodeAc
private static readonly TestParameters CSharp6 = private static readonly TestParameters CSharp6 =
new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6));
private static readonly TestParameters CSharp8 =
new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8));
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider((IPickMembersService)parameters.fixProviderData); => new GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider((IPickMembersService)parameters.fixProviderData);
...@@ -88,6 +85,45 @@ public override bool Equals(object obj) ...@@ -88,6 +85,45 @@ public override bool Equals(object obj)
parameters: CSharp6); parameters: CSharp6);
} }
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestNullableReferenceIEquatable()
{
await TestInRegularAndScript1Async(
@"#nullable enable
using System;
using System.Collections.Generic;
class S : IEquatable<S> { }
class Program
{
[|S? a;|]
}",
@"#nullable enable
using System;
using System.Collections.Generic;
class S : IEquatable<S> { }
class Program
{
S? a;
public override bool Equals(object? obj)
{
return obj is Program program &&
EqualityComparer<S?>.Default.Equals(a, program.a);
}
public override int GetHashCode()
{
return -1757793268 + EqualityComparer<S?>.Default.GetHashCode(a);
}
}", index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
public async Task TestValueIEquatable() public async Task TestValueIEquatable()
{ {
...@@ -422,8 +458,7 @@ public override bool Equals(object? obj) ...@@ -422,8 +458,7 @@ public override bool Equals(object? obj)
return obj is Program program && return obj is Program program &&
a == program.a; a == program.a;
} }
}", }");
parameters: CSharp8);
} }
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)]
......
...@@ -337,6 +337,63 @@ public object Method1() ...@@ -337,6 +337,63 @@ public object Method1()
}"); }");
} }
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task NoNullableAttributesInMethodFromMetadata()
{
var initial = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<MetadataReferenceFromSource Language=""C#"" CommonReferences=""true"">
<Document>
#nullable enable
public interface IInterface
{
void M(string? s1, string s2);
string this[string? s1, string s2] { get; set; }
}
</Document>
</MetadataReferenceFromSource>
<Document>
#nullable enable
using System;
class C : [|IInterface|]
{
}</Document>
</Project>
</Workspace>";
var expected = @"
#nullable enable
using System;
class C : IInterface
{
public string this[string? s1, string s2]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void M(string? s1, string s2)
{
throw new NotImplementedException();
}
}";
await TestWithAllCodeStyleOptionsOffAsync(initial, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodWhenClassBracesAreMissing() public async Task TestMethodWhenClassBracesAreMissing()
{ {
...@@ -6036,6 +6093,56 @@ public void set_P(int x, object Value) ...@@ -6036,6 +6093,56 @@ public void set_P(int x, object Value)
await TestWithAllCodeStyleOptionsOffAsync(initial, expected, index: 0); await TestWithAllCodeStyleOptionsOffAsync(initial, expected, index: 0);
} }
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementationOfIndexerWithInaccessibleAttributes()
{
var initial = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
internal class ShouldBeRemovedAttribute : Attribute { }
public interface I
{
string this[[ShouldBeRemovedAttribute] int i] { get; set; }
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<ProjectReference>Assembly1</ProjectReference>
<Document>
using System;
class C : [|I|]
{
}
</Document>
</Project>
</Workspace>";
var expected = @"
using System;
class C : I
{
public string this[int i]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
";
await TestWithAllCodeStyleOptionsOffAsync(initial, expected, index: 0);
}
#if false #if false
[WorkItem(13677)] [WorkItem(13677)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
...@@ -7996,7 +8103,7 @@ public class Test : ITest ...@@ -7996,7 +8103,7 @@ public class Test : ITest
}"); }");
} }
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/36101"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableDisabled() public async Task TestWithNullableDisabled()
{ {
await TestInRegularAndScriptAsync( await TestInRegularAndScriptAsync(
......
...@@ -38,6 +38,21 @@ class C ...@@ -38,6 +38,21 @@ class C
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
} }
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationWithNullableReferenceTypes()
{
var markup = @"
class C
{
(string?, string) y = [|($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(string?, string)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(655607, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/655607")] [WorkItem(655607, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/655607")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestMissingTupleElement() public async Task TestMissingTupleElement()
......
...@@ -3963,6 +3963,22 @@ static void Main(string[] args) ...@@ -3963,6 +3963,22 @@ static void Main(string[] args)
}", new TestParameters(options: PreferImplicitTypeWithSilent)); }", new TestParameters(options: PreferImplicitTypeWithSilent));
} }
[Fact, WorkItem(31849, "https://github.com/dotnet/roslyn/issues/31849")]
public async Task NoSuggestionOnNestedNullabilityRequired()
{
await TestMissingInRegularAndScriptAsync(
@"#nullable enable
using System.Threading.Tasks;
class C
{
Task<string?> FooAsync()
{
return Task.FromResult<[|string?|]>(""something"");
}
}");
}
[Theory] [Theory]
[InlineData(0)] [InlineData(0)]
[InlineData(1)] [InlineData(1)]
......
...@@ -45,9 +45,10 @@ void M(string s) ...@@ -45,9 +45,10 @@ void M(string s)
} }
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestOnIf() [WorkItem(38136, "https://github.com/dotnet/roslyn/pull/38136")]
public async Task TestMissingOnIf()
{ {
await TestInRegularAndScriptAsync( await TestMissingInRegularAndScriptAsync(
@"using System; @"using System;
class C class C
...@@ -58,15 +59,6 @@ void M(string s) ...@@ -58,15 +59,6 @@ void M(string s)
throw new ArgumentNullException(nameof(s)); throw new ArgumentNullException(nameof(s));
_s = s; _s = s;
} }
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}"); }");
} }
......
...@@ -91,9 +91,9 @@ class C ...@@ -91,9 +91,9 @@ class C
{ {
void M(string s, string t) void M(string s, string t)
{ {
{|FixAllInDocument:if|} (s == null) if (s == null)
{ {
throw new ArgumentNullException(nameof(s)); {|FixAllInDocument:throw new ArgumentNullException(nameof(s));|}
} }
if (t == null) if (t == null)
...@@ -132,9 +132,9 @@ void M(string s, string t) ...@@ -132,9 +132,9 @@ void M(string s, string t)
throw new ArgumentNullException(nameof(s)); throw new ArgumentNullException(nameof(s));
} }
{|FixAllInDocument:if|} (t == null) if (t == null)
{ {
throw new ArgumentNullException(nameof(t)); {|FixAllInDocument:throw new ArgumentNullException(nameof(t));|}
} }
_s = s; _s = s;
......
...@@ -398,7 +398,7 @@ Imports IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute ...@@ -398,7 +398,7 @@ Imports IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1"> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="ClassLibrary1">
<CompilationOptions <CompilationOptions
CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %>
StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>/> StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>
DelaySign="True" DelaySign="True"
/> />
</Project> </Project>
......
...@@ -70,6 +70,9 @@ public TestParameters WithFixProviderData(object fixProviderData) ...@@ -70,6 +70,9 @@ public TestParameters WithFixProviderData(object fixProviderData)
public TestParameters WithIndex(int index) public TestParameters WithIndex(int index)
=> new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, title: title); => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, title: title);
public TestParameters WithRetainNonFixableDiagnostics(bool retainNonFixableDiagnostics)
=> new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, title: title, retainNonFixableDiagnostics: retainNonFixableDiagnostics);
} }
protected abstract string GetLanguage(); protected abstract string GetLanguage();
...@@ -241,7 +244,7 @@ protected Task TestSmartTagGlyphTagsAsync(string initialMarkup, ImmutableArray<s ...@@ -241,7 +244,7 @@ protected Task TestSmartTagGlyphTagsAsync(string initialMarkup, ImmutableArray<s
string expectedDocumentName, string expectedDocumentName,
CodeAction action) CodeAction action)
{ {
var operations = await VerifyActionAndGetOperationsAsync(action, default); var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
return await TestAddDocument( return await TestAddDocument(
workspace, workspace,
expectedMarkup, expectedMarkup,
...@@ -398,7 +401,7 @@ protected Task TestSmartTagGlyphTagsAsync(string initialMarkup, ImmutableArray<s ...@@ -398,7 +401,7 @@ protected Task TestSmartTagGlyphTagsAsync(string initialMarkup, ImmutableArray<s
ImmutableArray<TextSpan> navigationSpans, ImmutableArray<TextSpan> navigationSpans,
TestParameters parameters) TestParameters parameters)
{ {
var operations = await VerifyActionAndGetOperationsAsync(action, parameters); var operations = await VerifyActionAndGetOperationsAsync(workspace, action, parameters);
return await TestOperationsAsync( return await TestOperationsAsync(
workspace, expected, operations, conflictSpans, renameSpans, workspace, expected, operations, conflictSpans, renameSpans,
warningSpans, navigationSpans, expectedChangedDocumentId: null, parseOptions: parameters.parseOptions); warningSpans, navigationSpans, expectedChangedDocumentId: null, parseOptions: parameters.parseOptions);
...@@ -539,10 +542,15 @@ static void VerifyExpectedDocumentText(string expected, string actual) ...@@ -539,10 +542,15 @@ static void VerifyExpectedDocumentText(string expected, string actual)
} }
} }
internal static Task<ImmutableArray<CodeActionOperation>> VerifyActionAndGetOperationsAsync( internal async Task<ImmutableArray<CodeActionOperation>> VerifyActionAndGetOperationsAsync(
CodeAction action, TestParameters parameters) TestWorkspace workspace, CodeAction action, TestParameters parameters)
{
if (action is null)
{ {
Assert.False(action is null, "No action was offered when one was expected."); var diagnostics = await GetDiagnosticsWorkerAsync(workspace, parameters.WithRetainNonFixableDiagnostics(true));
throw new Exception("No action was offered when one was expected. Diagnostics from the compilation: " + string.Join("", diagnostics.Select(d => Environment.NewLine + d.ToString())));
}
if (parameters.priority != null) if (parameters.priority != null)
{ {
...@@ -554,7 +562,7 @@ static void VerifyExpectedDocumentText(string expected, string actual) ...@@ -554,7 +562,7 @@ static void VerifyExpectedDocumentText(string expected, string actual)
Assert.Equal(parameters.title, action.Title); Assert.Equal(parameters.title, action.Title);
} }
return action.GetOperationsAsync(CancellationToken.None); return await action.GetOperationsAsync(CancellationToken.None);
} }
protected Tuple<Solution, Solution> ApplyOperationsAndGetSolution( protected Tuple<Solution, Solution> ApplyOperationsAndGetSolution(
......
...@@ -79,7 +79,7 @@ protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(Te ...@@ -79,7 +79,7 @@ protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(Te
CodeAction action, CodeAction action,
string expectedPreviewContents = null) string expectedPreviewContents = null)
{ {
var operations = await VerifyActionAndGetOperationsAsync(action, default); var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
await VerifyPreviewContents(workspace, expectedPreviewContents, operations); await VerifyPreviewContents(workspace, expectedPreviewContents, operations);
......
...@@ -259,6 +259,8 @@ public static TestWorkspace Create(string xmlDefinition, bool completed = true, ...@@ -259,6 +259,8 @@ public static TestWorkspace Create(string xmlDefinition, bool completed = true,
ref int projectId, ref int projectId,
ref int documentId) ref int documentId)
{ {
AssertNoChildText(projectElement);
var language = GetLanguage(workspace, projectElement); var language = GetLanguage(workspace, projectElement);
var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId); var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId);
...@@ -802,6 +804,8 @@ private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace ...@@ -802,6 +804,8 @@ private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace
private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource) private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource)
{ {
AssertNoChildText(referencedSource);
var languageName = GetLanguage(workspace, referencedSource); var languageName = GetLanguage(workspace, referencedSource);
var assemblyName = "ReferencedAssembly"; var assemblyName = "ReferencedAssembly";
...@@ -947,5 +951,16 @@ public static bool IsWorkspaceElement(string text) ...@@ -947,5 +951,16 @@ public static bool IsWorkspaceElement(string text)
{ {
return text.TrimStart('\r', '\n', ' ').StartsWith("<Workspace>", StringComparison.Ordinal); return text.TrimStart('\r', '\n', ' ').StartsWith("<Workspace>", StringComparison.Ordinal);
} }
private static void AssertNoChildText(XElement element)
{
foreach (var node in element.Nodes())
{
if (node is XText text && !string.IsNullOrWhiteSpace(text.Value))
{
throw new Exception($"Element {element} has child text that isn't recognized. The XML syntax is invalid.");
}
}
}
} }
} }
...@@ -60,7 +60,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar ...@@ -60,7 +60,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar
explicitInterfaceImplementations:=Nothing, explicitInterfaceImplementations:=Nothing,
name:=methodName, name:=methodName,
typeParameters:=Nothing, typeParameters:=Nothing,
parameters:=delegateInvokeMethod.Parameters.WithAttributesToBeCopied(destinationType), parameters:=delegateInvokeMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(destinationType).Parameters,
handlesExpressions:=ImmutableArray.Create(Of SyntaxNode)(handlesSyntax)) handlesExpressions:=ImmutableArray.Create(Of SyntaxNode)(handlesSyntax))
methodSymbol = GeneratedSymbolAnnotation.AddAnnotationToSymbol(methodSymbol) methodSymbol = GeneratedSymbolAnnotation.AddAnnotationToSymbol(methodSymbol)
......
...@@ -29,8 +29,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar ...@@ -29,8 +29,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.NavigationBar
Dim codeGenerationSymbol = GeneratedSymbolAnnotation.AddAnnotationToSymbol( Dim codeGenerationSymbol = GeneratedSymbolAnnotation.AddAnnotationToSymbol(
CodeGenerationSymbolFactory.CreateMethodSymbol( CodeGenerationSymbolFactory.CreateMethodSymbol(
methodToReplicate, methodToReplicate.RemoveInaccessibleAttributesAndAttributesOfTypes(destinationType)))
parameters:=methodToReplicate.Parameters.WithAttributesToBeCopied(destinationType)))
Return Await CodeGenerator.AddMethodDeclarationAsync(document.Project.Solution, Return Await CodeGenerator.AddMethodDeclarationAsync(document.Project.Solution,
destinationType, destinationType,
......
...@@ -27,7 +27,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Config ...@@ -27,7 +27,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Config
End Function End Function
Friend Overrides Function CreateDiagnosticProviderAndFixer(ByVal workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Friend Overrides Function CreateDiagnosticProviderAndFixer(ByVal workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicUseObjectInitializerDiagnosticAnalyzer(), New ConfigureCodeStyleOptionCodeFixProvider(performExperimentCheck:=False)) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicUseObjectInitializerDiagnosticAnalyzer(), New ConfigureCodeStyleOptionCodeFixProvider())
End Function End Function
Public Class TrueConfigurationTests Public Class TrueConfigurationTests
......
...@@ -27,7 +27,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Config ...@@ -27,7 +27,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Config
End Function End Function
Friend Overrides Function CreateDiagnosticProviderAndFixer(ByVal workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Friend Overrides Function CreateDiagnosticProviderAndFixer(ByVal workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicUseObjectInitializerDiagnosticAnalyzer(), New ConfigureSeverityLevelCodeFixProvider(performExperimentCheck:=False)) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicUseObjectInitializerDiagnosticAnalyzer(), New ConfigureSeverityLevelCodeFixProvider())
End Function End Function
Public Class NoneConfigurationTests Public Class NoneConfigurationTests
......
...@@ -51,7 +51,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Config ...@@ -51,7 +51,7 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Config
End Function End Function
Friend Overrides Function CreateDiagnosticProviderAndFixer(ByVal workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Friend Overrides Function CreateDiagnosticProviderAndFixer(ByVal workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New CustomDiagnosticAnalyzer(), New ConfigureSeverityLevelCodeFixProvider(performExperimentCheck:=False)) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New CustomDiagnosticAnalyzer(), New ConfigureSeverityLevelCodeFixProvider())
End Function End Function
Public Class NoneConfigurationTests Public Class NoneConfigurationTests
......
...@@ -181,7 +181,7 @@ private IEnumerable<SignatureHelpParameter> ConvertTupleMembers(INamedTypeSymbol ...@@ -181,7 +181,7 @@ private IEnumerable<SignatureHelpParameter> ConvertTupleMembers(INamedTypeSymbol
var result = new List<SignatureHelpParameter>(); var result = new List<SignatureHelpParameter>();
foreach (var element in tupleType.TupleElements) foreach (var element in tupleType.TupleElements)
{ {
var type = element.Type; var type = element.GetTypeWithAnnotatedNullability();
// The display name for each element. // The display name for each element.
// Empty strings for elements not explicitly declared // Empty strings for elements not explicitly declared
......
...@@ -26,19 +26,6 @@ internal sealed partial class ConfigureCodeStyleOptionCodeFixProvider : IConfigu ...@@ -26,19 +26,6 @@ internal sealed partial class ConfigureCodeStyleOptionCodeFixProvider : IConfigu
{ {
private static readonly ImmutableArray<bool> s_boolValues = ImmutableArray.Create(true, false); private static readonly ImmutableArray<bool> s_boolValues = ImmutableArray.Create(true, false);
private readonly bool _performExperimentCheck;
public ConfigureCodeStyleOptionCodeFixProvider()
: this(performExperimentCheck: true)
{
}
// Internal for test purpose.
internal ConfigureCodeStyleOptionCodeFixProvider(bool performExperimentCheck)
{
_performExperimentCheck = performExperimentCheck;
}
public bool IsFixableDiagnostic(Diagnostic diagnostic) public bool IsFixableDiagnostic(Diagnostic diagnostic)
{ {
// We only offer fix for configurable code style diagnostics which have one of more editorconfig based storage locations. // We only offer fix for configurable code style diagnostics which have one of more editorconfig based storage locations.
...@@ -60,16 +47,15 @@ public FixAllProvider GetFixAllProvider() ...@@ -60,16 +47,15 @@ public FixAllProvider GetFixAllProvider()
=> null; => null;
public Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) public Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
=> Task.FromResult(GetConfigurations(document.Project, diagnostics, _performExperimentCheck, cancellationToken)); => Task.FromResult(GetConfigurations(document.Project, diagnostics, cancellationToken));
public Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) public Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
=> Task.FromResult(GetConfigurations(project, diagnostics, _performExperimentCheck, cancellationToken)); => Task.FromResult(GetConfigurations(project, diagnostics, cancellationToken));
private static ImmutableArray<CodeFix> GetConfigurations(Project project, IEnumerable<Diagnostic> diagnostics, bool performExperimentCheck, CancellationToken cancellationToken) private static ImmutableArray<CodeFix> GetConfigurations(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{ {
// Bail out if NativeEditorConfigSupport experiment is not enabled. // Bail out if NativeEditorConfigSupport experiment is not enabled.
if (performExperimentCheck && if (!EditorConfigDocumentOptionsProviderFactory.ShouldUseNativeEditorConfigSupport(project.Solution.Workspace))
!EditorConfigDocumentOptionsProviderFactory.ShouldUseNativeEditorConfigSupport(project.Solution.Workspace))
{ {
return ImmutableArray<CodeFix>.Empty; return ImmutableArray<CodeFix>.Empty;
} }
......
...@@ -26,19 +26,6 @@ internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigura ...@@ -26,19 +26,6 @@ internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigura
(nameof(EditorConfigSeverityStrings.Warning), EditorConfigSeverityStrings.Warning), (nameof(EditorConfigSeverityStrings.Warning), EditorConfigSeverityStrings.Warning),
(nameof(EditorConfigSeverityStrings.Error), EditorConfigSeverityStrings.Error)); (nameof(EditorConfigSeverityStrings.Error), EditorConfigSeverityStrings.Error));
private readonly bool _performExperimentCheck;
public ConfigureSeverityLevelCodeFixProvider()
: this(performExperimentCheck: true)
{
}
// Internal for test purpose.
internal ConfigureSeverityLevelCodeFixProvider(bool performExperimentCheck)
{
_performExperimentCheck = performExperimentCheck;
}
// We only offer fix for configurable diagnostics. // We only offer fix for configurable diagnostics.
// Also skip suppressed diagnostics defensively, though the code fix engine should ideally never call us for suppressed diagnostics. // Also skip suppressed diagnostics defensively, though the code fix engine should ideally never call us for suppressed diagnostics.
public bool IsFixableDiagnostic(Diagnostic diagnostic) public bool IsFixableDiagnostic(Diagnostic diagnostic)
...@@ -48,16 +35,15 @@ public FixAllProvider GetFixAllProvider() ...@@ -48,16 +35,15 @@ public FixAllProvider GetFixAllProvider()
=> null; => null;
public Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) public Task<ImmutableArray<CodeFix>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
=> Task.FromResult(GetConfigurations(document.Project, diagnostics, _performExperimentCheck, cancellationToken)); => Task.FromResult(GetConfigurations(document.Project, diagnostics, cancellationToken));
public Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) public Task<ImmutableArray<CodeFix>> GetFixesAsync(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
=> Task.FromResult(GetConfigurations(project, diagnostics, _performExperimentCheck, cancellationToken)); => Task.FromResult(GetConfigurations(project, diagnostics, cancellationToken));
private static ImmutableArray<CodeFix> GetConfigurations(Project project, IEnumerable<Diagnostic> diagnostics, bool performExperimentCheck, CancellationToken cancellationToken) private static ImmutableArray<CodeFix> GetConfigurations(Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{ {
// Bail out if NativeEditorConfigSupport experiment is not enabled. // Bail out if NativeEditorConfigSupport experiment is not enabled.
if (performExperimentCheck && if (!EditorConfigDocumentOptionsProviderFactory.ShouldUseNativeEditorConfigSupport(project.Solution.Workspace))
!EditorConfigDocumentOptionsProviderFactory.ShouldUseNativeEditorConfigSupport(project.Solution.Workspace))
{ {
return ImmutableArray<CodeFix>.Empty; return ImmutableArray<CodeFix>.Empty;
} }
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
...@@ -9,6 +11,7 @@ ...@@ -9,6 +11,7 @@
using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ImplementInterface namespace Microsoft.CodeAnalysis.ImplementInterface
{ {
...@@ -44,7 +47,7 @@ internal partial class ImplementInterfaceCodeAction ...@@ -44,7 +47,7 @@ internal partial class ImplementInterfaceCodeAction
var updatedProperty = property.RenameParameters(parameterNames); var updatedProperty = property.RenameParameters(parameterNames);
updatedProperty = updatedProperty.RemoveAttributeFromParameters(attributesToRemove); updatedProperty = updatedProperty.RemoveInaccessibleAttributesAndAttributesOfTypes(compilation.Assembly, attributesToRemove);
// TODO(cyrusn): Delegate through throughMember if it's non-null. // TODO(cyrusn): Delegate through throughMember if it's non-null.
return CodeGenerationSymbolFactory.CreatePropertySymbol( return CodeGenerationSymbolFactory.CreatePropertySymbol(
...@@ -66,10 +69,10 @@ internal partial class ImplementInterfaceCodeAction ...@@ -66,10 +69,10 @@ internal partial class ImplementInterfaceCodeAction
private INamedTypeSymbol[] AttributesToRemove(Compilation compilation) private INamedTypeSymbol[] AttributesToRemove(Compilation compilation)
{ {
return new[] { compilation.ComAliasNameAttributeType(), compilation.TupleElementNamesAttributeType(), return new[] { compilation.ComAliasNameAttributeType(), compilation.TupleElementNamesAttributeType(),
compilation.DynamicAttributeType() }; compilation.DynamicAttributeType() }.WhereNotNull().ToArray()!;
} }
private IMethodSymbol GenerateSetAccessor( private IMethodSymbol? GenerateSetAccessor(
Compilation compilation, Compilation compilation,
IPropertySymbol property, IPropertySymbol property,
Accessibility accessibility, Accessibility accessibility,
...@@ -103,7 +106,7 @@ private INamedTypeSymbol[] AttributesToRemove(Compilation compilation) ...@@ -103,7 +106,7 @@ private INamedTypeSymbol[] AttributesToRemove(Compilation compilation)
compilation, property, generateAbstractly, propertyGenerationBehavior, cancellationToken)); compilation, property, generateAbstractly, propertyGenerationBehavior, cancellationToken));
} }
private IMethodSymbol GenerateGetAccessor( private IMethodSymbol? GenerateGetAccessor(
Compilation compilation, Compilation compilation,
IPropertySymbol property, IPropertySymbol property,
Accessibility accessibility, Accessibility accessibility,
......
...@@ -145,27 +145,6 @@ private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol ...@@ -145,27 +145,6 @@ private void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol
context.ReportDiagnostic( context.ReportDiagnostic(
DiagnosticHelper.Create(Descriptor, throwStatementSyntax.GetLocation(), option.Notification.Severity, additionalLocations: allLocations, properties: null)); DiagnosticHelper.Create(Descriptor, throwStatementSyntax.GetLocation(), option.Notification.Severity, additionalLocations: allLocations, properties: null));
// Fade out the rest of the if that surrounds the 'throw' exception.
var tokenBeforeThrow = throwStatementSyntax.GetFirstToken().GetPreviousToken();
var tokenAfterThrow = throwStatementSyntax.GetLastToken().GetNextToken();
context.ReportDiagnostic(
Diagnostic.Create(UnnecessaryWithSuggestionDescriptor,
Location.Create(syntaxTree, TextSpan.FromBounds(
ifOperation.Syntax.SpanStart,
tokenBeforeThrow.Span.End)),
additionalLocations: allLocations));
if (ifOperation.Syntax.Span.End > tokenAfterThrow.Span.Start)
{
context.ReportDiagnostic(
Diagnostic.Create(UnnecessaryWithSuggestionDescriptor,
Location.Create(syntaxTree, TextSpan.FromBounds(
tokenAfterThrow.Span.Start,
ifOperation.Syntax.Span.End)),
additionalLocations: allLocations));
}
} }
private static bool ValueIsAccessed(SemanticModel semanticModel, IConditionalOperation ifOperation, IBlockOperation containingBlock, ISymbol localOrParameter, IExpressionStatementOperation expressionStatement, IAssignmentOperation assignmentExpression) private static bool ValueIsAccessed(SemanticModel semanticModel, IConditionalOperation ifOperation, IBlockOperation containingBlock, ISymbol localOrParameter, IExpressionStatementOperation expressionStatement, IAssignmentOperation assignmentExpression)
......
...@@ -265,17 +265,18 @@ private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectB ...@@ -265,17 +265,18 @@ private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectB
} }
var syntaxFactory = semanticDocument.Document.GetLanguageService<SyntaxGenerator>(); var syntaxFactory = semanticDocument.Document.GetLanguageService<SyntaxGenerator>();
var delegateInvokeMethod = delegateType.DelegateInvokeMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(semanticDocument.SemanticModel.Compilation.Assembly);
return CodeGenerationSymbolFactory.CreateMethodSymbol( return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default, attributes: default,
accessibility: Accessibility.Private, accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()), modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()),
returnType: delegateType.DelegateInvokeMethod.ReturnType, returnType: delegateInvokeMethod.ReturnType,
refKind: delegateType.DelegateInvokeMethod.RefKind, refKind: delegateInvokeMethod.RefKind,
explicitInterfaceImplementations: default, explicitInterfaceImplementations: default,
name: eventHandlerMethodName, name: eventHandlerMethodName,
typeParameters: default, typeParameters: default,
parameters: delegateType.DelegateInvokeMethod.Parameters, parameters: delegateInvokeMethod.Parameters,
statements: ImmutableArray.Create( statements: ImmutableArray.Create(
CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, semanticDocument, "System.NotImplementedException", cancellationToken))); CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, semanticDocument, "System.NotImplementedException", cancellationToken)));
} }
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities;
...@@ -905,6 +906,59 @@ private void C_MyEvent() ...@@ -905,6 +906,59 @@ private void C_MyEvent()
testState.AssertCodeIs(expectedCode); testState.AssertCodeIs(expectedCode);
} }
[WpfFact, Trait(Traits.Feature, Traits.Features.EventHookup)]
public async Task EventHookupRemovesInaccessibleAttributes()
{
var workspaceXml = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""A"" CommonReferences=""true"">
<Document>
using System;
public static class C
{
public static event DelegateType E;
public delegate void DelegateType([ShouldBeRemovedInternalAttribute] object o);
}
internal class ShouldBeRemovedInternalAttribute : Attribute { }
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"">
<ProjectReference>A</ProjectReference>
<Document>
class D
{
void M()
{
C.E +$$
}
}</Document>
</Project>
</Workspace>";
using var testState = new EventHookupTestState(XElement.Parse(workspaceXml), options: null);
testState.SendTypeChar('=');
testState.SendTab();
await testState.WaitForAsynchronousOperationsAsync();
var expectedCode = @"
class D
{
void M()
{
C.E += C_E;
}
private void C_E(object o)
{
throw new System.NotImplementedException();
}
}";
testState.AssertCodeIs(expectedCode);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.EventHookup)] [WpfFact, Trait(Traits.Feature, Traits.Features.EventHookup)]
public async Task EventHookupWithQualifiedMethodAccessAndNotificationOptionSilent() public async Task EventHookupWithQualifiedMethodAccessAndNotificationOptionSilent()
{ {
......
...@@ -492,13 +492,12 @@ public class P2 { }"); ...@@ -492,13 +492,12 @@ public class P2 { }");
"Generate new type...", "Generate new type...",
"Remove unused variable", "Remove unused variable",
"Configure or Suppress issues", "Configure or Suppress issues",
// https://github.com/dotnet/roslyn/issues/36330 "Configure CS0168 severity",
//"Configure CS0168 severity", "None",
//"None", "Silent",
//"Silent", "Suggestion",
//"Suggestion", "Warning",
//"Warning", "Error",
//"Error",
"Suppress CS0168", "Suppress CS0168",
"in Source" "in Source"
}; };
...@@ -540,13 +539,12 @@ static void Main(string[] args) ...@@ -540,13 +539,12 @@ static void Main(string[] args)
"Generate new type...", "Generate new type...",
"Goober - using N;", "Goober - using N;",
"Configure or Suppress issues", "Configure or Suppress issues",
// https://github.com/dotnet/roslyn/issues/36330 "Configure CS0168 severity",
//"Configure CS0168 severity", "None",
//"None", "Silent",
//"Silent", "Suggestion",
//"Suggestion", "Warning",
//"Warning", "Error",
//"Error",
"Suppress CS0168", "Suppress CS0168",
"in Source", "in Source",
}; };
...@@ -583,13 +581,12 @@ static void Main(string[] args) ...@@ -583,13 +581,12 @@ static void Main(string[] args)
"Extract Method", "Extract Method",
generateImplicitTitle, generateImplicitTitle,
"Configure or Suppress issues", "Configure or Suppress issues",
// https://github.com/dotnet/roslyn/issues/36330 "Configure CS0612 severity",
//"Configure CS0612 severity", "None",
//"None", "Silent",
//"Silent", "Suggestion",
//"Suggestion", "Warning",
//"Warning", "Error",
//"Error",
"Suppress CS0612", "Suppress CS0612",
"in Source", "in Source",
}; };
...@@ -647,7 +644,7 @@ static void Main(string[] args) ...@@ -647,7 +644,7 @@ static void Main(string[] args)
} }
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/36330"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public void ConfigureCodeStyleOptionValueAndSeverity() public void ConfigureCodeStyleOptionValueAndSeverity()
{ {
SetUpEditor(@" SetUpEditor(@"
......
...@@ -428,7 +428,8 @@ public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol> ...@@ -428,7 +428,8 @@ public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol>
ImmutableArray<IParameterSymbol>? parameters = default, ImmutableArray<IParameterSymbol>? parameters = default,
ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> statements = default,
INamedTypeSymbol containingType = null, INamedTypeSymbol containingType = null,
ITypeSymbol returnType = null) ITypeSymbol returnType = null,
Optional<ImmutableArray<AttributeData>> returnTypeAttributes = default)
{ {
return CreateMethodSymbol( return CreateMethodSymbol(
containingType, containingType,
...@@ -442,7 +443,7 @@ public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol> ...@@ -442,7 +443,7 @@ public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol>
method.TypeParameters, method.TypeParameters,
parameters ?? method.Parameters, parameters ?? method.Parameters,
statements, statements,
returnTypeAttributes: method.GetReturnTypeAttributes()); returnTypeAttributes: returnTypeAttributes.HasValue ? returnTypeAttributes.Value : method.GetReturnTypeAttributes());
} }
internal static IPropertySymbol CreatePropertySymbol( internal static IPropertySymbol CreatePropertySymbol(
......
...@@ -101,13 +101,13 @@ public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, ILis ...@@ -101,13 +101,13 @@ public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, ILis
method.GetAttributes(), method.GetAttributes(),
method.DeclaredAccessibility, method.DeclaredAccessibility,
method.GetSymbolModifiers(), method.GetSymbolModifiers(),
method.ReturnType.SubstituteTypes(mapping, typeGenerator), method.GetReturnTypeWithAnnotatedNullability().SubstituteTypes(mapping, typeGenerator),
method.RefKind, method.RefKind,
method.ExplicitInterfaceImplementations, method.ExplicitInterfaceImplementations,
method.Name, method.Name,
updatedTypeParameters, updatedTypeParameters,
method.Parameters.SelectAsArray(p => method.Parameters.SelectAsArray(p =>
CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional, CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.GetTypeWithAnnotatedNullability().SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null))); p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)));
} }
...@@ -206,18 +206,8 @@ public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, ILis ...@@ -206,18 +206,8 @@ public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, ILis
params INamedTypeSymbol[] removeAttributeTypes) params INamedTypeSymbol[] removeAttributeTypes)
{ {
bool shouldRemoveAttribute(AttributeData a) => bool shouldRemoveAttribute(AttributeData a) =>
removeAttributeTypes.Any(attr => attr != null && attr.Equals(a.AttributeClass)) || !a.AttributeClass.IsAccessibleWithin(accessibleWithin); removeAttributeTypes.Any(attr => attr.Equals(a.AttributeClass)) || !a.AttributeClass.IsAccessibleWithin(accessibleWithin);
return method.RemoveAttributesCore(
shouldRemoveAttribute,
statements: default,
handlesExpressions: default);
}
private static IMethodSymbol RemoveAttributesCore(
this IMethodSymbol method, Func<AttributeData, bool> shouldRemoveAttribute,
ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> handlesExpressions)
{
var methodHasAttribute = method.GetAttributes().Any(shouldRemoveAttribute); var methodHasAttribute = method.GetAttributes().Any(shouldRemoveAttribute);
var someParameterHasAttribute = method.Parameters var someParameterHasAttribute = method.Parameters
...@@ -231,23 +221,16 @@ public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, ILis ...@@ -231,23 +221,16 @@ public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, ILis
} }
return CodeGenerationSymbolFactory.CreateMethodSymbol( return CodeGenerationSymbolFactory.CreateMethodSymbol(
method.ContainingType, method,
method.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)), containingType: method.ContainingType,
method.DeclaredAccessibility, explicitInterfaceImplementations: method.ExplicitInterfaceImplementations,
method.GetSymbolModifiers(), attributes: method.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
method.ReturnType, parameters: method.Parameters.SelectAsArray(p =>
method.RefKind,
method.ExplicitInterfaceImplementations,
method.Name,
method.TypeParameters,
method.Parameters.SelectAsArray(p =>
CodeGenerationSymbolFactory.CreateParameterSymbol( CodeGenerationSymbolFactory.CreateParameterSymbol(
p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)), p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional, p.RefKind, p.IsParams, p.GetTypeWithAnnotatedNullability(), p.Name, p.IsOptional,
p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)), p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)),
statements, returnTypeAttributes: method.GetReturnTypeAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)));
handlesExpressions,
method.GetReturnTypeAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)));
} }
public static bool? IsMoreSpecificThan(this IMethodSymbol method1, IMethodSymbol method2) public static bool? IsMoreSpecificThan(this IMethodSymbol method1, IMethodSymbol method2)
......
...@@ -53,11 +53,6 @@ public static IParameterSymbol WithAttributes(this IParameterSymbol parameter, I ...@@ -53,11 +53,6 @@ public static IParameterSymbol WithAttributes(this IParameterSymbol parameter, I
parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null); parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null);
} }
public static ImmutableArray<IParameterSymbol> WithAttributesToBeCopied(
this ImmutableArray<IParameterSymbol> parameters, INamedTypeSymbol containingType)
=> parameters.SelectAsArray(
p => p.WithAttributes(p.GetAttributes().WhereAsArray(a => a.ShouldKeepAttribute(containingType))));
public static ImmutableArray<IParameterSymbol> RenameParameters(this IList<IParameterSymbol> parameters, IList<string> parameterNames) public static ImmutableArray<IParameterSymbol> RenameParameters(this IList<IParameterSymbol> parameters, IList<string> parameterNames)
{ {
var result = ArrayBuilder<IParameterSymbol>.GetInstance(); var result = ArrayBuilder<IParameterSymbol>.GetInstance();
...@@ -68,8 +63,5 @@ public static ImmutableArray<IParameterSymbol> RenameParameters(this IList<IPara ...@@ -68,8 +63,5 @@ public static ImmutableArray<IParameterSymbol> RenameParameters(this IList<IPara
return result.ToImmutableAndFree(); return result.ToImmutableAndFree();
} }
private static bool ShouldKeepAttribute(this AttributeData attributeData, INamedTypeSymbol containingType)
=> attributeData.AttributeClass.IsAccessibleWithin(containingType);
} }
} }
...@@ -37,16 +37,11 @@ public static IPropertySymbol RenameParameters(this IPropertySymbol property, IL ...@@ -37,16 +37,11 @@ public static IPropertySymbol RenameParameters(this IPropertySymbol property, IL
property.IsIndexer); property.IsIndexer);
} }
public static IPropertySymbol RemoveAttributeFromParameters( public static IPropertySymbol RemoveInaccessibleAttributesAndAttributesOfTypes(
this IPropertySymbol property, INamedTypeSymbol?[]? attributesToRemove) this IPropertySymbol property, ISymbol accessibleWithin, params INamedTypeSymbol[] attributesToRemove)
{ {
if (attributesToRemove == null)
{
return property;
}
bool shouldRemoveAttribute(AttributeData a) => bool shouldRemoveAttribute(AttributeData a) =>
attributesToRemove.Any(attr => attr?.Equals(a.AttributeClass) ?? false); attributesToRemove.Any(attr => attr.Equals(a.AttributeClass)) || !a.AttributeClass.IsAccessibleWithin(accessibleWithin);
var someParameterHasAttribute = property.Parameters var someParameterHasAttribute = property.Parameters
.Any(p => p.GetAttributes().Any(shouldRemoveAttribute)); .Any(p => p.GetAttributes().Any(shouldRemoveAttribute));
...@@ -67,7 +62,7 @@ public static IPropertySymbol RenameParameters(this IPropertySymbol property, IL ...@@ -67,7 +62,7 @@ public static IPropertySymbol RenameParameters(this IPropertySymbol property, IL
property.Parameters.SelectAsArray(p => property.Parameters.SelectAsArray(p =>
CodeGenerationSymbolFactory.CreateParameterSymbol( CodeGenerationSymbolFactory.CreateParameterSymbol(
p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)), p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional, p.RefKind, p.IsParams, p.GetTypeWithAnnotatedNullability(), p.Name, p.IsOptional,
p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)), p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)),
property.GetMethod, property.GetMethod,
property.SetMethod, property.SetMethod,
......
...@@ -426,7 +426,7 @@ private static SyntaxNode CreateNewArgumentNullException(SyntaxGenerator factory ...@@ -426,7 +426,7 @@ private static SyntaxNode CreateNewArgumentNullException(SyntaxGenerator factory
accessibility: overriddenProperty.ComputeResultantAccessibility(containingType), accessibility: overriddenProperty.ComputeResultantAccessibility(containingType),
modifiers: modifiers, modifiers: modifiers,
name: overriddenProperty.Name, name: overriddenProperty.Name,
parameters: overriddenProperty.Parameters.WithAttributesToBeCopied(containingType), parameters: overriddenProperty.RemoveInaccessibleAttributesAndAttributesOfTypes(containingType).Parameters,
isIndexer: overriddenProperty.IsIndexer(), isIndexer: overriddenProperty.IsIndexer(),
getMethod: accessorGet, getMethod: accessorGet,
setMethod: accessorSet); setMethod: accessorSet);
...@@ -525,10 +525,9 @@ private static DeclarationModifiers GetOverrideModifiers(ISymbol symbol) ...@@ -525,10 +525,9 @@ private static DeclarationModifiers GetOverrideModifiers(ISymbol symbol)
} }
return CodeGenerationSymbolFactory.CreateMethodSymbol( return CodeGenerationSymbolFactory.CreateMethodSymbol(
method: overriddenMethod, method: overriddenMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(newContainingType),
accessibility: overriddenMethod.ComputeResultantAccessibility(newContainingType), accessibility: overriddenMethod.ComputeResultantAccessibility(newContainingType),
modifiers: modifiers, modifiers: modifiers,
parameters: overriddenMethod.Parameters.WithAttributesToBeCopied(newContainingType),
statements: overriddenMethod.ReturnsVoid statements: overriddenMethod.ReturnsVoid
? ImmutableArray.Create(codeFactory.ExpressionStatement(body)) ? ImmutableArray.Create(codeFactory.ExpressionStatement(body))
: ImmutableArray.Create(codeFactory.ReturnStatement(body))); : ImmutableArray.Create(codeFactory.ReturnStatement(body)));
......
...@@ -365,7 +365,7 @@ private static bool IsPrimitiveValueType(ITypeSymbol typeSymbol) ...@@ -365,7 +365,7 @@ private static bool IsPrimitiveValueType(ITypeSymbol typeSymbol)
ITypeSymbol type) ITypeSymbol type)
{ {
var equalityComparerType = compilation.EqualityComparerOfTType(); var equalityComparerType = compilation.EqualityComparerOfTType();
var constructedType = equalityComparerType.Construct(type); var constructedType = equalityComparerType.ConstructWithNullability(type);
return factory.MemberAccessExpression( return factory.MemberAccessExpression(
factory.TypeExpression(constructedType), factory.TypeExpression(constructedType),
factory.IdentifierName(DefaultName)); factory.IdentifierName(DefaultName));
...@@ -375,8 +375,8 @@ private static ITypeSymbol GetType(Compilation compilation, ISymbol symbol) ...@@ -375,8 +375,8 @@ private static ITypeSymbol GetType(Compilation compilation, ISymbol symbol)
{ {
switch (symbol) switch (symbol)
{ {
case IFieldSymbol field: return field.Type; case IFieldSymbol field: return field.GetTypeWithAnnotatedNullability();
case IPropertySymbol property: return property.Type; case IPropertySymbol property: return property.GetTypeWithAnnotatedNullability();
default: return compilation.GetSpecialType(SpecialType.System_Object); default: return compilation.GetSpecialType(SpecialType.System_Object);
} }
} }
......
...@@ -353,7 +353,7 @@ private static bool SymbolsAreCompatibleCore(ISymbol symbol, ISymbol newSymbol, ...@@ -353,7 +353,7 @@ private static bool SymbolsAreCompatibleCore(ISymbol symbol, ISymbol newSymbol,
} }
} }
if (symbol.Equals(newSymbol)) if (symbol.Equals(newSymbol, SymbolEqualityComparer.IncludeNullability))
{ {
return true; return true;
} }
......
...@@ -187,7 +187,9 @@ public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel sem ...@@ -187,7 +187,9 @@ public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel sem
public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null)
{ {
return WrappedSymbol.ToMinimalDisplayParts(semanticModel, position, format); // Call the right API once https://github.com/dotnet/roslyn/pull/35698 is merged
var convertedFlowState = Nullability == NullableAnnotation.Annotated ? NullableFlowState.MaybeNull : NullableFlowState.None;
return WrappedSymbol.ToMinimalDisplayParts(semanticModel, convertedFlowState, position, format);
} }
public string ToMinimalDisplayString(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null) public string ToMinimalDisplayString(SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format = null)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册