提交 a3ba9563 编写于 作者: V VSadov

Add code fixes for a number of our FxCop diagnostics. (changeset 1282258)

上级 fe4fe6e1
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="Settings">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Settings.targets" />
<Import Project="..\..\..\..\packages\Microsoft.Net.ToolsetCompilers.0.7.4032713-beta\build\Microsoft.Net.ToolsetCompilers.props" Condition="Exists('..\..\..\..\packages\Microsoft.Net.ToolsetCompilers.0.7.4032713-beta\build\Microsoft.Net.ToolsetCompilers.props')" />
</ImportGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{EDA725D2-1125-4F43-91FF-4837157F9C4B}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RunStyleCop>true</RunStyleCop>
<RootNamespace>Microsoft.CodeAnalysis.CSharp.FxCopDiagnosticFixers</RootNamespace>
<AssemblyName>Microsoft.CodeAnalysis.CSharp.FxCopDiagnosticFixers</AssemblyName>
<SolutionDir Condition="'$(SolutionDir)' == '' OR '$(SolutionDir)' == '*Undefined*'">..\..\..\..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<OutDir>..\..\..\..\..\Binaries\$(Configuration)\</OutDir>
</PropertyGroup>
<ItemGroup Label="File References">
<Reference Include="System.Collections.Immutable">
<HintPath>..\..\..\packages\Microsoft.Bcl.Immutable.1.1.20-beta\lib\portable-net45+win8\System.Collections.Immutable.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}</Project>
<Name>CodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\CSharpCodeAnalysis.csproj">
<Project>{B501A547-C911-4A05-AC6E-274A50DFF30E}</Project>
<Name>CSharpCodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Diagnostics\FxCop\Core\FxCopRulesDiagnosticAnalyzers.csproj">
<Project>{36755424-5267-478C-9434-37A507E22711}</Project>
<Name>FxCopRulesDiagnosticAnalyzers</Name>
</ProjectReference>
<ProjectReference Include="..\Core\FxCopRulesDiagnosticFixers.csproj">
<Project>{C87731D2-4A0A-4883-961D-745262E3CD6A}</Project>
<Name>FxCopRulesDiagnosticFixers</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\Core\Workspaces.csproj">
<Project>{5F8D2414-064A-4B3A-9B42-8E2A04246BE5}</Project>
<Name>Workspaces</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Diagnostics\FxCop\CSharp\CSharpFxCopRulesDiagnosticAnalyzers.csproj">
<Project>{3BA13187-2A3B-4B08-9199-C11FDA1D5AD0}</Project>
<Name>CSharpFxCopRulesDiagnosticAnalyzers</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "></PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "></PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Collections" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="Design\CA1001CSharpCodeFixProvider.cs" />
<Compile Include="Design\CA1008CSharpCodeFixProvider.cs" />
<Compile Include="Design\CA1052CSharpCodeFixProvider.cs" />
<Compile Include="Design\EnumWithFlagsCSharpCodeFixProvider.cs" />
<Compile Include="Globalization\CA1309CSharpCodeFixProvider.cs" />
<Compile Include="Globalization\CA2101CSharpCodeFixProvider.cs" />
<Compile Include="Performance\CA1813CSharpCodeFixProvider.cs" />
<Compile Include="Usage\CA2213CSharpCodeFixProvider.cs" />
<Compile Include="Usage\CA2231CSharpCodeFixProvider.cs" />
<Compile Include="Usage\CA2235CSharpCodeFixProvider.cs" />
</ItemGroup>
<ItemGroup />
<ImportGroup Label="Targets">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
</Project>
\ No newline at end of file
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design
{
/// <summary>
/// CA1001: Types that own disposable fields should be disposable
/// </summary>
[ExportCodeFixProvider(CA1001DiagnosticAnalyzer.RuleId, LanguageNames.CSharp)]
public class CA1001CSharpCodeFixProvider : CA1001CodeFixProviderBase
{
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
//// We are going to implement IDisposable interface:
////
//// public void Dispose()
//// {
//// throw new NotImplementedException();
//// }
var syntaxNode = nodeToFix as ClassDeclarationSyntax;
if (syntaxNode == null)
{
return Task.FromResult(document);
}
var statement = CreateThrowNotImplementedStatement(model);
if (statement == null)
{
return Task.FromResult(document);
}
var member = CreateSimpleMethodDeclaration(CA1001DiagnosticAnalyzer.Dispose, statement);
var newNode =
syntaxNode.BaseList != null ?
syntaxNode.AddBaseListTypes(SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable)).AddMembers(new[] { member }) :
syntaxNode.AddBaseListTypes(SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable)).AddMembers(new[] { member }).WithIdentifier(syntaxNode.Identifier.WithTrailingTrivia(SyntaxFactory.Space));
newNode = newNode.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(nodeToFix, newNode)));
}
protected StatementSyntax CreateThrowNotImplementedStatement(SemanticModel model)
{
var exceptionType = model.Compilation.GetTypeByMetadataName(NotImplementedExceptionName);
if (exceptionType == null)
{
// If we can't find the exception, we can't generate anything.
return null;
}
return SyntaxFactory.ThrowStatement(
SyntaxFactory.ObjectCreationExpression(
SyntaxFactory.Token(SyntaxKind.NewKeyword),
SyntaxFactory.IdentifierName(exceptionType.Name),
SyntaxFactory.ArgumentList(),
null));
}
protected MethodDeclarationSyntax CreateSimpleMethodDeclaration(string name, StatementSyntax statement)
{
return SyntaxFactory.MethodDeclaration(
new SyntaxList<AttributeListSyntax>(),
SyntaxFactory.TokenList(new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword) }),
SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
null,
SyntaxFactory.Identifier(name),
null,
SyntaxFactory.ParameterList(),
new SyntaxList<TypeParameterConstraintClauseSyntax>(),
SyntaxFactory.Block(statement),
new SyntaxToken());
}
}
}
\ No newline at end of file
using System.Linq;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design
{
/// <summary>
/// CA1008: Enums should have zero value
/// </summary>
[ExportCodeFixProvider("CA1008", LanguageNames.CSharp)]
public class CA1008CSharpCodeFixProvider : CA1008CodeFixProviderBase
{
internal override SyntaxNode GetFieldInitializer(IFieldSymbol field)
{
if (field.DeclaringSyntaxReferences.Length == 0)
{
return null;
}
var syntax = field.DeclaringSyntaxReferences.First().GetSyntax();
var enumMemberSyntax = syntax as EnumMemberDeclarationSyntax;
return enumMemberSyntax == null ? null : enumMemberSyntax.EqualsValue;
}
internal override SyntaxNode CreateConstantValueInitializer(SyntaxNode constantValueExpression)
{
return SyntaxFactory.EqualsValueClause((ExpressionSyntax)constantValueExpression);
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design
{
[ExportCodeFixProvider(StaticTypeRulesDiagnosticAnalyzer.CA1052RuleId, LanguageNames.CSharp)]
public class CA1052CSharpCodeFixProvider : ICodeFixProvider
{
public IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(StaticTypeRulesDiagnosticAnalyzer.CA1052RuleId);
}
public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var root = await document.GetSyntaxRootAsync(cancellationToken);
var classDeclaration = root.FindToken(span.Start).GetAncestor<ClassDeclarationSyntax>();
if (classDeclaration != null)
{
var staticKeyword = SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithAdditionalAnnotations(Formatter.Annotation);
var newDeclaration = classDeclaration.AddModifiers(staticKeyword);
var newRoot = root.ReplaceNode(classDeclaration, newDeclaration);
return SpecializedCollections.SingletonEnumerable(
CodeAction.Create(string.Format(FxCopRulesResources.StaticHolderTypeIsNotStatic, classDeclaration.Identifier.Text), document.WithSyntaxRoot(newRoot)));
}
return null;
}
}
}
using System.Threading;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design
{
/// <summary>
/// CA1027: Mark enums with FlagsAttribute
/// CA2217: Do not mark enums with FlagsAttribute
/// </summary>
[ExportCodeFixProvider(EnumWithFlagsDiagnosticAnalyzer.RuleNameForExportAttribute, LanguageNames.CSharp)]
public class EnumWithFlagsCSharpCodeFixProvider : EnumWithFlagsCodeFixProviderBase
{
}
}
\ No newline at end of file
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Globalization;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Globalization
{
[ExportCodeFixProvider(CA1309DiagnosticAnalyzer.RuleId, LanguageNames.CSharp)]
public class CA1309CSharpCodeFixProvider : CA1309CodeFixProviderBase
{
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
// if nothing can be fixed, return the unchanged node
var newRoot = root;
var kind = nodeToFix.CSharpKind();
var syntaxFactoryService = document.GetLanguageService<ISyntaxFactoryService>();
switch (kind)
{
case SyntaxKind.Argument:
// StringComparison.CurrentCulture => StringComparison.Ordinal
// StringComparison.CurrentCultureIgnoreCase => StringComparison.OrdinalIgnoreCase
var argument = (ArgumentSyntax)nodeToFix;
var memberAccess = argument.Expression as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
// preserve the "IgnoreCase" suffix if present
bool isIgnoreCase = memberAccess.Name.GetText().ToString().EndsWith(CA1309DiagnosticAnalyzer.IgnoreCaseText);
var newOrdinalText = isIgnoreCase ? CA1309DiagnosticAnalyzer.OrdinalIgnoreCaseText : CA1309DiagnosticAnalyzer.OrdinalText;
var newIdentifier = syntaxFactoryService.CreateIdentifierName(newOrdinalText);
var newMemberAccess = memberAccess.WithName((SimpleNameSyntax)newIdentifier).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(memberAccess, newMemberAccess);
}
break;
case SyntaxKind.IdentifierName:
// string.Equals(a, b) => string.Equals(a, b, StringComparison.Ordinal)
// string.Compare(a, b) => string.Compare(a, b, StringComparison.Ordinal)
var identifier = (IdentifierNameSyntax)nodeToFix;
var invokeParent = identifier.GetAncestor<InvocationExpressionSyntax>();
if (invokeParent != null)
{
var methodSymbol = model.GetSymbolInfo(identifier).Symbol as IMethodSymbol;
if (methodSymbol != null && CanAddStringComparison(methodSymbol))
{
// append a new StringComparison.Ordinal argument
var newArg = syntaxFactoryService.CreateArgument(CreateOrdinalMemberAccess(syntaxFactoryService, model))
.WithAdditionalAnnotations(Formatter.Annotation);
var newInvoke = invokeParent.AddArgumentListArguments((ArgumentSyntax)newArg).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(invokeParent, newInvoke);
}
}
break;
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
// "a == b" => "string.Equals(a, b, StringComparison.Ordinal)"
// "a != b" => "!string.Equals(a, b, StringComparison.Ordinal)"
var binaryExpression = (BinaryExpressionSyntax)nodeToFix;
var invocation = CreateEqualsExpression(syntaxFactoryService, model, binaryExpression.Left, binaryExpression.Right, kind == SyntaxKind.EqualsExpression).WithAdditionalAnnotations(Formatter.Annotation);
newRoot = root.ReplaceNode(nodeToFix, invocation);
break;
}
if (newRoot == root)
{
return Task.FromResult(document);
}
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
}
}
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Globalization;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Interoperability;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Utilities;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Globalization
{
[ExportCodeFixProvider(PInvokeDiagnosticAnalyzer.CA2101, LanguageNames.CSharp)]
public class CA2101CSharpCodeFixProvider : CA2101CodeFixProviderBase
{
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var charSetType = WellKnownTypes.CharSet(model.Compilation);
var dllImportType = WellKnownTypes.DllImportAttribute(model.Compilation);
var marshalAsType = WellKnownTypes.MarshalAsAttribute(model.Compilation);
var unmanagedType = WellKnownTypes.UnmanagedType(model.Compilation);
if (charSetType == null || dllImportType == null || marshalAsType == null || unmanagedType == null)
{
return Task.FromResult(document);
}
var syntaxFactoryService = document.Project.LanguageServices.GetService<ISyntaxFactoryService>();
// return the unchanged root if no fix is available
var newRoot = root;
if (nodeToFix.CSharpKind() == SyntaxKind.Attribute)
{
// could be either a [DllImport] or [MarshalAs] attribute
var attribute = (AttributeSyntax)nodeToFix;
var attributeType = model.GetSymbolInfo(attribute).Symbol;
var arguments = attribute.ArgumentList.Arguments;
if (dllImportType.Equals(attributeType.ContainingType))
{
// [DllImport] attribute, add or replace CharSet named parameter
var argumentValue = CreateCharSetArgument(syntaxFactoryService, charSetType).WithAdditionalAnnotations(Formatter.Annotation);
var namedParameter = arguments.FirstOrDefault(arg => arg.NameEquals != null && arg.NameEquals.Name.Identifier.Text == CharSetText);
if (namedParameter == null)
{
// add the parameter
namedParameter = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(CharSetText), null, (ExpressionSyntax)argumentValue)
.WithAdditionalAnnotations(Formatter.Annotation);
var newArguments = arguments.Add(namedParameter);
var newArgumentList = attribute.ArgumentList.WithArguments(newArguments);
newRoot = root.ReplaceNode(attribute.ArgumentList, newArgumentList);
}
else
{
// replace the parameter
var newNamedParameter = namedParameter.WithExpression((ExpressionSyntax)argumentValue);
newRoot = root.ReplaceNode(namedParameter, newNamedParameter);
}
}
else if (marshalAsType.Equals(attributeType.ContainingType) && arguments.Count == 1)
{
// [MarshalAs] attribute, replace the only argument
var newExpression = CreateMarshalAsArgument(syntaxFactoryService, unmanagedType)
.WithLeadingTrivia(arguments[0].GetLeadingTrivia())
.WithTrailingTrivia(arguments[0].GetTrailingTrivia());
var newArgument = arguments[0].WithExpression((ExpressionSyntax)newExpression);
newRoot = root.ReplaceNode(arguments[0], newArgument);
}
}
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
}
}
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Performance;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Performance
{
/// <summary>
/// CA1813: Seal attribute types for improved performance. Sealing attribute types speeds up performance during reflection on custom attributes.
/// </summary>
[ExportCodeFixProvider(CA1813DiagnosticAnalyzer.RuleId, LanguageNames.CSharp)]
public class CA1813CSharpCodeFixProvider : CA1813CodeFixProviderBase
{
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
var attributeSyntax = nodeToFix as ClassDeclarationSyntax;
if (attributeSyntax != null)
{
// TODO : Organize the modifiers list after adding sealed modifier.
var sealedModifier = SyntaxFactory.Token(SyntaxKind.SealedKeyword);
var newAttributeSyntax = attributeSyntax
.WithModifiers(attributeSyntax.Modifiers.Add(sealedModifier))
.WithAdditionalAnnotations(Formatter.Annotation);
document = document.WithSyntaxRoot(root.ReplaceNode(attributeSyntax, newAttributeSyntax));
}
return Task.FromResult(document);
}
}
}
\ No newline at end of file
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Usage;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Usage
{
/// <summary>
/// CA2213: Disposable fields should be disposed
/// </summary>
[ExportCodeFixProvider(CA2213DiagnosticAnalyzer.RuleId, LanguageNames.CSharp)]
public class CA2213CSharpCodeFixProvider : CA2213CodeFixProviderBase
{
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
//// We are going to add a call Dispose on fields:
////
//// public void Dispose()
//// {
//// A.Dispose();
//// ...
//// }
var syntaxNode = nodeToFix as VariableDeclaratorSyntax;
if (syntaxNode == null)
{
return Task.FromResult(document);
}
// find a Dispose method
var member = syntaxNode.FirstAncestorOrSelf<ClassDeclarationSyntax>()
.DescendantNodes().OfType<MethodDeclarationSyntax>()
.Where(n => n.Identifier.ValueText == CA2213DiagnosticAnalyzer.Dispose).FirstOrDefault();
if (member == null)
{
return Task.FromResult(document);
}
var factory = document.GetLanguageService<ISyntaxFactoryService>();
var symbol = model.GetDeclaredSymbol(syntaxNode);
// handle a case where a local in the Dipose method with the same name by generating this (or ClassName) and simplifying it
var path = symbol.IsStatic
? factory.CreateIdentifierName(symbol.ContainingType.MetadataName)
: factory.CreateThisExpression();
var statement =
factory.CreateExpressionStatement(
factory.CreateInvocationExpression(
factory.CreateMemberAccessExpression(
factory.CreateMemberAccessExpression(path, factory.CreateIdentifierName(symbol.Name)).WithAdditionalAnnotations(Simplification.Simplifier.Annotation),
factory.CreateIdentifierName(CA2213DiagnosticAnalyzer.Dispose))));
var newMember = member.AddBodyStatements((StatementSyntax)statement).WithAdditionalAnnotations(Formatter.Annotation);
return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(member, newMember)));
}
}
}
\ No newline at end of file
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Usage;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Usage
{
/// <summary>
/// CA2231: Overload operator equals on overriding ValueType.Equals
/// </summary>
[ExportCodeFixProvider(CA2231DiagnosticAnalyzer.RuleId, LanguageNames.CSharp)]
public class CA2231CSharpCodeFixProvider : CA2231CodeFixProviderBase
{
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
//// We are going to add two operators:
////
//// public static bool operator ==(A left, A right)
//// {
//// throw new NotImplementedException();
//// }
////
//// public static bool operator !=(A left, A right)
//// {
//// throw new NotImplementedException();
//// }
var syntaxNode = nodeToFix as StructDeclarationSyntax;
if (syntaxNode == null)
{
return Task.FromResult(document);
}
var statement = CreateThrowNotImplementedStatement(model);
if (statement == null)
{
return Task.FromResult(document);
}
var parameters = new[] { CreateParameter(syntaxNode.Identifier.ValueText, LeftName), CreateParameter(syntaxNode.Identifier.ValueText, RightName) };
var op_equality = CreateOperatorDeclaration(SyntaxKind.EqualsEqualsToken, parameters, statement);
var op_inequality = CreateOperatorDeclaration(SyntaxKind.ExclamationEqualsToken, parameters, statement);
var newNode = syntaxNode.AddMembers(new[] { op_equality, op_inequality }).WithAdditionalAnnotations(Formatter.Annotation);
return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(nodeToFix, newNode)));
}
protected StatementSyntax CreateThrowNotImplementedStatement(SemanticModel model)
{
var exceptionType = model.Compilation.GetTypeByMetadataName(NotImplementedExceptionName);
if (exceptionType == null)
{
// If we can't find the exception, we can't generate anything.
return null;
}
return SyntaxFactory.ThrowStatement(
SyntaxFactory.ObjectCreationExpression(
SyntaxFactory.Token(SyntaxKind.NewKeyword),
SyntaxFactory.IdentifierName(exceptionType.Name),
SyntaxFactory.ArgumentList(),
null));
}
protected ParameterSyntax CreateParameter(string type, string name)
{
return SyntaxFactory.Parameter(
new SyntaxList<AttributeListSyntax>(),
SyntaxFactory.TokenList(),
SyntaxFactory.ParseTypeName(type),
SyntaxFactory.IdentifierName(name).Identifier,
null);
}
protected OperatorDeclarationSyntax CreateOperatorDeclaration(SyntaxKind kind, ParameterSyntax[] parameters, StatementSyntax statement)
{
return SyntaxFactory.OperatorDeclaration(
new SyntaxList<AttributeListSyntax>(),
SyntaxFactory.TokenList(new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword) }),
SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
SyntaxFactory.Token(kind),
SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)),
SyntaxFactory.Block(statement),
new SyntaxToken());
}
}
}
\ No newline at end of file
using System;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Usage;
namespace Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Usage
{
[ExportCodeFixProvider("CA2237 CodeFix provider", LanguageNames.CSharp)]
public class CA2235CSharpCodeFixProvider : CA2235CodeFixProviderBase
{
protected override SyntaxNode GetFieldDeclarationNode(SyntaxNode node)
{
var fieldNode = node;
while (fieldNode != null && fieldNode.CSharpKind() != SyntaxKind.FieldDeclaration)
{
fieldNode = fieldNode.Parent;
}
return fieldNode.CSharpKind() == SyntaxKind.FieldDeclaration ? fieldNode : null;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl.Immutable" version="1.1.20-beta" targetFramework="net45" />
<package id="Microsoft.Net.ToolsetCompilers" version="0.7.4032713-beta" targetFramework="net45" developmentDependency="true" />
</packages>
\ No newline at end of file
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers
{
public abstract class CodeFixProviderBase : ICodeFixProvider
{
protected abstract string GetCodeFixDescription(string ruleId);
public abstract IEnumerable<string> GetFixableDiagnosticIds();
internal abstract Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken);
async Task<IEnumerable<CodeAction>> ICodeFixProvider.GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var actions = SpecializedCollections.EmptyEnumerable<CodeAction>();
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
var nodeToFix = root.FindNode(diagnostic.Location.SourceSpan);
var newDocument = await GetUpdatedDocumentAsync(document, model, root, nodeToFix, diagnostic.Id, cancellationToken).ConfigureAwait(false);
Debug.Assert(newDocument != null);
if (newDocument != document)
{
var codeFixDescription = GetCodeFixDescription(diagnostic.Id);
actions = actions.Concat(CodeAction.Create(codeFixDescription, newDocument));
}
}
return actions;
}
}
}
using System.Collections.Generic;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Design
{
/// <summary>
/// CA1001: Types that own disposable fields should be disposable
/// </summary>
public abstract class CA1001CodeFixProviderBase : CodeFixProviderBase
{
protected const string NotImplementedExceptionName = "System.NotImplementedException";
protected const string IDisposableName = "System.IDisposable";
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(CA1001DiagnosticAnalyzer.RuleId);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.ImplementIDisposableInterface;
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Design
{
/// <summary>
/// CA1008: Enums should have zero value
/// </summary>
public abstract class CA1008CodeFixProviderBase : CodeFixProviderBase
{
// TODO: Fix this code fix provider
////private readonly IEnumerable<string> diagnosticIds = ImmutableArray.Create(CA1008DiagnosticAnalyzer.RuleNameRename,
//// CA1008DiagnosticAnalyzer.RuleNameMultipleZero,
//// CA1008DiagnosticAnalyzer.RuleNameNoZeroValue);
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
////return diagnosticIds;
return SpecializedCollections.EmptyEnumerable<string>();
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
////switch (ruleId)
////{
//// case CA1008DiagnosticAnalyzer.RuleNameRename:
//// return FxCopFixersResources.EnumsShouldZeroValueFlagsRenameCodeFix;
//// case CA1008DiagnosticAnalyzer.RuleNameMultipleZero:
//// return FxCopFixersResources.EnumsShouldZeroValueFlagsMultipleZeroCodeFix;
//// case CA1008DiagnosticAnalyzer.RuleNameNoZeroValue:
//// return FxCopFixersResources.EnumsShouldZeroValueNotFlagsNoZeroValueCodeFix;
//// default:
//// throw Contract.Unreachable;
////}
throw new NotImplementedException();
}
internal abstract SyntaxNode GetFieldInitializer(IFieldSymbol field);
internal abstract SyntaxNode CreateConstantValueInitializer(SyntaxNode constantValueExpression);
private IFieldSymbol GetExplicitlyAssignedField(IFieldSymbol originalField, ISyntaxFactoryService syntaxFactoryService)
{
var originalInitializer = GetFieldInitializer(originalField);
if (originalInitializer != null || !originalField.HasConstantValue)
{
return originalField;
}
var constantValueExpression = syntaxFactoryService.CreateConstantExpression(originalField.ConstantValue);
var newInitializer = CreateConstantValueInitializer(constantValueExpression);
return CodeGenerationSymbolFactory.CreateFieldSymbol(originalField.GetAttributes(), originalField.DeclaredAccessibility, originalField.GetSymbolModifiers(),
originalField.Type, originalField.Name, originalField.HasConstantValue, originalField.ConstantValue, newInitializer);
}
private IList<ISymbol> GetNewFieldsForRuleNameRename(INamedTypeSymbol enumType, IFieldSymbol zeroValuedField)
{
// Diagnostic: In enum '{0}', change the name of '{1}' to 'None'.
// Fix: Rename zero-valued enum field to 'None'.
var newFields = new List<ISymbol>();
foreach (IFieldSymbol field in enumType.GetMembers().Where(m => m.Kind == SymbolKind.Field))
{
if (field != zeroValuedField)
{
newFields.Add(field);
}
else
{
var newInitializer = GetFieldInitializer(field);
var newField = CodeGenerationSymbolFactory.CreateFieldSymbol(field.GetAttributes(), field.DeclaredAccessibility, field.GetSymbolModifiers(),
field.Type, "None", field.HasConstantValue, field.ConstantValue, newInitializer);
newFields.Add(newField);
}
}
return newFields;
}
private Task<Document> GetUpdatedDocumentForRuleNameRename(Document document, SyntaxNode root, SyntaxNode nodeToFix, INamedTypeSymbol enumType, IEnumerable<IFieldSymbol> zeroValuedFields, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(zeroValuedFields.Count() == 1);
var zeroValuedField = zeroValuedFields.Single();
Contract.ThrowIfTrue(CA1008DiagnosticAnalyzer.IsMemberNamedNone(zeroValuedField));
var newFields = GetNewFieldsForRuleNameRename(enumType, zeroValuedField);
return GetUpdatedDocumentWithFix(document, root, nodeToFix, newFields, cancellationToken);
}
private IList<ISymbol> GetNewFieldsForRuleNameMultipleZero(INamedTypeSymbol enumType, IEnumerable<IFieldSymbol> zeroValuedFields, ISyntaxFactoryService syntaxFactoryService)
{
// Diagnostic: Remove all members that have the value zero from '{0}' except for one member that is named 'None'.
// Fix: Remove all members that have the value zero except for one member that is named 'None'.
bool needsNewZeroValuedNoneField = true;
var set = zeroValuedFields.ToSet();
bool makeNextFieldExplicit = false;
var newFields = new List<ISymbol>();
foreach (IFieldSymbol field in enumType.GetMembers().Where(m => m.Kind == SymbolKind.Field))
{
var isZeroValued = set.Contains(field);
var isZeroValuedNamedNone = isZeroValued && CA1008DiagnosticAnalyzer.IsMemberNamedNone(field);
if (!isZeroValued || isZeroValuedNamedNone)
{
var newField = field;
if (makeNextFieldExplicit)
{
newField = GetExplicitlyAssignedField(field, syntaxFactoryService);
makeNextFieldExplicit = false;
}
newFields.Add(newField);
if (isZeroValuedNamedNone)
{
needsNewZeroValuedNoneField = false;
}
}
else
{
makeNextFieldExplicit = true;
}
}
if (needsNewZeroValuedNoneField)
{
var firstZeroValuedField = zeroValuedFields.First();
var constantValueExpression = syntaxFactoryService.CreateConstantExpression(firstZeroValuedField.ConstantValue);
var newInitializer = CreateConstantValueInitializer(constantValueExpression);
var newField = CodeGenerationSymbolFactory.CreateFieldSymbol(firstZeroValuedField.GetAttributes(), firstZeroValuedField.DeclaredAccessibility, firstZeroValuedField.GetSymbolModifiers(),
firstZeroValuedField.Type, "None", firstZeroValuedField.HasConstantValue, firstZeroValuedField.ConstantValue, newInitializer);
newFields.Insert(0, newField);
}
return newFields;
}
private Task<Document> GetUpdatedDocumentForRuleNameMultipleZero(Document document, SyntaxNode root, SyntaxNode nodeToFix, INamedTypeSymbol enumType, IEnumerable<IFieldSymbol> zeroValuedFields, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(zeroValuedFields.Count() > 1);
var syntaxFactoryService = document.GetLanguageService<ISyntaxFactoryService>();
var newFields = GetNewFieldsForRuleNameMultipleZero(enumType, zeroValuedFields, syntaxFactoryService);
return GetUpdatedDocumentWithFix(document, root, nodeToFix, newFields, cancellationToken);
}
private IList<ISymbol> GetNewFieldsForRuleNameNoZeroValue(INamedTypeSymbol enumType, ISyntaxFactoryService syntaxFactoryService)
{
// Diagnostic: Add a member to '{0}' that has a value of zero with a suggested name of 'None'.
// Fix: Add a zero-valued member 'None' to enum.
var newFields = new List<ISymbol>();
var constantValueExpression = syntaxFactoryService.CreateConstantExpression(0);
var newInitializer = CreateConstantValueInitializer(constantValueExpression);
var newField = CodeGenerationSymbolFactory.CreateFieldSymbol(SpecializedCollections.EmptyList<AttributeData>(), Accessibility.Public,
default(SymbolModifiers), enumType.EnumUnderlyingType, "None", true, 0, newInitializer);
newFields.Add(newField);
foreach (var member in enumType.GetMembers())
{
if (!CA1008DiagnosticAnalyzer.IsMemberNamedNone(member))
{
newFields.Add(member);
}
}
return newFields;
}
private Task<Document> GetUpdatedDocumentForRuleNameNoZeroValue(Document document, SyntaxNode root, SyntaxNode nodeToFix, INamedTypeSymbol enumType, CancellationToken cancellationToken)
{
var syntaxFactoryService = document.GetLanguageService<ISyntaxFactoryService>();
var newFields = GetNewFieldsForRuleNameNoZeroValue(enumType, syntaxFactoryService);
return GetUpdatedDocumentWithFix(document, root, nodeToFix, newFields, cancellationToken);
}
private Task<Document> GetUpdatedDocumentWithFix(Document document, SyntaxNode root, SyntaxNode nodeToFix, IList<ISymbol> newFields, CancellationToken cancellationToken)
{
var newEnumSyntax = CodeGenerator.UpdateDeclarationMembers(nodeToFix, document.Project.Solution.Workspace, newFields, cancellationToken: cancellationToken)
.WithAdditionalAnnotations(Formatting.Formatter.Annotation);
var newRoot = root.ReplaceNode(nodeToFix, newEnumSyntax);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
internal sealed override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
var enumType = model.GetDeclaredSymbol(nodeToFix, cancellationToken) as INamedTypeSymbol;
Contract.ThrowIfNull(enumType);
switch (diagnosticId)
{
////case CA1008DiagnosticAnalyzer.RuleNameRename:
//// var zeroValuedFields = CA1008DiagnosticAnalyzer.GetZeroValuedFields(enumType);
//// return GetUpdatedDocumentForRuleNameRename(document, root, nodeToFix, enumType, zeroValuedFields, cancellationToken);
////case CA1008DiagnosticAnalyzer.RuleNameMultipleZero:
//// zeroValuedFields = CA1008DiagnosticAnalyzer.GetZeroValuedFields(enumType);
//// return GetUpdatedDocumentForRuleNameMultipleZero(document, root, nodeToFix, enumType, zeroValuedFields, cancellationToken);
////case CA1008DiagnosticAnalyzer.RuleNameNoZeroValue:
//// return GetUpdatedDocumentForRuleNameNoZeroValue(document, root, nodeToFix, enumType, cancellationToken);
default:
throw Contract.Unreachable;
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Design
{
/// <summary>
/// CA1012: Abstract classes should not have public constructors
/// </summary>
[ExportCodeFixProvider(CA1012DiagnosticAnalyzer.RuleId, LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class CA1012CodeFixProvider : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(CA1012DiagnosticAnalyzer.RuleId);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.AbstractTypesShouldNotHavePublicConstructorsCodeFix;
}
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
var classSymbol = (INamedTypeSymbol)model.GetDeclaredSymbol(nodeToFix);
var instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => t.DeclaringSyntaxReferences[0].GetSyntax());
var workspace = document.Project.Solution.Workspace;
Func<SyntaxNode, SyntaxNode, SyntaxNode> replacementForNodes = (constructorNode, dummy) =>
{
var newSyntax = CodeGenerator.UpdateDeclarationAccessibility(constructorNode, workspace, Accessibility.Protected, cancellationToken: cancellationToken).WithAdditionalAnnotations(Formatter.Annotation);
return newSyntax;
};
return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNodes(instanceConstructors, replacementForNodes)));
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Utilities;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Design
{
/// <summary>
/// CA1027: Mark enums with FlagsAttribute
/// CA2217: Do not mark enums with FlagsAttribute
/// </summary>
public abstract class EnumWithFlagsCodeFixProviderBase : CodeFixProviderBase
{
private readonly IEnumerable<string> diagnosticIds = ImmutableArray.Create(EnumWithFlagsDiagnosticAnalyzer.RuleIdMarkEnumsWithFlags,
EnumWithFlagsDiagnosticAnalyzer.RuleIdDoNotMarkEnumsWithFlags);
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return diagnosticIds;
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return ruleId == EnumWithFlagsDiagnosticAnalyzer.RuleIdMarkEnumsWithFlags ?
FxCopFixersResources.MarkEnumsWithFlagsCodeFix :
FxCopFixersResources.DoNotMarkEnumsWithFlagsCodeFix;
}
internal virtual SyntaxNode GetUpdatedRoot(SyntaxNode root, SyntaxNode nodeToFix, SyntaxNode newEnumTypeSyntax)
{
return root.ReplaceNode(nodeToFix, newEnumTypeSyntax);
}
internal sealed override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
var flagsAttributeType = WellKnownTypes.FlagsAttribute(model.Compilation);
Contract.ThrowIfNull(flagsAttributeType);
var workspace = document.Project.Solution.Workspace;
var newEnumBlockSyntax = diagnosticId == EnumWithFlagsDiagnosticAnalyzer.RuleIdMarkEnumsWithFlags ?
AddFlagsAttribute(workspace, nodeToFix, flagsAttributeType, cancellationToken) :
RemoveFlagsAttribute(workspace, model, nodeToFix, flagsAttributeType, cancellationToken);
var newRoot = GetUpdatedRoot(root, nodeToFix, newEnumBlockSyntax);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
private static SyntaxNode AddFlagsAttribute(Workspace workspace, SyntaxNode enumTypeSyntax, INamedTypeSymbol flagsAttributeType, CancellationToken cancellationToken)
{
var attr = CodeGenerationSymbolFactory.CreateAttributeData(flagsAttributeType);
return CodeGenerator.AddAttributes(enumTypeSyntax, workspace, SpecializedCollections.SingletonEnumerable(attr))
.WithAdditionalAnnotations(Formatter.Annotation);
}
private static SyntaxNode RemoveFlagsAttribute(Workspace workspace, SemanticModel model, SyntaxNode enumTypeSyntax, INamedTypeSymbol flagsAttributeType, CancellationToken cancellationToken)
{
var enumType = model.GetDeclaredSymbol(enumTypeSyntax) as INamedTypeSymbol;
Contract.ThrowIfNull(enumType);
var flagsAttribute = enumType.GetAttributes().First(a => a.AttributeClass == flagsAttributeType);
return CodeGenerator.RemoveAttribute(enumTypeSyntax, workspace, flagsAttribute, CodeGenerationOptions.Default, cancellationToken);
}
}
}
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.CodeAnalysis.FxCopDiagnosticFixers {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class FxCopFixersResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal FxCopFixersResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.FxCopDiagnosticFixers.FxCopFixersResources", typeof(FxCopFixersResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Abstract classes should not have public constructors.
/// </summary>
internal static string AbstractTypesShouldNotHavePublicConstructors {
get {
return ResourceManager.GetString("AbstractTypesShouldNotHavePublicConstructors", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Change the accessibility of all public contructors in this class to protected..
/// </summary>
internal static string AbstractTypesShouldNotHavePublicConstructorsCodeFix {
get {
return ResourceManager.GetString("AbstractTypesShouldNotHavePublicConstructorsCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add the &apos;NonSerialized&apos; attribute to this field..
/// </summary>
internal static string AddNonSerializedAttribute {
get {
return ResourceManager.GetString("AddNonSerializedAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add Serializable attribute.
/// </summary>
internal static string AddSerializableAttribute {
get {
return ResourceManager.GetString("AddSerializableAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Avoid unsealed attributes..
/// </summary>
internal static string AvoidUnsealedAttributes {
get {
return ResourceManager.GetString("AvoidUnsealedAttributes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Seal attribute type..
/// </summary>
internal static string AvoidUnsealedAttributesCodeFix {
get {
return ResourceManager.GetString("AvoidUnsealedAttributesCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Disposable fields should be disposed.
/// </summary>
internal static string DisposableFieldsShouldBeDisposed {
get {
return ResourceManager.GetString("DisposableFieldsShouldBeDisposed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove FlagsAttribute from enum..
/// </summary>
internal static string DoNotMarkEnumsWithFlagsCodeFix {
get {
return ResourceManager.GetString("DoNotMarkEnumsWithFlagsCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove all members that have the value zero except for one member that is named &apos;None&apos;..
/// </summary>
internal static string EnumsShouldZeroValueFlagsMultipleZeroCodeFix {
get {
return ResourceManager.GetString("EnumsShouldZeroValueFlagsMultipleZeroCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rename zero-valued enum field to &apos;None&apos;..
/// </summary>
internal static string EnumsShouldZeroValueFlagsRenameCodeFix {
get {
return ResourceManager.GetString("EnumsShouldZeroValueFlagsRenameCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Add a zero-valued member &apos;None&apos; to enum..
/// </summary>
internal static string EnumsShouldZeroValueNotFlagsNoZeroValueCodeFix {
get {
return ResourceManager.GetString("EnumsShouldZeroValueNotFlagsNoZeroValueCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Implement IDisposable Interface.
/// </summary>
internal static string ImplementIDisposableInterface {
get {
return ResourceManager.GetString("ImplementIDisposableInterface", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Implement Serialization constructor.
/// </summary>
internal static string ImplementSerializationConstructor {
get {
return ResourceManager.GetString("ImplementSerializationConstructor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Apply FlagsAttribute to enum..
/// </summary>
internal static string MarkEnumsWithFlagsCodeFix {
get {
return ResourceManager.GetString("MarkEnumsWithFlagsCodeFix", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overload operator equals on overriding ValueType.Equals.
/// </summary>
internal static string OverloadOperatorEqualsOnOverridingValueTypeEquals {
get {
return ResourceManager.GetString("OverloadOperatorEqualsOnOverridingValueTypeEquals", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Remove empty finalizers.
/// </summary>
internal static string RemoveEmptyFinalizers {
get {
return ResourceManager.GetString("RemoveEmptyFinalizers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specify marshaling for P/Invoke string arguments.
/// </summary>
internal static string SpecifyMarshalingForPInvokeStringArguments {
get {
return ResourceManager.GetString("SpecifyMarshalingForPInvokeStringArguments", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to String comparison should use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase.
/// </summary>
internal static string StringComparisonShouldBeOrdinalOrOrdinalIgnoreCase {
get {
return ResourceManager.GetString("StringComparisonShouldBeOrdinalOrOrdinalIgnoreCase", resourceCulture);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ImplementIDisposableInterface" xml:space="preserve">
<value>Implement IDisposable Interface</value>
</data>
<data name="OverloadOperatorEqualsOnOverridingValueTypeEquals" xml:space="preserve">
<value>Overload operator equals on overriding ValueType.Equals</value>
</data>
<data name="AvoidUnsealedAttributesCodeFix" xml:space="preserve">
<value>Seal attribute type.</value>
</data>
<data name="StringComparisonShouldBeOrdinalOrOrdinalIgnoreCase" xml:space="preserve">
<value>String comparison should use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase</value>
</data>
<data name="DisposableFieldsShouldBeDisposed" xml:space="preserve">
<value>Disposable fields should be disposed</value>
</data>
<data name="RemoveEmptyFinalizers" xml:space="preserve">
<value>Remove empty finalizers</value>
</data>
<data name="SpecifyMarshalingForPInvokeStringArguments" xml:space="preserve">
<value>Specify marshaling for P/Invoke string arguments</value>
</data>
<data name="EnumsShouldZeroValueFlagsRenameCodeFix" xml:space="preserve">
<value>Rename zero-valued enum field to 'None'.</value>
</data>
<data name="EnumsShouldZeroValueFlagsMultipleZeroCodeFix" xml:space="preserve">
<value>Remove all members that have the value zero except for one member that is named 'None'.</value>
</data>
<data name="EnumsShouldZeroValueNotFlagsNoZeroValueCodeFix" xml:space="preserve">
<value>Add a zero-valued member 'None' to enum.</value>
</data>
<data name="MarkEnumsWithFlagsCodeFix" xml:space="preserve">
<value>Apply FlagsAttribute to enum.</value>
</data>
<data name="DoNotMarkEnumsWithFlagsCodeFix" xml:space="preserve">
<value>Remove FlagsAttribute from enum.</value>
</data>
<data name="ImplementSerializationConstructor" xml:space="preserve">
<value>Implement Serialization constructor</value>
</data>
<data name="AddSerializableAttribute" xml:space="preserve">
<value>Add Serializable attribute</value>
</data>
<data name="AddNonSerializedAttribute" xml:space="preserve">
<value>Add the 'NonSerialized' attribute to this field.</value>
</data>
<data name="AvoidUnsealedAttributes" xml:space="preserve">
<value>Avoid unsealed attributes.</value>
</data>
<data name="AbstractTypesShouldNotHavePublicConstructorsCodeFix" xml:space="preserve">
<value>Change the accessibility of all public contructors in this class to protected.</value>
</data>
<data name="AbstractTypesShouldNotHavePublicConstructors" xml:space="preserve">
<value>Abstract classes should not have public constructors</value>
</data>
</root>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="Settings">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Settings.targets" />
<Import Project="..\..\..\..\packages\Microsoft.Net.ToolsetCompilers.0.7.4032713-beta\build\Microsoft.Net.ToolsetCompilers.props" Condition="Exists('..\..\..\..\packages\Microsoft.Net.ToolsetCompilers.0.7.4032713-beta\build\Microsoft.Net.ToolsetCompilers.props')" />
</ImportGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C87731D2-4A0A-4883-961D-745262E3CD6A}</ProjectGuid>
<OutputType>Library</OutputType>
<MinimumVisualStudioVersion>$(VisualStudioVersion)</MinimumVisualStudioVersion>
<RunStyleCop>true</RunStyleCop>
<RootNamespace>Microsoft.CodeAnalysis.FxCopDiagnosticFixers</RootNamespace>
<AssemblyName>Microsoft.CodeAnalysis.FxCopDiagnosticFixers</AssemblyName>
<SolutionDir Condition="'$(SolutionDir)' == '' OR '$(SolutionDir)' == '*Undefined*'">..\..\..\..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<OutDir>..\..\..\..\..\Binaries\$(Configuration)\</OutDir>
</PropertyGroup>
<ItemGroup Label="File References">
<Reference Include="System.Collections.Immutable">
<HintPath>..\..\..\packages\Microsoft.Bcl.Immutable.1.1.20-beta\lib\portable-net45+win8\System.Collections.Immutable.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}</Project>
<Name>CodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\Core\Workspaces.csproj">
<Project>{5F8D2414-064A-4B3A-9B42-8E2A04246BE5}</Project>
<Name>Workspaces</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Diagnostics\FxCop\Core\FxCopRulesDiagnosticAnalyzers.csproj">
<Project>{36755424-5267-478C-9434-37A507E22711}</Project>
<Name>FxCopRulesDiagnosticAnalyzers</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "></PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "></PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="InteractiveHost" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Features" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.FxCopDiagnosticFixers" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Text" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Features" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.FxCopDiagnosticFixers" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" />
<InternalsVisibleTo Include="Roslyn.CSharp.InteractiveEditorFeatures" />
<InternalsVisibleTo Include="Roslyn.InteractiveEditorFeatures" />
<InternalsVisibleTo Include="Roslyn.InteractiveFeatures" />
<InternalsVisibleTo Include="Roslyn.VisualBasic.InteractiveEditorFeatures" />
<InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" />
<InternalsVisibleToTest Include="Roslyn.Diagnostics.Analyzers.FxCop.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Hosting.Diagnostics" />
<InternalsVisibleToTest Include="Roslyn.InteractiveHost.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.InteractiveWindow.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.InteractiveWindow.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Services.Editor.CSharp.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Services.Editor.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Services.Editor.UnitTests2" />
<InternalsVisibleToTest Include="Roslyn.Services.Editor.VisualBasic.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.Services.UnitTests" />
<InternalsVisibleToTest Include="Roslyn.VisualStudio.Services.UnitTests" />
<InternalsVisibleToTest Include="RoslynETAHost" />
<InternalsVisibleToTest Include="RoslynTaoActions" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeFixProviderBase.cs" />
<Compile Include="Design\CA1001CodeFixProviderBase.cs" />
<Compile Include="Design\CA1008CodeFixProviderBase.cs" />
<Compile Include="Design\CA1012CodeFixProvider.cs" />
<Compile Include="Design\EnumWithFlagsCodeFixProviderBase.cs" />
<Compile Include="FxCopFixersResources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>FxCopFixersResources.resx</DependentUpon>
</Compile>
<Compile Include="Globalization\CA1309CodeFixProviderBase.cs" />
<Compile Include="Globalization\CA2101CodeFixProviderBase.cs" />
<Compile Include="MultipleCodeFixProviderBase.cs" />
<Compile Include="Performance\CA1813CodeFixProviderBase.cs" />
<Compile Include="Performance\CA1821CodeFixProvider.cs" />
<Compile Include="Usage\CA2213CodeFixProviderBase.cs" />
<Compile Include="Usage\CA2229CodeFixProvider.cs" />
<Compile Include="Usage\CA2231CodeFixProviderBase.cs" />
<Compile Include="Usage\CA2235CodeFixProviderBase.cs" />
<Compile Include="Usage\CA2237CodeFixProvider.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="FxCopFixersResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<SubType>Designer</SubType>
<LastGenOutput>FxCopFixersResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup />
<ImportGroup Label="Targets">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
</Project>
\ No newline at end of file
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Utilities;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Globalization
{
public abstract class CA1309CodeFixProviderBase : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(CA1309DiagnosticAnalyzer.RuleId);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.StringComparisonShouldBeOrdinalOrOrdinalIgnoreCase;
}
internal SyntaxNode CreateEqualsExpression(ISyntaxFactoryService syntaxFactoryService, SemanticModel model, SyntaxNode operand1, SyntaxNode operand2, bool isEquals)
{
var stringType = model.Compilation.GetSpecialType(SpecialType.System_String);
var memberAccess = syntaxFactoryService.CreateMemberAccessExpression(
syntaxFactoryService.CreateTypeReferenceExpression(stringType),
syntaxFactoryService.CreateIdentifierName(CA1309DiagnosticAnalyzer.EqualsMethodName));
var ordinal = CreateOrdinalMemberAccess(syntaxFactoryService, model);
var invocation = syntaxFactoryService.CreateInvocationExpression(
memberAccess,
operand1,
operand2.WithTrailingTrivia(),
ordinal)
.WithAdditionalAnnotations(Formatter.Annotation);
if (!isEquals)
{
invocation = syntaxFactoryService.CreateLogicalNotExpression(invocation);
}
invocation = invocation.WithTrailingTrivia(operand2.GetTrailingTrivia());
return invocation;
}
internal SyntaxNode CreateOrdinalMemberAccess(ISyntaxFactoryService syntaxFactoryService, SemanticModel model)
{
var stringComparisonType = WellKnownTypes.StringComparison(model.Compilation);
return syntaxFactoryService.CreateMemberAccessExpression(
syntaxFactoryService.CreateTypeReferenceExpression(stringComparisonType),
syntaxFactoryService.CreateIdentifierName(CA1309DiagnosticAnalyzer.OrdinalText));
}
protected bool CanAddStringComparison(IMethodSymbol methodSymbol)
{
var parameters = methodSymbol.Parameters;
switch (methodSymbol.Name)
{
case CA1309DiagnosticAnalyzer.EqualsMethodName:
// can fix .Equals() with (string), (string, string)
switch (parameters.Length)
{
case 1:
return parameters[0].Type.SpecialType == SpecialType.System_String;
case 2:
return parameters[0].Type.SpecialType == SpecialType.System_String &&
parameters[1].Type.SpecialType == SpecialType.System_String;
}
break;
case CA1309DiagnosticAnalyzer.CompareMethodName:
// can fix .Compare() with (string, string), (string, int, string, int, int)
switch (parameters.Length)
{
case 2:
return parameters[0].Type.SpecialType == SpecialType.System_String &&
parameters[1].Type.SpecialType == SpecialType.System_String;
case 5:
return parameters[0].Type.SpecialType == SpecialType.System_String &&
parameters[1].Type.SpecialType == SpecialType.System_Int32 &&
parameters[2].Type.SpecialType == SpecialType.System_String &&
parameters[3].Type.SpecialType == SpecialType.System_Int32 &&
parameters[4].Type.SpecialType == SpecialType.System_Int32;
}
break;
}
return false;
}
}
}
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Globalization
{
public abstract class CA2101CodeFixProviderBase : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(Interoperability.PInvokeDiagnosticAnalyzer.CA2101);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.SpecifyMarshalingForPInvokeStringArguments;
}
protected const string CharSetText = "CharSet";
protected const string LPWStrText = "LPWStr";
protected const string UnicodeText = "Unicode";
internal SyntaxNode CreateMarshalAsArgument(ISyntaxFactoryService syntaxFactoryService, INamedTypeSymbol unmanagedType)
{
return syntaxFactoryService.CreateMemberAccessExpression(
syntaxFactoryService.CreateTypeReferenceExpression(unmanagedType), syntaxFactoryService.CreateIdentifierName(LPWStrText));
}
internal SyntaxNode CreateCharSetArgument(ISyntaxFactoryService syntaxFactoryService, INamedTypeSymbol charSetType)
{
return syntaxFactoryService.CreateMemberAccessExpression(
syntaxFactoryService.CreateTypeReferenceExpression(charSetType), syntaxFactoryService.CreateIdentifierName(UnicodeText));
}
}
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers
{
public abstract class MultipleCodeFixProviderBase : ICodeFixProvider
{
public abstract IEnumerable<string> GetFixableDiagnosticIds();
internal abstract Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken);
async Task<IEnumerable<CodeAction>> ICodeFixProvider.GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var actions = SpecializedCollections.EmptyEnumerable<CodeAction>();
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
var nodeToFix = root.FindNode(diagnostic.Location.SourceSpan);
var newActions = await GetFixesAsync(document, model, root, nodeToFix, cancellationToken).ConfigureAwait(false);
if (newActions != null)
{
actions = actions.Concat(newActions);
}
}
return actions;
}
}
}
using System.Collections.Generic;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Performance
{
/// <summary>
/// CA1813: Avoid unsealed attributes
/// </summary>
public abstract class CA1813CodeFixProviderBase : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(CA1813DiagnosticAnalyzer.RuleId);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.AvoidUnsealedAttributesCodeFix;
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Performance
{
/// <summary>
/// CA1821: Remove empty finalizers
/// </summary>
[ExportCodeFixProvider(CA1821DiagnosticAnalyzer.RuleId, LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class CA1821CodeFixProvider : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(CA1821DiagnosticAnalyzer.RuleId);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.RemoveEmptyFinalizers;
}
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
return Task.FromResult(document.WithSyntaxRoot(root.RemoveNode(nodeToFix, SyntaxRemoveOptions.KeepNoTrivia)));
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Usage
{
/// <summary>
/// CA2213: Disposable fields should be disposed
/// </summary>
public abstract class CA2213CodeFixProviderBase : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(CA2213DiagnosticAnalyzer.RuleId);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.DisposableFieldsShouldBeDisposed;
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.FxCopAnalyzers;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Utilities;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Usage
{
[ExportCodeFixProvider("CA2229 CodeFix provider", LanguageNames.CSharp)]
public sealed class CA2229CodeFixProvider : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(SerializationRulesDiagnosticAnalyzer.RuleCA2229Id);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.ImplementSerializationConstructor;
}
internal async override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
var syntaxFactoryService = document.GetLanguageService<ISyntaxFactoryService>();
var symbol = model.GetDeclaredSymbol(nodeToFix);
// There was no constructor and so the diagnostic was on the type. Generate a serlialization ctor.
if (symbol.Kind == SymbolKind.NamedType)
{
var typeSymbol = symbol as INamedTypeSymbol;
var throwStatement = syntaxFactoryService.CreateThrowNotImplementedStatementBlock(model.Compilation);
var parameters = ImmutableArray.Create(
CodeGenerationSymbolFactory.CreateParameterSymbol(WellKnownTypes.SerializationInfo(model.Compilation), "serializationInfo"),
CodeGenerationSymbolFactory.CreateParameterSymbol(WellKnownTypes.StreamingContext(model.Compilation), "streamingContext"));
var ctorSymbol = CodeGenerationSymbolFactory.CreateConstructorSymbol(null,
typeSymbol.IsSealed ? Accessibility.Private : Accessibility.Protected,
new SymbolModifiers(),
typeSymbol.Name,
parameters,
throwStatement);
return await CodeGenerator.AddMethodDeclarationAsync(document.Project.Solution, typeSymbol, ctorSymbol).ConfigureAwait(false);
}
else if (symbol.Kind == SymbolKind.Method)
{
// There is a serialization constructor but with incorrect accessibility. Set that right.
var methodSymbol = symbol as IMethodSymbol;
// This would be constructor and can have only one definition.
Debug.Assert(methodSymbol.IsConstructor() && methodSymbol.DeclaringSyntaxReferences.Count() == 1);
var declaration = await methodSymbol.DeclaringSyntaxReferences.First().GetSyntaxAsync(cancellationToken);
var newAccessibility = methodSymbol.ContainingType.IsSealed ? Accessibility.Private : Accessibility.Protected;
var newDecl = CodeGenerator.UpdateDeclarationAccessibility(declaration, document.Project.Solution.Workspace, newAccessibility, cancellationToken: cancellationToken);
return document.WithSyntaxRoot(root.ReplaceNode(declaration, newDecl));
}
return document;
}
}
}
using System.Collections.Generic;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Usage
{
/// <summary>
/// CA2231: Overload operator equals on overriding ValueType.Equals
/// </summary>
public abstract class CA2231CodeFixProviderBase : CodeFixProviderBase
{
protected const string LeftName = "left";
protected const string RightName = "right";
protected const string NotImplementedExceptionName = "System.NotImplementedException";
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(CA2231DiagnosticAnalyzer.RuleId);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.OverloadOperatorEqualsOnOverridingValueTypeEquals;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Utilities;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Usage
{
public abstract class CA2235CodeFixProviderBase : MultipleCodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(SerializationRulesDiagnosticAnalyzer.RuleCA2235Id);
}
protected abstract SyntaxNode GetFieldDeclarationNode(SyntaxNode node);
internal async override Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken)
{
IEnumerable<CodeAction> actions = null;
// Fix 1: Add a NonSerialized attribute to the field
var fieldNode = GetFieldDeclarationNode(nodeToFix);
if (fieldNode != null)
{
var attr = CodeGenerationSymbolFactory.CreateAttributeData(WellKnownTypes.NonSerializedAttribute(model.Compilation));
var newNode = CodeGenerator.AddAttributes(fieldNode, document.Project.Solution.Workspace, SpecializedCollections.SingletonEnumerable(attr)).WithAdditionalAnnotations(Formatting.Formatter.Annotation);
var newDocument = document.WithSyntaxRoot(root.ReplaceNode(fieldNode, newNode));
var codeAction = CodeAction.Create(FxCopFixersResources.AddNonSerializedAttribute, newDocument);
actions = SpecializedCollections.SingletonEnumerable(codeAction);
// Fix 2: If the type of the field is defined in source, then add the serializable attribute to the type.
var fieldSymbol = model.GetDeclaredSymbol(nodeToFix) as IFieldSymbol;
var type = fieldSymbol.Type;
if (type.Locations.Any(l => l.IsInSource))
{
var typeDeclNode = type.DeclaringSyntaxReferences.First().GetSyntax();
var serializableAttr = CodeGenerationSymbolFactory.CreateAttributeData(WellKnownTypes.SerializableAttribute(model.Compilation));
var newTypeDeclNode = CodeGenerator.AddAttributes(typeDeclNode, document.Project.Solution.Workspace, SpecializedCollections.SingletonEnumerable(serializableAttr)).WithAdditionalAnnotations(Formatting.Formatter.Annotation);
var documentContainingNode = document.Project.Solution.GetDocument(typeDeclNode.SyntaxTree);
var docRoot = await documentContainingNode.GetSyntaxRootAsync(cancellationToken);
var newDocumentContainingNode = documentContainingNode.WithSyntaxRoot(docRoot.ReplaceNode(typeDeclNode, newTypeDeclNode));
var typeCodeAction = CodeAction.Create(FxCopFixersResources.AddSerializableAttribute, newDocumentContainingNode.Project.Solution);
actions = actions.Concat(typeCodeAction);
}
}
return actions;
}
}
}
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Utilities;
using Microsoft.CodeAnalysis.FxCopDiagnosticFixers;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Usage
{
[ExportCodeFixProvider("CA2237 CodeFix provider", LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class CA2237CodeFixProvider : CodeFixProviderBase
{
public sealed override IEnumerable<string> GetFixableDiagnosticIds()
{
return SpecializedCollections.SingletonEnumerable(SerializationRulesDiagnosticAnalyzer.RuleCA2237Id);
}
protected sealed override string GetCodeFixDescription(string ruleId)
{
return FxCopFixersResources.AddSerializableAttribute;
}
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
{
var attr = CodeGenerationSymbolFactory.CreateAttributeData(WellKnownTypes.SerializableAttribute(model.Compilation));
var newNode = CodeGenerator.AddAttributes(nodeToFix, document.Project.Solution.Workspace, SpecializedCollections.SingletonEnumerable(attr)).WithAdditionalAnnotations(Formatting.Formatter.Annotation);
return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(nodeToFix, newNode)));
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl.Immutable" version="1.1.20-beta" targetFramework="net45" />
<package id="Microsoft.Net.ToolsetCompilers" version="0.7.4032713-beta" targetFramework="net45" developmentDependency="true" />
</packages>
\ No newline at end of file
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Design;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA1001FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA1001DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA1001BasicCodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA1001DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1001CSharpCodeFixProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001CSharpCodeFixNoEqualsOperator()
{
VerifyCSharpFix(@"
using System;
using System.IO;
// This class violates the rule.
public class NoDisposeClass
{
FileStream newFile;
public NoDisposeClass()
{
newFile = new FileStream("""", FileMode.Append);
}
}
",
@"
using System;
using System.IO;
// This class violates the rule.
public class NoDisposeClass : IDisposable
{
FileStream newFile;
public NoDisposeClass()
{
newFile = new FileStream("""", FileMode.Append);
}
public void Dispose()
{
throw new NotImplementedException();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001BasicCodeFixNoEqualsOperator()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class NoDisposeMethod
Dim newFile As FileStream
Sub New()
newFile = New FileStream("""", FileMode.Append)
End Sub
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class NoDisposeMethod
Implements IDisposable
Dim newFile As FileStream
Sub New()
newFile = New FileStream("""", FileMode.Append)
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
");
}
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Design;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class CA1008FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA1008DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA1008BasicCodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA1008DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1008CSharpCodeFixProvider();
}
[WorkItem(836193)]
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueFlagsRename()
{
var code = @"
[System.Flags]
private enum E
{
A = 0,
B = 3
}
[System.Flags]
public enum E2
{
A2 = 0,
B2 = 1
}
[System.Flags]
public enum E3
{
A3 = (ushort)0,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
A4 = 0,
B4 = (uint)2 // Not a constant
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
var expectedFixedCode = @"
[System.Flags]
private enum E
{
None,
B = 3
}
[System.Flags]
public enum E2
{
None,
B2 = 1
}
[System.Flags]
public enum E3
{
None,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
None,
B4 = (uint)2 // Not a constant
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueFlagsMultipleZero()
{
var code = @"// Some comment
[System.Flags]
private enum E
{
None = 0,
A = 0
}
// Some comment
[System.Flags]
internal enum E2
{
None = 0,
A = None
}";
var expectedFixedCode = @"// Some comment
[System.Flags]
private enum E
{
None = 0
}
// Some comment
[System.Flags]
internal enum E2
{
None = 0
}";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueFlagsMultipleZeroWithScope()
{
var code = @"// Some comment
[System.Flags]
private enum E
{
None = 0,
A = 0
}
[|// Some comment
[System.Flags]
internal enum E2
{
None = 0,
A = None
}|]";
var expectedFixedCode = @"// Some comment
[System.Flags]
private enum E
{
None = 0,
A = 0
}
// Some comment
[System.Flags]
internal enum E2
{
None = 0
}";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueNotFlagsNoZeroValue()
{
var code = @"
private enum E
{
A = 1
}
private enum E2
{
None = 1,
A = 2
}
internal enum E3
{
None = 0,
A = 1
}
internal enum E4
{
None = 0,
A = 0
}
";
var expectedFixedCode = @"
private enum E
{
None,
A = 1
}
private enum E2
{
None,
A = 2
}
internal enum E3
{
None = 0,
A = 1
}
internal enum E4
{
None = 0,
A = 0
}
";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueNotFlagsNoZeroValueWithScope()
{
var code = @"
class C
{
private enum E
{
A = 1
}
[|private enum E2
{
None = 1,
A = 2
}
internal enum E3
{
None = 0,
A = 1
}|]
internal enum E4
{
None = 0,
A = 0
}
}
";
var expectedFixedCode = @"
class C
{
private enum E
{
A = 1
}
private enum E2
{
None,
A = 2
}
internal enum E3
{
None = 0,
A = 1
}
internal enum E4
{
None = 0,
A = 0
}
}
";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueFlagsRename()
{
var code = @"
<System.Flags>
Private Enum E
A = 0
B = 1
End Enum
<System.Flags>
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
<System.Flags>
Private Enum E
None
B = 1
End Enum
<System.Flags>
Public Enum E2
None
B2 = 1
End Enum
<System.Flags>
Public Enum E3
None
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueFlagsRenameScope()
{
var code = @"
<System.Flags>
Private Enum E
A = 0
B = 1
End Enum
[|<System.Flags>
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum|]
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
<System.Flags>
Private Enum E
A = 0
B = 1
End Enum
<System.Flags>
Public Enum E2
None
B2 = 1
End Enum
<System.Flags>
Public Enum E3
None
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
[WorkItem(836193)]
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueFlagsRename_AttributeListHasTrivia()
{
var code = @"
<System.Flags> _
Private Enum E
A = 0
B = 1
End Enum
<System.Flags> _
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
<System.Flags> _
Private Enum E
None
B = 1
End Enum
<System.Flags> _
Public Enum E2
None
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
None
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueFlagsMultipleZero()
{
var code = @"
<System.Flags>
Private Enum E
None = 0
A = 0
End Enum
<System.Flags>
Friend Enum E2
None = 0
A = None
End Enum
<System.Flags>
Public Enum E3
A3 = 0
B3 = CUInt(0) ' Not a constant
End Enum";
var expectedFixedCode = @"
<System.Flags>
Private Enum E
None = 0
End Enum
<System.Flags>
Friend Enum E2
None = 0
End Enum
<System.Flags>
Public Enum E3
None
End Enum";
VerifyBasicFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueNotFlagsNoZeroValue()
{
var code = @"
Private Enum E
A = 1
End Enum
Private Enum E2
None = 1
A = 2
End Enum
Friend Enum E3
None = 0
A = 1
End Enum
Friend Enum E4
None = 0
A = 0
End Enum
";
var expectedFixedCode = @"
Private Enum E
None
A = 1
End Enum
Private Enum E2
None
A = 2
End Enum
Friend Enum E3
None = 0
A = 1
End Enum
Friend Enum E4
None = 0
A = 0
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
[Fact(Skip = "Bug 880044"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueNotFlagsNoZeroValueWithScope()
{
var code = @"
Private Enum E
A = 1
End Enum
[|Private Enum E2
None = 1
A = 2
End Enum
Friend Enum E3
None = 0
A = 1
End Enum|]
Friend Enum E4
None = 0
A = 0
End Enum
";
var expectedFixedCode = @"
Private Enum E
A = 1
End Enum
Private Enum E2
None
A = 2
End Enum
Friend Enum E3
None = 0
A = 1
End Enum
Friend Enum E4
None = 0
A = 0
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA1012FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA1012DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA1012CodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA1012DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1012CodeFixProvider();
}
[Fact(Skip = "Bug 823796"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestCSPublicAbstractClass()
{
var code = @"
public abstract class C
{
public C()
{
}
}
";
var fix = @"
public abstract class C
{
protected C()
{
}
}
";
VerifyCSharpFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestVBPublicAbstractClass()
{
var code = @"
Public MustInherit Class C
Public Sub New()
End Sub
End Class
";
var fix = @"
Public MustInherit Class C
Protected Sub New()
End Sub
End Class
";
VerifyBasicFix(code, fix);
}
[Fact(Skip = "Bug 823796"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestCSInternalAbstractClass()
{
var code = @"
abstract class C
{
public C()
{
}
}
";
var fix = @"
abstract class C
{
protected C()
{
}
}
";
VerifyCSharpFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestVBInternalAbstractClass()
{
var code = @"
MustInherit Class C
Public Sub New()
End Sub
End Class
";
var fix = @"
MustInherit Class C
Protected Sub New()
End Sub
End Class
";
VerifyBasicFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestCSNestedAbstractClassWithPublicConstructor1()
{
var code = @"
public struct C
{
abstract class D
{
public D() { }
}
}
";
var fix = @"
public struct C
{
abstract class D
{
protected D() { }
}
}
";
VerifyCSharpFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestVBNestedAbstractClassWithPublicConstructor1()
{
var code = @"
Public Structure C
MustInherit Class D
Public Sub New()
End Sub
End Class
End Class
";
var fix = @"
Public Structure C
MustInherit Class D
Protected Sub New()
End Sub
End Class
End Class
";
VerifyBasicFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestNestedAbstractClassWithPublicConstructor2()
{
var code = @"
public abstract class C
{
public abstract class D
{
public D() { }
}
}
";
var fix = @"
public abstract class C
{
public abstract class D
{
protected D() { }
}
}
";
VerifyCSharpFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestVBNestedAbstractClassWithPublicConstructor2()
{
var code = @"
Public MustInherit Class C
Protected Friend MustInherit Class D
Sub New()
End Sub
End Class
End Class
";
var fix = @"
Public MustInherit Class C
Protected Friend MustInherit Class D
Protected Sub New()
End Sub
End Class
End Class
";
VerifyBasicFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestNestedAbstractClassWithPublicConstructor3()
{
var code = @"
internal abstract class C
{
public abstract class D
{
public D() { }
}
}
";
var fix = @"
internal abstract class C
{
public abstract class D
{
protected D() { }
}
}
";
VerifyCSharpFix(code, fix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void TestVBNestedAbstractClassWithPublicConstructor3()
{
var code = @"
MustInherit Class C
Public MustInherit Class D
Sub New()
End Sub
End Class
End Class
";
var fix = @"
MustInherit Class C
Public MustInherit Class D
Protected Sub New()
End Sub
End Class
End Class
";
VerifyBasicFix(code, fix);
}
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Design;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class EnumWithFlagsAttributesRulesFixerTests : CodeFixTestBase
{
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new EnumWithFlagsBasicCodeFixProvider();
}
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new BasicEnumWithFlagsDiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new EnumWithFlagsCSharpCodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CSharpEnumWithFlagsDiagnosticAnalyzer();
}
private static string GetCSharpCode_EnumWithFlagsAttributes(string code, bool hasFlags)
{
var stringToReplace = hasFlags ? "[System.Flags]" : "";
return string.Format(code, stringToReplace);
}
private static string GetBasicCode_EnumWithFlagsAttributes(string code, bool hasFlags)
{
var stringToReplace = hasFlags ? "<System.Flags>" : "";
return string.Format(code, stringToReplace);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumWithFlagsAttributes_SimpleCase()
{
var code = @"{0}
public enum SimpleFlagsEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4
}}
{0}
public enum HexFlagsEnumClass
{{
One = 0x1,
Two = 0x2,
Four = 0x4,
All = 0x7
}}";
var codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
var codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
// Verify fixes for CA1027
VerifyCSharpFix(codeWithoutFlags, codeWithFlags);
}
[Fact(Skip = "Bug 902707"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumWithFlagsAttributes_SimpleCase()
{
var code = @"{0}
Public Enum SimpleFlagsEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
End Enum
{0}
Public Enum HexFlagsEnumClass
One = &H1
Two = &H2
Four = &H4
All = &H7
End Enum";
var codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
var codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
// Verify fixes for CA1027
VerifyBasicFix(codeWithoutFlags, codeWithFlags);
}
[WorkItem(823796)]
[Fact(Skip = "Bug 823796"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumWithFlagsAttributes_DuplicateValues()
{
string code = @"{0}
public enum DuplicateValuesEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
AnotherFour = 4,
ThreePlusOne = Two + One + One
}}
";
var codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false);
var codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
// Verify fixes for CA1027
VerifyCSharpFix(codeWithoutFlags, codeWithFlags);
}
[Fact(Skip = "Bug 902707"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumWithFlagsAttributes_DuplicateValues()
{
string code = @"{0}
Public Enum DuplicateValuesEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
AnotherFour = 4
ThreePlusOne = Two + One + One
End Enum
";
var codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false);
var codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
// Verify fixes for CA1027
VerifyBasicFix(codeWithoutFlags, codeWithFlags);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumWithFlagsAttributes_MissingPowerOfTwo()
{
string code = @"
{0}
public enum MissingPowerOfTwoEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
Sixteen = 16
}}
{0}
public enum MultipleMissingPowerOfTwoEnumClass
{{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
ThirtyTwo = 32
}}
{0}
public enum AnotherTestValue
{{
Value1 = 0,
Value2 = 1,
Value3 = 1,
Value4 = 3
}}";
var codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true);
var codeWithFlagsFix = @"
public enum MissingPowerOfTwoEnumClass
{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
Sixteen = 16
}
public enum MultipleMissingPowerOfTwoEnumClass
{
Zero = 0,
One = 1,
Two = 2,
Four = 4,
ThirtyTwo = 32
}
public enum AnotherTestValue
{
Value1 = 0,
Value2 = 1,
Value3 = 1,
Value4 = 3
}";
// Verify fixes for CA2217
VerifyCSharpFix(codeWithFlags, codeWithFlagsFix);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumWithFlagsAttributes_MissingPowerOfTwo()
{
string code = @"
{0}
Public Enum MissingPowerOfTwoEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
Sixteen = 16
End Enum
{0}
Public Enum MultipleMissingPowerOfTwoEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
ThirtyTwo = 32
End Enum
{0}
Public Enum AnotherTestValue
Value1 = 0
Value2 = 1
Value3 = 1
Value4 = 3
End Enum
";
var codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true);
string codeWithFlagsFix = @"
Public Enum MissingPowerOfTwoEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
Sixteen = 16
End Enum
Public Enum MultipleMissingPowerOfTwoEnumClass
Zero = 0
One = 1
Two = 2
Four = 4
ThirtyTwo = 32
End Enum
Public Enum AnotherTestValue
Value1 = 0
Value2 = 1
Value3 = 1
Value4 = 3
End Enum
";
// Verify fixes for CA2217
VerifyBasicFix(codeWithFlags, codeWithFlagsFix);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="Settings">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Settings.targets" />
<Import Project="..\..\..\..\packages\Microsoft.Net.ToolsetCompilers.0.7.4032713-beta\build\Microsoft.Net.ToolsetCompilers.props" Condition="Exists('..\..\..\..\packages\Microsoft.Net.ToolsetCompilers.0.7.4032713-beta\build\Microsoft.Net.ToolsetCompilers.props')" />
</ImportGroup>
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<ProjectGuid>{4BA8E3A5-85B2-4FC5-8D4D-89DB15BD91AE}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.UnitTests</RootNamespace>
<AssemblyName>Roslyn.Diagnostics.CodeFixes.FxCop.UnitTests</AssemblyName>
<RunStyleCop>true</RunStyleCop>
<Nonshipping>true</Nonshipping>
<SolutionDir Condition="'$(SolutionDir)' == '' OR '$(SolutionDir)' == '*Undefined*'">..\..\..\..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<OutDir>..\..\..\..\..\Binaries\$(Configuration)\</OutDir>
</PropertyGroup>
<ItemGroup Label="File References">
<Reference Include="System.Collections.Immutable">
<HintPath>..\..\..\packages\Microsoft.Bcl.Immutable.1.1.20-beta\lib\portable-net45+win8\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="xunit.abstractions">
<HintPath>..\..\..\..\packages\xunit.abstractions.2.0.0-alpha-build2576\lib\net35\xunit.abstractions.dll</HintPath>
</Reference>
<Reference Include="xunit2.assert">
<HintPath>..\..\..\..\packages\xunit.assert.2.0.0-alpha-build2576\lib\net45\xunit2.assert.dll</HintPath>
</Reference>
<Reference Include="xunit2">
<HintPath>..\..\..\..\packages\xunit.core.2.0.0-alpha-build2576\lib\net45\xunit2.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1EE8CAD3-55F9-4D91-96B2-084641DA9A6C}</Project>
<Name>CodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\CSharpCodeAnalysis.csproj">
<Project>{B501A547-C911-4A05-AC6E-274A50DFF30E}</Project>
<Name>CSharpCodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\CompilerTestResources.vbproj">
<Project>{7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}</Project>
<Name>CompilerTestResources</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\BasicCodeAnalysis.vbproj">
<Project>{2523D0E6-DF32-4A3E-8AE0-A19BFFAE2EF6}</Project>
<Name>BasicCodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Test\Utilities\TestUtilities.csproj">
<Project>{76C6F005-C89D-4348-BB4A-391898DBEB52}</Project>
<Name>TestUtilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\CSharp\CSharpWorkspace.csproj">
<Project>{21B239D0-D144-430F-A394-C066D58EE267}</Project>
<Name>CSharpWorkspace</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\VisualBasic\BasicWorkspace.vbproj">
<Project>{57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}</Project>
<Name>BasicWorkspace</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\Core\Workspaces.csproj">
<Project>{5F8D2414-064A-4B3A-9B42-8E2A04246BE5}</Project>
<Name>Workspaces</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Diagnostics\FxCop\Core\FxCopRulesDiagnosticAnalyzers.csproj">
<Project>{36755424-5267-478C-9434-37A507E22711}</Project>
<Name>FxCopRulesDiagnosticAnalyzers</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Diagnostics\FxCop\CSharp\CSharpFxCopRulesDiagnosticAnalyzers.csproj">
<Project>{3BA13187-2A3B-4B08-9199-C11FDA1D5AD0}</Project>
<Name>CSharpFxCopRulesDiagnosticAnalyzers</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Diagnostics\FxCop\VisualBasic\BasicFxCopRulesDiagnosticAnalyzers.vbproj">
<Project>{2FCCB9BE-DD4E-48F2-B678-80E6FB196948}</Project>
<Name>BasicFxCopRulesDiagnosticAnalyzers</Name>
</ProjectReference>
<ProjectReference Include="..\Core\FxCopRulesDiagnosticFixers.csproj">
<Project>{C87731D2-4A0A-4883-961D-745262E3CD6A}</Project>
<Name>FxCopRulesDiagnosticFixers</Name>
</ProjectReference>
<ProjectReference Include="..\CSharp\CSharpFxCopRulesDiagnosticFixers.csproj">
<Project>{EDA725D2-1125-4F43-91FF-4837157F9C4B}</Project>
<Name>CSharpFxCopRulesDiagnosticFixers</Name>
</ProjectReference>
<ProjectReference Include="..\VisualBasic\BasicFxCopRulesDiagnosticFixers.vbproj">
<Project>{058F3AE9-FB37-47CC-8D3B-518DEA93D888}</Project>
<Name>BasicFxCopRulesDiagnosticFixers</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Diagnostics\Test\Utilities\DiagnosticsTestUtilities.csproj">
<Project>{0A0621F2-D1DC-47FF-B643-C6646557505E}</Project>
<Name>DiagnosticsTestUtilities</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "></PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "></PropertyGroup>
<ItemGroup>
<Compile Include="Design\CA1001FixerTests.cs" />
<Compile Include="Design\CA1008FixerTests.cs" />
<Compile Include="Design\CA1012FixerTests.cs" />
<Compile Include="Design\EnumWithFlagsAttributesRulesFixerTests.cs" />
<Compile Include="Globalization\CA1309FixerTests.cs" />
<Compile Include="Globalization\CA2101FixerTests.cs" />
<Compile Include="Performance\CA1813FixerTests.cs" />
<Compile Include="Performance\CA1821FixerTests.cs" />
<Compile Include="Usage\CA2213FixerTests.cs" />
<Compile Include="Usage\CA2229FixerTests.cs" />
<Compile Include="Usage\CA2231FixerTests.cs" />
<Compile Include="Usage\CA2235FixerTests.cs" />
<Compile Include="Usage\CA2237FixerTests.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Web" />
<Reference Include="System.Xaml" />
<Reference Include="System.XML" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ImportGroup Label="Targets">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
</Project>
\ No newline at end of file
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Globalization;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Globalization;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Globalization
{
[WorkItem(858659)]
public class CA1309FixerTests : CodeFixTestBase
{
#region Helper methods
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CSharpCA1309DiagnosticAnalyzer();
}
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new BasicCA1309DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1309CSharpCodeFixProvider();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA1309BasicCodeFixProvider();
}
#endregion
#region Code fix tests
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixOperatorCSharp()
{
VerifyCSharpFix(@"
class C
{
void M(string a, string b)
{
if (a == b) { }
if (a != b) { }
var c = a == b/*comment*/;
}
}
", @"
class C
{
void M(string a, string b)
{
if (string.Equals(a, b, System.StringComparison.Ordinal)) { }
if (!string.Equals(a, b, System.StringComparison.Ordinal)) { }
var c = string.Equals(a, b, System.StringComparison.Ordinal)/*comment*/;
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixOperatorBasic()
{
VerifyBasicFix(@"
Class C
Sub M(a As String, b As String)
If a = b Then
End If
If a <> b Then
End If
Dim c = a = b'comment
End Sub
End Class
", @"
Class C
Sub M(a As String, b As String)
If (String).Equals(a, b, System.StringComparison.Ordinal) Then
End If
If Not (String).Equals(a, b, System.StringComparison.Ordinal) Then
End If
Dim c = (String).Equals(a, b, System.StringComparison.Ordinal) 'comment
End Sub
End Class
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixStaticEqualsOverloadCSharp()
{
VerifyCSharpFix(@"
class C
{
void M(string a, string b)
{
if (string.Equals(a, b)) { }
if (string.Equals(a, b, System.StringComparison.CurrentCulture)) { }
if (string.Equals(a, b, System.StringComparison.CurrentCultureIgnoreCase)) { }
}
}
", @"
class C
{
void M(string a, string b)
{
if (string.Equals(a, b, System.StringComparison.Ordinal)) { }
if (string.Equals(a, b, System.StringComparison.Ordinal)) { }
if (string.Equals(a, b, System.StringComparison.OrdinalIgnoreCase)) { }
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixStaticEqualsOverloadBasic()
{
VerifyBasicFix(@"
Class C
Sub M(a As String, b As String)
If String.Equals(a, b) Then
End If
If String.Equals(a, b, System.StringComparison.CurrentCulture) Then
End If
If String.Equals(a, b, System.StringComparison.CurrentCultureIgnoreCase) Then
End If
End Sub
End Class
", @"
Class C
Sub M(a As String, b As String)
If String.Equals(a, b, System.StringComparison.Ordinal) Then
End If
If String.Equals(a, b, System.StringComparison.Ordinal) Then
End If
If String.Equals(a, b, System.StringComparison.OrdinalIgnoreCase) Then
End If
End Sub
End Class
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixInstanceEqualsOverloadCSharp()
{
VerifyCSharpFix(@"
class C
{
void M(string a, string b)
{
if (a.Equals(15)) { }
if (a.Equals(b)) { }
if (a.Equals(b, System.StringComparison.Ordinal)) { }
if (a.Equals(b, System.StringComparison.CurrentCulture)) { }
}
}
", @"
class C
{
void M(string a, string b)
{
if (a.Equals(15)) { }
if (a.Equals(b, System.StringComparison.Ordinal)) { }
if (a.Equals(b, System.StringComparison.Ordinal)) { }
if (a.Equals(b, System.StringComparison.Ordinal)) { }
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixInstanceEqualsOverloadBasic()
{
VerifyBasicFix(@"
Class C
Sub M(a As String, b As String)
If a.Equals(15) Then
End If
If a.Equals(b) Then
End If
If a.Equals(b, System.StringComparison.Ordinal) Then
End If
If a.Equals(b, System.StringComparison.CurrentCulture) Then
End If
End Sub
End Class
", @"
Class C
Sub M(a As String, b As String)
If a.Equals(15) Then
End If
If a.Equals(b, System.StringComparison.Ordinal) Then
End If
If a.Equals(b, System.StringComparison.Ordinal) Then
End If
If a.Equals(b, System.StringComparison.Ordinal) Then
End If
End Sub
End Class
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixStaticCompareOverloadCSharp()
{
VerifyCSharpFix(@"
class C
{
void M(string a, string b)
{
System.Globalization.CultureInfo ci;
System.Globalization.CompareOptions co;
// add or correct StringComparison
if (string.Compare(a, b) == 0) { }
if (string.Compare(a, 0, b, 0, 0) == 0) { }
if (string.Compare(a, b, System.StringComparison.CurrentCulture) == 0) { }
if (string.Compare(a, b, System.StringComparison.CurrentCultureIgnoreCase) == 0) { }
if (string.Compare(a, 0, b, 0, 0, System.StringComparison.CurrentCulture) == 0) { }
// these can't be auto-fixed
if (string.Compare(a, b, true) == 0) { }
if (string.Compare(a, b, true, ci) == 0) { }
if (string.Compare(a, b, ci, co) == 0) { }
if (string.Compare(a, 0, b, 0, 0, true) == 0) { }
if (string.Compare(a, 0, b, 0, 0, true, ci) == 0) { }
if (string.Compare(a, 0, b, 0, 0, ci, co) == 0) { }
}
}
", @"
class C
{
void M(string a, string b)
{
System.Globalization.CultureInfo ci;
System.Globalization.CompareOptions co;
// add or correct StringComparison
if (string.Compare(a, b, System.StringComparison.Ordinal) == 0) { }
if (string.Compare(a, 0, b, 0, 0, System.StringComparison.Ordinal) == 0) { }
if (string.Compare(a, b, System.StringComparison.Ordinal) == 0) { }
if (string.Compare(a, b, System.StringComparison.OrdinalIgnoreCase) == 0) { }
if (string.Compare(a, 0, b, 0, 0, System.StringComparison.Ordinal) == 0) { }
// these can't be auto-fixed
if (string.Compare(a, b, true) == 0) { }
if (string.Compare(a, b, true, ci) == 0) { }
if (string.Compare(a, b, ci, co) == 0) { }
if (string.Compare(a, 0, b, 0, 0, true) == 0) { }
if (string.Compare(a, 0, b, 0, 0, true, ci) == 0) { }
if (string.Compare(a, 0, b, 0, 0, ci, co) == 0) { }
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1309FixStaticCompareOverloadBasic()
{
VerifyBasicFix(@"
Class C
Sub M(a As String, b As String)
Dim ci As System.Globalization.CultureInfo
Dim co As System.Globalization.CompareOptions
' add or correct StringComparison
If String.Compare(a, b) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0) = 0 Then
End If
If String.Compare(a, b, System.StringComparison.CurrentCulture) = 0 Then
End If
If String.Compare(a, b, System.StringComparison.CurrentCultureIgnoreCase) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, System.StringComparison.CurrentCulture) = 0 Then
End If
' these can't be auto-fixed
If String.Compare(a, b, True) = 0 Then
End If
If String.Compare(a, b, True, ci) = 0 Then
End If
If String.Compare(a, b, ci, co) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, True) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, True, ci) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, ci, co) = 0 Then
End If
End Sub
End Class
", @"
Class C
Sub M(a As String, b As String)
Dim ci As System.Globalization.CultureInfo
Dim co As System.Globalization.CompareOptions
' add or correct StringComparison
If String.Compare(a, b, System.StringComparison.Ordinal) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, System.StringComparison.Ordinal) = 0 Then
End If
If String.Compare(a, b, System.StringComparison.Ordinal) = 0 Then
End If
If String.Compare(a, b, System.StringComparison.OrdinalIgnoreCase) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, System.StringComparison.Ordinal) = 0 Then
End If
' these can't be auto-fixed
If String.Compare(a, b, True) = 0 Then
End If
If String.Compare(a, b, True, ci) = 0 Then
End If
If String.Compare(a, b, ci, co) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, True) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, True, ci) = 0 Then
End If
If String.Compare(a, 0, b, 0, 0, ci, co) = 0 Then
End If
End Sub
End Class
");
}
#endregion
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Globalization;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Interoperability;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Globalization;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Interoperability
{
public class CA2101FixerTests : CodeFixTestBase
{
#region Verifiers
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new PInvokeDiagnosticAnalyzer();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new PInvokeDiagnosticAnalyzer();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA2101BasicCodeFixProvider();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA2101CSharpCodeFixProvider();
}
#endregion
#region CA2101 Fixer tests
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2101FixMarshalAsCSharpTest()
{
VerifyCSharpFix(@"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"")]
private static extern void Foo1([MarshalAs(UnmanagedType.LPStr)] string s, [MarshalAs(UnmanagedType.LPStr)] StringBuilder t);
[DllImport(""user32.dll"")]
private static extern void Foo2([MarshalAs((short)0)] string s);
}
", @"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"")]
private static extern void Foo1([MarshalAs(UnmanagedType.LPWStr)] string s, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder t);
[DllImport(""user32.dll"")]
private static extern void Foo2([MarshalAs(UnmanagedType.LPWStr)] string s);
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2101FixMarshalAsBasicTest()
{
VerifyBasicFix(@"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"")>
Private Shared Sub Foo1(<MarshalAs(UnmanagedType.LPStr)> s As String, <MarshalAs(UnmanagedType.LPStr)> t As StringBuilder)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Foo2(<MarshalAs(CShort(0)) s As String)
End Sub
Private Declare Sub Foo3 Lib ""user32.dll"" (<MarshalAs(UnmanagedType.LPStr)> s As String)
End Class
", @"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"")>
Private Shared Sub Foo1(<MarshalAs(UnmanagedType.LPWStr)> s As String, <MarshalAs(UnmanagedType.LPWStr)> t As StringBuilder)
End Sub
<DllImport(""user32.dll"")>
Private Shared Sub Foo2(<MarshalAs(UnmanagedType.LPWStr) s As String)
End Sub
Private Declare Sub Foo3 Lib ""user32.dll"" (<MarshalAs(UnmanagedType.LPWStr)> s As String)
End Class
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2101FixCharSetCSharpTest()
{
VerifyCSharpFix(@"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"")]
private static extern void Foo1(string s);
[DllImport(""user32.dll"", CharSet = CharSet.Ansi)]
private static extern void Foo2(string s);
}
", @"
using System.Runtime.InteropServices;
using System.Text;
class C
{
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern void Foo1(string s);
[DllImport(""user32.dll"", CharSet = CharSet.Unicode)]
private static extern void Foo2(string s);
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2101FixCharSetBasicTest()
{
VerifyBasicFix(@"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"")>
Private Shared Sub Foo1(s As String)
End Sub
<DllImport(""user32.dll"", CharSet:=CharSet.Ansi)>
Private Shared Sub Foo2(s As String)
End Sub
EndClass
", @"
Imports System.Runtime.InteropServices
Imports System.Text
Class C
<DllImport(""user32.dll"", CharSet:=CharSet.Unicode)>
Private Shared Sub Foo1(s As String)
End Sub
<DllImport(""user32.dll"", CharSet:=CharSet.Unicode)>
Private Shared Sub Foo2(s As String)
End Sub
EndClass
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2101FixDeclareBasicTest()
{
VerifyBasicFix(@"
Imports System.Text
Class C
Private Declare Sub Foo1 Lib ""user32.dll"" (s As String)
Private Declare Ansi Sub Foo2 Lib ""user32.dll"" (s As StringBuilder)
Private Declare Function Foo3 Lib ""user32.dll"" () As String
EndClass
", @"
Imports System.Text
Class C
Private Declare Unicode Sub Foo1 Lib ""user32.dll"" (s As String)
Private Declare Unicode Sub Foo2 Lib ""user32.dll"" (s As StringBuilder)
Private Declare Unicode Function Foo3 Lib ""user32.dll"" () As String
EndClass
");
}
#endregion
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Performance;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Performance;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Performance;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA1813FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA1813DiagnosticAnalyzer();
}
[WorkItem(858655)]
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA1813BasicCodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA1813DiagnosticAnalyzer();
}
[WorkItem(858655)]
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1813CSharpCodeFixProvider();
}
#region CodeFix Tests
[Fact(Skip = "Bug 858655"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1813CSharpCodeFixProviderTestFired()
{
VerifyCSharpFix(@"
public class AttributeClass : Attribute
{
}", @"
public sealed class AttributeClass : Attribute
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1813VisualBasicCodeFixProviderTestFired()
{
VerifyBasicFix(@"
Imports System
Public Class AttributeClass
Inherits Attribute
End Class", @"
Imports System
Public NotInheritable Class AttributeClass
Inherits Attribute
End Class");
}
#endregion
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Performance;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Performance;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Performance;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA1821FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new BasicCA1821DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA1821CodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CSharpCA1821DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1821CodeFixProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1821CSharpCodeFixTestRemoveEmptyFinalizers()
{
VerifyCSharpFix(@"
public class Class1
{
// Violation occurs because the finalizer is empty.
~Class1()
{
}
}
",
@"
public class Class1
{
}
");
}
[Fact(Skip = "Bug 902686"), Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1821BasicCodeFixTestRemoveEmptyFinalizers()
{
VerifyBasicFix(@"
Imports System.Diagnostics
Public Class Class1
' Violation occurs because the finalizer is empty.
Protected Overrides Sub Finalize()
End Sub
End Class
",
@"
Imports System.Diagnostics
Public Class Class1
End Class
");
}
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Usage;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Usage;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA2213FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new BasicCA2213DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA2213BasicCodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CSharpCA2213DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA2213CSharpCodeFixProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213CSharpCodeFixDisposableFiledShouldBeDisposed()
{
VerifyCSharpFix(@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
A a = new A();
public void Dispose()
{
}
}
",
@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
A a = new A();
public void Dispose()
{
a.Dispose();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213CSharpCodeFixDisposeMethodHasExplicitName()
{
VerifyCSharpFix(@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
A a = new A();
void IDisposable.Dispose()
{
}
}
",
@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
A a = new A();
void IDisposable.Dispose()
{
a.Dispose();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213CSharpCodeFixDisposeMethodHasConflictNames()
{
VerifyCSharpFix(@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
A a = new A();
void IDisposable.Dispose()
{
bool a = true;
}
}
",
@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
A a = new A();
void IDisposable.Dispose()
{
bool a = true;
this.a.Dispose();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213CSharpCodeFixDisposeMethodHasConflictStaticNames()
{
VerifyCSharpFix(@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
static A a = new A();
void IDisposable.Dispose()
{
bool a = true;
}
}
",
@"
using System;
public class A : IDisposable
{
public void Dispose()
{
}
}
public class B : IDisposable
{
static A a = new A();
void IDisposable.Dispose()
{
bool a = true;
B.a.Dispose();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213BasicCodeFixDisposableFiledShouldBeDisposed()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub 'Dispose
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Public Overloads Sub Dispose() Implements IDisposable.Dispose
a.Dispose()
End Sub 'Dispose
End Class
",
codeFixIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213BasicCodeFixDisposableFiledHasConflictName()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dim a = True
End Sub 'Dispose
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dim a = True
Me.a.Dispose()
End Sub 'Dispose
End Class
",
codeFixIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213BasicCodeFixDisposableFiledHasConflictStaticName()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Shared Dim a As A = New A()
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dim a = True
End Sub 'Dispose
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Shared Dim a As A = New A()
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dim a = True
B.a.Dispose()
End Sub 'Dispose
End Class
",
codeFixIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213BasicCodeFixDisposedMethodHasCustomName()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Sub MyDispose() Implements IDisposable.Dispose
End Sub
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Sub MyDispose() Implements IDisposable.Dispose
a.Dispose()
End Sub
End Class
",
codeFixIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213BasicCodeFixDisposableFieldHasCustomName()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub MyDispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub MyDispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Sub Dispose() Implements IDisposable.Dispose
a.MyDispose()
End Sub
End Class
",
codeFixIndex: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2213BasicCodeFixDisposedMethodAndDisposableFieldHaveCustomNames()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub MyDispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Sub MyDispose() Implements IDisposable.Dispose
End Sub
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class A
Implements IDisposable
Public Overloads Sub MyDispose() Implements IDisposable.Dispose
End Sub
End Class
Public Class B
Implements IDisposable
Dim a As A = New A()
Sub MyDispose() Implements IDisposable.Dispose
a.MyDispose()
End Sub
End Class
",
codeFixIndex: 0);
}
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Usage;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA2229FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new SerializationRulesDiagnosticAnalyzer();
}
[WorkItem(858655)]
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA2229CodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new SerializationRulesDiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA2229CodeFixProvider();
}
#region CA2229
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2229NoConstructorFix()
{
VerifyCSharpFix(@"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229NoConstructor : ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}", @"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229NoConstructor : ISerializable
{
protected CA2229NoConstructor(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new NotImplementedException();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}");
VerifyBasicFix(@"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229NoConstructor
Implements ISerializable
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class", @"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229NoConstructor
Implements ISerializable
Protected Sub New(serializationInfo As SerializationInfo, streamingContext As StreamingContext)
Throw New NotImplementedException()
End Sub
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2229HasConstructorWrongAccessibilityFix()
{
VerifyCSharpFix(@"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229HasConstructorWrongAccessibility : ISerializable
{
public CA2229HasConstructorWrongAccessibility(SerializationInfo info, StreamingContext context) { }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}", @"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2229HasConstructorWrongAccessibility : ISerializable
{
protected CA2229HasConstructorWrongAccessibility(SerializationInfo info, StreamingContext context) { }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}");
VerifyBasicFix(@"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229HasConstructorWrongAccessibility
Implements ISerializable
Public Sub New(info As SerializationInfo, context As StreamingContext)
End Sub
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class", @"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2229HasConstructorWrongAccessibility
Implements ISerializable
Protected Sub New(info As SerializationInfo, context As StreamingContext)
End Sub
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2229HasConstructorWrongAccessibility2Fix()
{
VerifyCSharpFix(@"
using System;
using System.Runtime.Serialization;
[Serializable]
public sealed class CA2229HasConstructorWrongAccessibility2 : ISerializable
{
protected internal CA2229HasConstructorWrongAccessibility2(SerializationInfo info, StreamingContext context) { }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}", @"
using System;
using System.Runtime.Serialization;
[Serializable]
public sealed class CA2229HasConstructorWrongAccessibility2 : ISerializable
{
private CA2229HasConstructorWrongAccessibility2(SerializationInfo info, StreamingContext context) { }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}");
VerifyBasicFix(@"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public NotInheritable Class CA2229HasConstructorWrongAccessibility2
Implements ISerializable
Protected Friend Sub New(info As SerializationInfo, context As StreamingContext)
End Sub
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class", @"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public NotInheritable Class CA2229HasConstructorWrongAccessibility2
Implements ISerializable
Private Sub New(info As SerializationInfo, context As StreamingContext)
End Sub
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class");
}
#endregion
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Usage;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Usage;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Usage;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA2231FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA2231DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA2231BasicCodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA2231DiagnosticAnalyzer();
}
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA2231CSharpCodeFixProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2231CSharpCodeFixNoEqualsOperator()
{
VerifyCSharpFix(@"
using System;
// value type without overridding Equals
public struct A
{
public override bool Equals(Object obj)
{
return true;
}
}
",
@"
using System;
// value type without overridding Equals
public struct A
{
public override bool Equals(Object obj)
{
return true;
}
public static bool operator ==(A left, A right)
{
throw new NotImplementedException();
}
public static bool operator !=(A left, A right)
{
throw new NotImplementedException();
}
}
",
// This fix introduces the compiler warning:
// Test0.cs(5,15): warning CS0661: 'A' defines operator == or operator != but does not override Object.GetHashCode()
allowNewCompilerDiagnostics: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2231BasicCodeFixNoEqualsOperator()
{
VerifyBasicFix(@"
Imports System
Public Structure A
Public Overloads Overrides Function Equals(obj As Object) As Boolean
Return True
End Function
End Structure
",
@"
Imports System
Public Structure A
Public Overloads Overrides Function Equals(obj As Object) As Boolean
Return True
End Function
Public Shared Operator =(left As A, right As A) As Boolean
Throw New NotImplementedException()
End Operator
Public Shared Operator <>(left As A, right As A) As Boolean
Throw New NotImplementedException()
End Operator
End Structure
");
}
}
}
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Usage;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class CA2237FixerTests : CodeFixTestBase
{
protected override IDiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new SerializationRulesDiagnosticAnalyzer();
}
[WorkItem(858655)]
protected override ICodeFixProvider GetBasicCodeFixProvider()
{
return new CA2237CodeFixProvider();
}
protected override IDiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new SerializationRulesDiagnosticAnalyzer();
}
[WorkItem(858655)]
protected override ICodeFixProvider GetCSharpCodeFixProvider()
{
return new CA2237CodeFixProvider();
}
#region CA2237
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA2237SerializableMissingAttrFix()
{
VerifyCSharpFix(@"
using System;
using System.Runtime.Serialization;
public class CA2237SerializableMissingAttr : ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}",
@"
using System;
using System.Runtime.Serialization;
[Serializable]
public class CA2237SerializableMissingAttr : ISerializable
{
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}",
codeFixIndex: 0);
VerifyBasicFix(@"
Imports System
Imports System.Runtime.Serialization
Public Class CA2237SerializableMissingAttr
Implements ISerializable
Protected Sub New(context As StreamingContext, info As SerializationInfo)
End Sub
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class",
@"
Imports System
Imports System.Runtime.Serialization
<Serializable>
Public Class CA2237SerializableMissingAttr
Implements ISerializable
Protected Sub New(context As StreamingContext, info As SerializationInfo)
End Sub
Public Sub GetObjectData(info as SerializationInfo, context as StreamingContext)
throw new NotImplementedException()
End Sub
End Class",
codeFixIndex: 0);
}
#endregion
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl.Immutable" version="1.1.20-beta" targetFramework="net45" />
<package id="Microsoft.Net.ToolsetCompilers" version="0.7.4032713-beta" targetFramework="net45" developmentDependency="true" />
<package id="xunit" version="2.0.0-alpha-build2576" targetFramework="net45" />
<package id="xunit.abstractions" version="2.0.0-alpha-build2576" targetFramework="net45" />
<package id="xunit.assert" version="2.0.0-alpha-build2576" targetFramework="net45" />
<package id="xunit.core" version="2.0.0-alpha-build2576" targetFramework="net45" />
</packages>
\ No newline at end of file
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.FxCopAnalyzers.Usage
Namespace Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Usage
<ExportCodeFixProvider("CA2229 CodeFix provider", LanguageNames.VisualBasic)>
Public Class CA2235BasicCodeFixProvider
Inherits CA2235CodeFixProviderBase
Protected Overrides Function GetFieldDeclarationNode(node As SyntaxNode) As SyntaxNode
Dim fieldNode = node
While fieldNode IsNot Nothing AndAlso fieldNode.VisualBasicKind() <> VisualBasic.SyntaxKind.FieldDeclaration
fieldNode = fieldNode.Parent
End While
Return If(fieldNode.VisualBasicKind() = VisualBasic.SyntaxKind.FieldDeclaration, fieldNode, Nothing)
End Function
End Class
End Namespace
\ No newline at end of file
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册