提交 3a54c091 编写于 作者: S Srivatsn Narayanan

Create new projects for System.Runtime.Analyzers

Move rule CA1001 to this project. Rewrite the codefixer for it to be based on DocumentEditor and hence language agnostic.

Fix for CA1001 shouldn't generate a dispose method if there is already one in the type. Instead modify that method to make it the interface implementation.
Adding some tests.
上级 4f147f5b
......@@ -73,7 +73,6 @@
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="Design\CodeFixes\CA1001CSharpCodeFixProvider.cs" />
<Compile Include="Design\CodeFixes\CA1008CSharpCodeFixProvider.cs" />
<Compile Include="Design\CodeFixes\CA1052CSharpCodeFixProvider.cs" />
<Compile Include="Design\CodeFixes\EnumWithFlagsCSharpCodeFixProvider.cs" />
......@@ -107,4 +106,4 @@
<Import Project="..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
</Project>
\ No newline at end of file
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
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(LanguageNames.CSharp, Name = CA1001DiagnosticAnalyzer.RuleId), Shared]
public class CA1001CSharpCodeFixProvider : CA1001CodeFixProviderBase
{
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, 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.SimpleBaseType(SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable))).AddMembers(new[] { member }) :
syntaxNode.AddBaseListTypes(SyntaxFactory.SimpleBaseType(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());
}
}
}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
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 ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CA1001DiagnosticAnalyzer.RuleId); }
}
protected sealed override string GetCodeFixDescription(Diagnostic diagnostic)
{
return FxCopFixersResources.ImplementIDisposableInterface;
}
}
}
......@@ -103,7 +103,6 @@
<Compile Include="CodeFixProviderBase.cs" />
<Compile Include="DiagnosticCustomTags.cs" />
<Compile Include="Design\AssemblyAttributesDiagnosticAnalyzer.cs" />
<Compile Include="Design\CA1001DiagnosticAnalyzer.cs" />
<Compile Include="Design\CA1003DiagnosticAnalyzer.cs" />
<Compile Include="Design\CA1008DiagnosticAnalyzer.cs" />
<Compile Include="Design\CA1012DiagnosticAnalyzer.cs" />
......@@ -112,7 +111,6 @@
<Compile Include="Design\CA1019DiagnosticAnalyzer.cs" />
<Compile Include="Design\CA1024DiagnosticAnalyzer.cs" />
<Compile Include="Design\CA1060DiagnosticAnalyzer.cs" />
<Compile Include="Design\CodeFixes\CA1001CodeFixProviderBase.cs" />
<Compile Include="Design\CodeFixes\CA1008CodeFixProviderBase.cs" />
<Compile Include="Design\CodeFixes\CA1012CodeFixProvider.cs" />
<Compile Include="Design\CodeFixes\EnumWithFlagsCodeFixProviderBase.cs" />
......@@ -195,4 +193,4 @@
<Import Project="..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project ToolsVersion="14.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="..\..\..\..\..\build\VSL.Settings.Closed.targets" />
</ImportGroup>
<PropertyGroup>
<MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{921B412A-5551-4853-82B4-46AD5A05A03E}</ProjectGuid>
<OutputType>Library</OutputType>
<AnalyzerProject>true</AnalyzerProject>
<RootNamespace>System.Runtime.CSharp.Analyzers</RootNamespace>
<AssemblyName>System.Runtime.CSharp.Analyzers</AssemblyName>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkProfile>Profile7</TargetFrameworkProfile>
<TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
<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="..\..\..\..\Workspaces\Core\Portable\Workspaces.csproj">
<Project>{5f8d2414-064a-4b3a-9b42-8e2a04246be5}</Project>
<Name>Workspaces</Name>
</ProjectReference>
<ProjectReference Include="..\Core\SystemRuntimeAnalyzers.csproj">
<Project>{d8762a0a-3832-47be-bcf6-8b1060be6b28}</Project>
<Name>SystemRuntimeAnalyzers</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Reference Include="System.Collections.Immutable, Version=1.1.33.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\System.Collections.Immutable.1.1.33-beta\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Composition.AttributedModel, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Convention, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Hosting, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Runtime, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Composition.TypedParts, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.TypedParts.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Folder Include="Design\" />
</ItemGroup>
<ImportGroup Label="Targets">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="..\..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="System.Collections.Immutable" version="1.1.33-beta" targetFramework="net45" />
<package id="Microsoft.Composition" version="1.0.27" targetFramework="net45" />
<package id="StyleCop.MSBuild" version="4.7.48.2" targetFramework="net45" developmentDependency="true" />
</packages>
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
namespace System.Runtime.Analyzers
{
public abstract class CodeFixProviderBase : CodeFixProvider
{
protected abstract string GetCodeFixDescription(Diagnostic diagnostic);
internal abstract Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken);
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var cancellationToken = context.CancellationToken;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in context.Diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
var nodeToFix = root.FindNode(diagnostic.Location.SourceSpan);
var newDocument = await GetUpdatedDocumentAsync(document, model, root, nodeToFix, diagnostic, cancellationToken).ConfigureAwait(false);
Debug.Assert(newDocument != null);
if (newDocument != document)
{
var codeFixDescription = GetCodeFixDescription(diagnostic);
context.RegisterCodeFix(new MyCodeAction(codeFixDescription, newDocument), diagnostic);
}
}
}
private class MyCodeAction : DocumentChangeAction
{
public MyCodeAction(string title, Document newDocument) :
base(title, c => Task.FromResult(newDocument))
{
}
}
}
}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
namespace System.Runtime.Analyzers
{
/// <summary>
/// CA1001: Types that own disposable fields should be disposable
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared]
public class TypesThatOwnDisposableFieldsShouldBeDisposableFixer : CodeFixProvider
{
protected const string NotImplementedExceptionName = "System.NotImplementedException";
protected const string IDisposableName = "System.IDisposable";
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer.RuleId); }
}
protected string GetCodeFixDescription(Diagnostic diagnostic)
{
return SystemRuntimeAnalyzersResources.ImplementIDisposableInterface;
}
public async override Task RegisterCodeFixesAsync(CodeFixContext context)
{
var generator = SyntaxGenerator.GetGenerator(context.Document);
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var declaration = root.FindNode(context.Span);
declaration = generator.GetDeclaration(declaration);
if (declaration == null)
{
return;
}
// We cannot have multiple overlapping diagnostics of this id.
var diagnostic = context.Diagnostics.Single();
context.RegisterCodeFix(new DocumentChangeAction(SystemRuntimeAnalyzersResources.ImplementIDisposableInterface,
async ct => await ImplementIDisposable(context.Document, declaration, ct).ConfigureAwait(false)),
diagnostic);
}
private async Task<Document> ImplementIDisposable(Document document, SyntaxNode declaration, CancellationToken cancellationToken)
{
DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;
var model = editor.SemanticModel;
// Add the interface to the baselist.
var interfaceType = generator.TypeExpression(WellKnownTypes.IDisposable(model.Compilation));
editor.AddInterfaceType(declaration, interfaceType);
// Find a Dispose method. If one exists make that implement IDisposable, else generate a new method.
var typeSymbol = model.GetDeclaredSymbol(declaration) as INamedTypeSymbol;
var disposeMethod = (typeSymbol?.GetMembers("Dispose"))?.OfType<IMethodSymbol>()?.Where(m => m.Parameters.Length == 0).FirstOrDefault();
if (disposeMethod != null && disposeMethod.DeclaringSyntaxReferences.Length == 1)
{
var memberPartNode = await disposeMethod.DeclaringSyntaxReferences.Single().GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
memberPartNode = generator.GetDeclaration(memberPartNode);
editor.ReplaceNode(memberPartNode, generator.AsPublicInterfaceImplementation(memberPartNode, interfaceType));
}
else
{
var throwStatement = generator.ThrowStatement(generator.ObjectCreationExpression(WellKnownTypes.NotImplementedException(model.Compilation)));
var member = generator.MethodDeclaration(TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer.Dispose, statements: new[] { throwStatement });
member = generator.AsPublicInterfaceImplementation(member, interfaceType);
editor.AddMember(declaration, member);
}
return editor.GetChangedDocument();
}
}
}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Design
namespace System.Runtime.Analyzers
{
/// <summary>
/// CA1001: Types that own disposable fields should be disposable
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class CA1001DiagnosticAnalyzer : AbstractNamedTypeAnalyzer
public sealed class TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1001";
internal const string Dispose = "Dispose";
internal const string IDisposable = "System.IDisposable";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(RuleId,
new LocalizableResourceString(nameof(FxCopRulesResources.TypesThatOwnDisposableFieldsShouldBeDisposable), FxCopRulesResources.ResourceManager, typeof(FxCopRulesResources)),
new LocalizableResourceString(nameof(FxCopRulesResources.TypeOwnsDisposableFieldButIsNotDisposable), FxCopRulesResources.ResourceManager, typeof(FxCopRulesResources)),
FxCopDiagnosticCategory.Design,
new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.TypesThatOwnDisposableFieldsShouldBeDisposable), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)),
new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.TypeOwnsDisposableFieldButIsNotDisposable), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources)),
DiagnosticCategory.Design,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: "http://msdn.microsoft.com/library/ms182172.aspx",
customTags: DiagnosticCustomTags.Microsoft);
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
......@@ -38,7 +36,16 @@ public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
}
}
protected override void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterSymbolAction(context =>
{
AnalyzeSymbol((INamedTypeSymbol)context.Symbol, context.Compilation, context.ReportDiagnostic, context.Options, context.CancellationToken);
},
SymbolKind.NamedType);
}
private static void AnalyzeSymbol(INamedTypeSymbol symbol, Compilation compilation, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
{
var disposableType = WellKnownTypes.IDisposable(compilation);
if (disposableType != null && !symbol.AllInterfaces.Contains(disposableType))
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace System.Runtime.Analyzers
{
internal static class DiagnosticCategory
{
public static readonly string Design = SystemRuntimeAnalyzersResources.CategoryDesign;
public static readonly string Globalization = SystemRuntimeAnalyzersResources.CategoryGlobalization;
public static readonly string Interoperability = SystemRuntimeAnalyzersResources.CategoryInteroperability;
public static readonly string Performance = SystemRuntimeAnalyzersResources.CategoryPerformance;
public static readonly string Reliability = SystemRuntimeAnalyzersResources.CategoryReliability;
public static readonly string Usage = SystemRuntimeAnalyzersResources.CategoryUsage;
public static readonly string Naming = SystemRuntimeAnalyzersResources.CategoryNaming;
}
}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace System.Runtime.Analyzers
{
internal static class DiagnosticExtensions
{
public static IEnumerable<Diagnostic> CreateDiagnostics(
this IEnumerable<SyntaxNode> nodes,
DiagnosticDescriptor rule,
params object[] args)
{
foreach (var node in nodes)
{
yield return node.CreateDiagnostic(rule, args);
}
}
public static Diagnostic CreateDiagnostic(
this SyntaxNode node,
DiagnosticDescriptor rule,
params object[] args)
{
return node.GetLocation().CreateDiagnostic(rule, args);
}
public static IEnumerable<Diagnostic> CreateDiagnostics(
this IEnumerable<SyntaxToken> tokens,
DiagnosticDescriptor rule,
params object[] args)
{
foreach (var token in tokens)
{
yield return token.CreateDiagnostic(rule, args);
}
}
public static Diagnostic CreateDiagnostic(
this SyntaxToken token,
DiagnosticDescriptor rule,
params object[] args)
{
return token.GetLocation().CreateDiagnostic(rule, args);
}
public static IEnumerable<Diagnostic> CreateDiagnostics(
this IEnumerable<SyntaxNodeOrToken> nodesOrTokens,
DiagnosticDescriptor rule,
params object[] args)
{
foreach (var nodeOrToken in nodesOrTokens)
{
yield return nodeOrToken.CreateDiagnostic(rule, args);
}
}
public static Diagnostic CreateDiagnostic(
this SyntaxNodeOrToken nodeOrToken,
DiagnosticDescriptor rule,
params object[] args)
{
return nodeOrToken.GetLocation().CreateDiagnostic(rule, args);
}
public static IEnumerable<Diagnostic> CreateDiagnostics(
this IEnumerable<ISymbol> symbols,
DiagnosticDescriptor rule,
params object[] args)
{
foreach (var symbol in symbols)
{
yield return symbol.CreateDiagnostic(rule, args);
}
}
public static Diagnostic CreateDiagnostic(
this ISymbol symbol,
DiagnosticDescriptor rule,
params object[] args)
{
return symbol.Locations.CreateDiagnostic(rule, args);
}
public static IEnumerable<Diagnostic> CreateDiagnostics(
this IEnumerable<Location> locations,
DiagnosticDescriptor rule,
params object[] args)
{
foreach (var location in locations)
{
yield return location.CreateDiagnostic(rule, args);
}
}
public static Diagnostic CreateDiagnostic(
this Location location,
DiagnosticDescriptor rule,
params object[] args)
{
if (!location.IsInSource)
{
return Diagnostic.Create(rule, null, args);
}
return Diagnostic.Create(rule, location, args);
}
public static IEnumerable<Diagnostic> CreateDiagnostics(
this IEnumerable<IEnumerable<Location>> setOfLocations,
DiagnosticDescriptor rule,
params object[] args)
{
foreach (var locations in setOfLocations)
{
yield return locations.CreateDiagnostic(rule, args);
}
}
public static Diagnostic CreateDiagnostic(
this IEnumerable<Location> locations,
DiagnosticDescriptor rule,
params object[] args)
{
var location = locations.First(l => l.IsInSource);
var additionalLocations = locations.Where(l => l.IsInSource).Skip(1);
return Diagnostic.Create(rule,
location: location,
additionalLocations: additionalLocations,
messageArgs: args);
}
}
}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis
{
internal class DocumentChangeAction : CodeAction
{
private readonly string _title;
private readonly Func<CancellationToken, Task<Document>> _createChangedDocument;
public DocumentChangeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
{
_title = title;
_createChangedDocument = createChangedDocument;
}
public override string Title
{
get { return _title; }
}
protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
return _createChangedDocument(cancellationToken);
}
}
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project ToolsVersion="14.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="..\..\..\..\..\build\VSL.Settings.Closed.targets" />
</ImportGroup>
<PropertyGroup>
<MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D8762A0A-3832-47BE-BCF6-8B1060BE6B28}</ProjectGuid>
<OutputType>Library</OutputType>
<AnalyzerProject>true</AnalyzerProject>
<RootNamespace>System.Runtime.Analyzers</RootNamespace>
<AssemblyName>System.Runtime.Analyzers</AssemblyName>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkProfile>Profile7</TargetFrameworkProfile>
<TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1ee8cad3-55f9-4d91-96b2-084641da9a6c}</Project>
<Name>CodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\Core\Portable\Workspaces.csproj">
<Project>{5f8d2414-064a-4b3a-9b42-8e2a04246be5}</Project>
<Name>Workspaces</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Reference Include="System.Collections.Immutable, Version=1.1.33.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\System.Collections.Immutable.1.1.33-beta\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Composition.AttributedModel, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="System.Runtime.CSharp.Analyzers" />
<InternalsVisibleTo Include="System.Runtime.VisualBasic.Analyzers" />
<InternalsVisibleToTest Include="System.Runtime.Analyzers.UnitTests" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeFixProviderBase.cs" />
<Compile Include="Design\TypesThatOwnDisposableFieldsShouldBeDisposable.Fixer.cs" />
<Compile Include="Design\TypesThatOwnDisposableFieldsShouldBeDisposable.cs" />
<Compile Include="DiagnosticCategory.cs" />
<Compile Include="DiagnosticExtensions.cs" />
<Compile Include="DocumentChangeAction.cs" />
<Compile Include="SystemRuntimeAnalyzersResources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>SystemRuntimeAnalyzersResources.resx</DependentUpon>
</Compile>
<Compile Include="WellKnownTypes.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="SystemRuntimeAnalyzersResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>SystemRuntimeAnalyzersResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup />
<ImportGroup Label="Targets">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="..\..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace System.Runtime.Analyzers {
using System;
using System.Reflection;
/// <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 SystemRuntimeAnalyzersResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal SystemRuntimeAnalyzersResources() {
}
/// <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("System.Runtime.Analyzers.SystemRuntimeAnalyzersResources", typeof(SystemRuntimeAnalyzersResources).GetTypeInfo().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 Design.
/// </summary>
internal static string CategoryDesign {
get {
return ResourceManager.GetString("CategoryDesign", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Globalization.
/// </summary>
internal static string CategoryGlobalization {
get {
return ResourceManager.GetString("CategoryGlobalization", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Interoperability.
/// </summary>
internal static string CategoryInteroperability {
get {
return ResourceManager.GetString("CategoryInteroperability", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Naming.
/// </summary>
internal static string CategoryNaming {
get {
return ResourceManager.GetString("CategoryNaming", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Performance.
/// </summary>
internal static string CategoryPerformance {
get {
return ResourceManager.GetString("CategoryPerformance", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reliability.
/// </summary>
internal static string CategoryReliability {
get {
return ResourceManager.GetString("CategoryReliability", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Usage.
/// </summary>
internal static string CategoryUsage {
get {
return ResourceManager.GetString("CategoryUsage", 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 Type &apos;{0}&apos; owns disposable fields but is not disposable.
/// </summary>
internal static string TypeOwnsDisposableFieldButIsNotDisposable {
get {
return ResourceManager.GetString("TypeOwnsDisposableFieldButIsNotDisposable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Types that own disposable fields should be disposable.
/// </summary>
internal static string TypesThatOwnDisposableFieldsShouldBeDisposable {
get {
return ResourceManager.GetString("TypesThatOwnDisposableFieldsShouldBeDisposable", 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="TypesThatOwnDisposableFieldsShouldBeDisposable" xml:space="preserve">
<value>Types that own disposable fields should be disposable</value>
</data>
<data name="CategoryDesign" xml:space="preserve">
<value>Design</value>
</data>
<data name="CategoryGlobalization" xml:space="preserve">
<value>Globalization</value>
</data>
<data name="CategoryInteroperability" xml:space="preserve">
<value>Interoperability</value>
</data>
<data name="CategoryNaming" xml:space="preserve">
<value>Naming</value>
</data>
<data name="CategoryPerformance" xml:space="preserve">
<value>Performance</value>
</data>
<data name="CategoryReliability" xml:space="preserve">
<value>Reliability</value>
</data>
<data name="CategoryUsage" xml:space="preserve">
<value>Usage</value>
</data>
<data name="ImplementIDisposableInterface" xml:space="preserve">
<value>Implement IDisposable Interface</value>
</data>
<data name="TypeOwnsDisposableFieldButIsNotDisposable" xml:space="preserve">
<value>Type '{0}' owns disposable fields but is not disposable</value>
</data>
</root>
\ No newline at end of file
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
namespace System.Runtime.Analyzers
{
internal static class WellKnownTypes
{
public static INamedTypeSymbol FlagsAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.FlagsAttribute");
}
public static INamedTypeSymbol StringComparison(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.StringComparison");
}
public static INamedTypeSymbol CharSet(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.CharSet");
}
public static INamedTypeSymbol DllImportAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.DllImportAttribute");
}
public static INamedTypeSymbol MarshalAsAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.MarshalAsAttribute");
}
public static INamedTypeSymbol StringBuilder(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Text.StringBuilder");
}
public static INamedTypeSymbol UnmanagedType(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.UnmanagedType");
}
public static INamedTypeSymbol MarshalByRefObject(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.MarshalByRefObject");
}
public static INamedTypeSymbol ExecutionEngineException(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.ExecutionEngineException");
}
public static INamedTypeSymbol OutOfMemoryException(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.OutOfMemoryException");
}
public static INamedTypeSymbol StackOverflowException(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.StackOverflowException");
}
public static INamedTypeSymbol MemberInfo(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Reflection.MemberInfo");
}
public static INamedTypeSymbol ParameterInfo(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Reflection.ParameterInfo");
}
public static INamedTypeSymbol Thread(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Threading.Thread");
}
public static INamedTypeSymbol WebUIControl(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Web.UI.Control");
}
public static INamedTypeSymbol WinFormsUIControl(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Windows.Forms.Control");
}
public static INamedTypeSymbol IDisposable(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.IDisposable");
}
public static INamedTypeSymbol ISerializable(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.Serialization.ISerializable");
}
public static INamedTypeSymbol SerializationInfo(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.Serialization.SerializationInfo");
}
public static INamedTypeSymbol StreamingContext(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.Serialization.StreamingContext");
}
public static INamedTypeSymbol SerializableAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.SerializableAttribute");
}
public static INamedTypeSymbol NonSerializedAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.NonSerializedAttribute");
}
public static INamedTypeSymbol AttributeUsageAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.AttributeUsageAttribute");
}
public static INamedTypeSymbol AssemblyVersionAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Reflection.AssemblyVersionAttribute");
}
public static INamedTypeSymbol CLSCompliantAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.CLSCompliantAttribute");
}
public static INamedTypeSymbol ConditionalAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Diagnostics.ConditionalAttribute");
}
public static INamedTypeSymbol IComparable(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.IComparable");
}
public static INamedTypeSymbol ComSourceInterfaceAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.ComSourceInterfacesAttribute");
}
public static INamedTypeSymbol EventHandler(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.EventHandler");
}
public static INamedTypeSymbol GenericEventHandler(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.EventHandler`1");
}
public static INamedTypeSymbol EventArgs(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.EventArgs");
}
public static INamedTypeSymbol ComVisibleAttribute(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.Runtime.InteropServices.ComVisibleAttribute");
}
public static INamedTypeSymbol NotImplementedException(Compilation compilation)
{
return compilation.GetTypeByMetadataName("System.NotImplementedException");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="System.Collections.Immutable" version="1.1.33-beta" targetFramework="net45" />
<package id="Microsoft.Composition" version="1.0.27" targetFramework="net45" />
<package id="StyleCop.MSBuild" version="4.7.48.2" targetFramework="net45" developmentDependency="true" />
</packages>
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project 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="..\..\..\..\..\build\VSL.Settings.Closed.targets" />
</ImportGroup>
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<ProjectGuid>{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>System.Runtime.Analyzers.UnitTests</RootNamespace>
<AssemblyName>System.Runtime.Analyzers.UnitTests</AssemblyName>
<Nonshipping>true</Nonshipping>
<SolutionDir Condition="'$(SolutionDir)' == '' OR '$(SolutionDir)' == '*Undefined*'">..\..\..\..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Desktop\CodeAnalysis.Desktop.csproj">
<Project>{dfa21ca1-7f96-47ee-940c-069858e81727}</Project>
<Name>CodeAnalysis.Desktop</Name>
</ProjectReference>
<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\VisualBasic\Desktop\BasicCodeAnalysis.Desktop.vbproj">
<Project>{73f3e2c5-d742-452e-b9e1-20732ddbc75d}</Project>
<Name>BasicCodeAnalysis.Desktop</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\Portable\CSharpWorkspace.csproj">
<Project>{21B239D0-D144-430F-A394-C066D58EE267}</Project>
<Name>CSharpWorkspace</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\VisualBasic\Portable\BasicWorkspace.vbproj">
<Project>{57CA988D-F010-4BF2-9A2E-07D6DCD2FF2C}</Project>
<Name>BasicWorkspace</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\Core\Portable\Workspaces.csproj">
<Project>{5F8D2414-064A-4B3A-9B42-8E2A04246BE5}</Project>
<Name>Workspaces</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\Test\Utilities\DiagnosticsTestUtilities.csproj">
<Project>{0A0621F2-D1DC-47FF-B643-C6646557505E}</Project>
<Name>DiagnosticsTestUtilities</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\CompilerTestResources.vbproj">
<Project>{7FE6B002-89D8-4298-9B1B-0B5C247DD1FD}</Project>
<Name>CompilerTestResources</Name>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
<ProjectReference Include="..\Core\SystemRuntimeAnalyzers.csproj">
<Project>{d8762a0a-3832-47be-bcf6-8b1060be6b28}</Project>
<Name>SystemRuntimeAnalyzers</Name>
</ProjectReference>
<ProjectReference Include="..\CSharp\CSharpSystemRuntimeAnalyzers.csproj">
<Project>{921b412a-5551-4853-82b4-46ad5a05a03e}</Project>
<Name>CSharpSystemRuntimeAnalyzers</Name>
</ProjectReference>
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Collections.Immutable, Version=1.1.33.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\System.Collections.Immutable.1.1.33-beta\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="xunit">
<HintPath>..\..\..\..\..\packages\xunit.1.9.2\lib\net20\xunit.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Compile Include="TypesThatOwnDisposableFieldsShouldBeDisposableTests.Fixer.cs" />
<Compile Include="TypesThatOwnDisposableFieldsShouldBeDisposableTests.cs" />
</ItemGroup>
<ImportGroup Label="Targets">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="..\..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="..\..\..\..\..\build\Roslyn.Toolsets.Xunit.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
\ No newline at end of file
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using 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 Microsoft.CodeAnalysis.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
namespace System.Runtime.Analyzers.UnitTests
{
public partial class CA1001FixerTests : CodeFixTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA1001DiagnosticAnalyzer();
return new TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer();
}
protected override CodeFixProvider GetBasicCodeFixProvider()
{
return new CA1001BasicCodeFixProvider();
return new TypesThatOwnDisposableFieldsShouldBeDisposableFixer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA1001DiagnosticAnalyzer();
return new TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer();
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1001CSharpCodeFixProvider();
return new TypesThatOwnDisposableFieldsShouldBeDisposableFixer();
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001CSharpCodeFixNoEqualsOperator()
public void CA1001CSharpCodeFixNoDispose()
{
VerifyCSharpFix(@"
using System;
......@@ -55,7 +54,8 @@ public NoDisposeClass()
using System.IO;
// This class violates the rule.
public class NoDisposeClass : IDisposable
public class NoDisposeClass
: IDisposable
{
FileStream newFile;
......@@ -73,7 +73,7 @@ public void Dispose()
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001BasicCodeFixNoEqualsOperator()
public void CA1001BasicCodeFixNoDispose()
{
VerifyBasicFix(@"
Imports System
......@@ -104,7 +104,149 @@ Sub New()
newFile = New FileStream("""", FileMode.Append)
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001CSharpCodeFixHasDispose()
{
VerifyCSharpFix(@"
using System;
using System.IO;
// This class violates the rule.
public class NoDisposeClass
{
FileStream newFile;
void Dispose() {
// Some content
}
}
",
@"
using System;
using System.IO;
// This class violates the rule.
public class NoDisposeClass
: IDisposable
{
FileStream newFile;
public void Dispose() {
// Some content
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001CSharpCodeFixHasWrongDispose()
{
VerifyCSharpFix(@"
using System;
using System.IO;
// This class violates the rule.
public partial class NoDisposeClass
{
FileStream newFile;
void Dispose(int x) {
// Some content
}
}
",
@"
using System;
using System.IO;
// This class violates the rule.
public partial class NoDisposeClass
: IDisposable
{
FileStream newFile;
void Dispose(int x) {
// Some content
}
public void Dispose()
{
throw new NotImplementedException();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001BasicCodeFixHasDispose()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class NoDisposeMethod
Dim newFile As FileStream
Sub Dispose()
End Sub
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class NoDisposeMethod
Implements IDisposable
Dim newFile As FileStream
Sub Dispose() Implements IDisposable.Dispose
End Sub
End Class
");
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CA1001BasicCodeFixHasWrongDispose()
{
VerifyBasicFix(@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class NoDisposeMethod
Dim newFile As FileStream
Sub Dispose(x As Integer)
End Sub
End Class
",
@"
Imports System
Imports System.IO
' This class violates the rule.
Public Class NoDisposeMethod
Implements IDisposable
Dim newFile As FileStream
Sub Dispose(x As Integer)
End Sub
Sub Dispose() Implements IDisposable.Dispose
Throw New NotImplementedException()
End Sub
End Class
......
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
namespace System.Runtime.Analyzers.UnitTests
{
public partial class CA1001Tests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA1001DiagnosticAnalyzer();
return new TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA1001DiagnosticAnalyzer();
return new TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer();
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
......
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="StyleCop.MSBuild" version="4.7.48.2" targetFramework="net45" developmentDependency="true" />
<package id="System.Collections.Immutable" version="1.1.33-beta" targetFramework="net45" />
<package id="xunit" version="1.9.2" targetFramework="net45" />
</packages>
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -->
<Project ToolsVersion="14.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="..\..\..\..\..\build\VSL.Settings.Closed.targets" />
</ImportGroup>
<PropertyGroup>
<MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B1A6A74B-E484-48FB-8745-7A30A06DB631}</ProjectGuid>
<OutputType>Library</OutputType>
<AnalyzerProject>true</AnalyzerProject>
<AssemblyName>Microsoft.CodeAnalysis.VisualBasic.Analyzers</AssemblyName>
<ProjectTypeGuids>{14182A97-F7F0-4C62-8B27-98AA8AE2109A};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
<TargetFrameworkProfile>Profile7</TargetFrameworkProfile>
<TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\CodeAnalysis.csproj">
<Project>{1ee8cad3-55f9-4d91-96b2-084641da9a6c}</Project>
<Name>CodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\BasicCodeAnalysis.vbproj">
<Project>{2523d0e6-df32-4a3e-8ae0-a19bffae2ef6}</Project>
<Name>BasicCodeAnalysis</Name>
</ProjectReference>
<ProjectReference Include="..\..\..\..\Workspaces\Core\Portable\Workspaces.csproj">
<Project>{5f8d2414-064a-4b3a-9b42-8e2a04246be5}</Project>
<Name>Workspaces</Name>
</ProjectReference>
<ProjectReference Include="..\Core\SystemRuntimeAnalyzers.csproj">
<Project>{d8762a0a-3832-47be-bcf6-8b1060be6b28}</Project>
<Name>CodeAnalysisDiagnosticAnalyzers</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Reference Include="System.Collections.Immutable, Version=1.1.33.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\System.Collections.Immutable.1.1.33-beta\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Composition.AttributedModel, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.AttributedModel.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Convention, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Convention.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Hosting, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Hosting.dll</HintPath>
</Reference>
<Reference Include="System.Composition.Runtime, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.Runtime.dll</HintPath>
</Reference>
<Reference Include="System.Composition.TypedParts, Version=1.0.27.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\packages\Microsoft.Composition.1.0.27\lib\portable-net45+win8+wp8+wpa81\System.Composition.TypedParts.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<ImportGroup Label="Targets">
<Import Project="..\..\..\..\Tools\Microsoft.CodeAnalysis.Toolset.Open\Targets\VSL.Imports.targets" />
<Import Project="..\..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="System.Collections.Immutable" version="1.1.33-beta" targetFramework="net45" />
<package id="Microsoft.Composition" version="1.0.27" targetFramework="net45" />
<package id="StyleCop.MSBuild" version="4.7.48.2" targetFramework="net45" developmentDependency="true" />
</packages>
......@@ -80,7 +80,6 @@
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
</PropertyGroup>
<ItemGroup>
<Compile Include="Design\CA1001Tests.cs" />
<Compile Include="Design\CA1003Tests.cs" />
<Compile Include="Design\CA1008Tests.cs" />
<Compile Include="Design\CA1012Tests.cs" />
......@@ -93,7 +92,6 @@
<Compile Include="Design\CA1052Tests.cs" />
<Compile Include="Design\CA1053Tests.cs" />
<Compile Include="Design\CA1060Tests.cs" />
<Compile Include="Design\CodeFixes\CA1001FixerTests.cs" />
<Compile Include="Design\CodeFixes\CA1008FixerTests.cs" />
<Compile Include="Design\CodeFixes\CA1012FixerTests.cs" />
<Compile Include="Design\CodeFixes\EnumWithFlagsAttributesRulesFixerTests.cs" />
......@@ -150,4 +148,4 @@
<Import Project="..\..\..\..\build\Roslyn.Toolsets.Xunit.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
</Project>
\ No newline at end of file
......@@ -99,7 +99,6 @@
<Compile Include="Design\BasicCA1019DiagnosticAnalyzer.vb" />
<Compile Include="Design\BasicCA1024DiagnosticAnalyzer.vb" />
<Compile Include="Design\BasicEnumWithFlagsDiagnosticAnalyzer.vb" />
<Compile Include="Design\CodeFixes\CA1001BasicCodeFixProvider.vb" />
<Compile Include="Design\CodeFixes\CA1008BasicCodeFixProvider.vb" />
<Compile Include="Design\CodeFixes\CA1052BasicCodeFixProvider.vb" />
<Compile Include="Design\CodeFixes\EnumWithFlagsBasicCodeFixProvider.vb" />
......@@ -132,4 +131,4 @@
<Import Project="..\..\..\..\build\VSL.Imports.Closed.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
</ImportGroup>
</Project>
</Project>
\ No newline at end of file
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.FxCopAnalyzers.Design
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Design
' <summary>
' CA1001: Types that own disposable fields should be disposable
' </summary>
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=CA1001DiagnosticAnalyzer.RuleId), [Shared]>
Public Class CA1001BasicCodeFixProvider
Inherits CA1001CodeFixProviderBase
Friend Overrides Function GetUpdatedDocumentAsync(document As Document, model As SemanticModel, root As SyntaxNode, nodeToFix As SyntaxNode, diagnostic As Diagnostic, cancellationToken As CancellationToken) As Task(Of Document)
' We are going to implement IDisposable interface
'
' Public Sub Dispose() Implements IDisposable.Dispose
' Throw New NotImplementedException()
' End Sub
Dim syntaxNode = TryCast(nodeToFix, ClassStatementSyntax)
If syntaxNode Is Nothing Then
Return Task.FromResult(document)
End If
Dim statement = CreateThrowNotImplementedStatement(model)
If statement Is Nothing Then
Return Task.FromResult(document)
End If
Dim member = CreateSimpleSubBlockDeclaration(CA1001DiagnosticAnalyzer.Dispose, statement)
Dim parent = DirectCast(syntaxNode.Parent, ClassBlockSyntax)
Dim implementsStatement = SyntaxFactory.ImplementsStatement(
SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable) _
.WithAdditionalAnnotations(Simplifier.Annotation)) _
.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
Dim newNode = parent.AddMembers(New MethodBlockSyntax() {member}).AddImplements(implementsStatement).WithAdditionalAnnotations(Formatter.Annotation)
Return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(parent, newNode)))
End Function
Protected Function CreateThrowNotImplementedStatement(model As SemanticModel) As StatementSyntax
Dim exceptionType = model.Compilation.GetTypeByMetadataName(NotImplementedExceptionName)
If exceptionType Is Nothing Then
' If we can't find the exception, we can't generate anything.
Return Nothing
End If
Return SyntaxFactory.ThrowStatement(
SyntaxFactory.ObjectCreationExpression(
Nothing,
SyntaxFactory.ParseTypeName(exceptionType.Name),
SyntaxFactory.ArgumentList(),
Nothing))
End Function
Protected Function CreateSimpleSubBlockDeclaration(name As String, statement As StatementSyntax) As MethodBlockSyntax
Return SyntaxFactory.SubBlock(
SyntaxFactory.SubStatement(
Nothing,
SyntaxFactory.TokenList(New SyntaxToken() {SyntaxFactory.Token(SyntaxKind.PublicKeyword)}),
SyntaxFactory.Token(SyntaxKind.SubKeyword),
SyntaxFactory.Identifier(name),
Nothing,
SyntaxFactory.ParameterList(),
Nothing,
Nothing,
SyntaxFactory.ImplementsClause(
SyntaxFactory.QualifiedName(
SyntaxFactory.ParseName(CA1001DiagnosticAnalyzer.IDisposable),
SyntaxFactory.IdentifierName(CA1001DiagnosticAnalyzer.Dispose)) _
.WithAdditionalAnnotations(Simplifier.Annotation))),
SyntaxFactory.SingletonList(statement))
End Function
End Class
End Namespace
......@@ -293,6 +293,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeAnalysisDiagnosticAnaly
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeAnalysisDiagnosticsSetup", "Diagnostics\CodeAnalysis\Setup\CodeAnalysisDiagnosticsSetup.csproj", "{54F6AE18-B0CD-4799-9DF0-9B1AAD6A78AF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "System.Runtime.Analyzers", "System.Runtime.Analyzers", "{F24D89AC-5A93-4F21-A329-DCEFD41EC0FE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SystemRuntimeAnalyzers", "Diagnostics\FxCop\System.Runtime.Analyzers\Core\SystemRuntimeAnalyzers.csproj", "{D8762A0A-3832-47BE-BCF6-8B1060BE6B28}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpSystemRuntimeAnalyzers", "Diagnostics\FxCop\System.Runtime.Analyzers\CSharp\CSharpSystemRuntimeAnalyzers.csproj", "{921B412A-5551-4853-82B4-46AD5A05A03E}"
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "BasicSystemRuntimeAnalyzers", "Diagnostics\FxCop\System.Runtime.Analyzers\VisualBasic\BasicSystemRuntimeAnalyzers.vbproj", "{B1A6A74B-E484-48FB-8745-7A30A06DB631}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SystemRuntimeAnalyzersTest", "Diagnostics\FxCop\System.Runtime.Analyzers\Test\SystemRuntimeAnalyzersTest.csproj", "{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{edc68a0e-c68d-4a74-91b7-bf38ec909888}*SharedItemsImports = 4
......@@ -802,6 +812,22 @@ Global
{54F6AE18-B0CD-4799-9DF0-9B1AAD6A78AF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{54F6AE18-B0CD-4799-9DF0-9B1AAD6A78AF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{54F6AE18-B0CD-4799-9DF0-9B1AAD6A78AF}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{D8762A0A-3832-47BE-BCF6-8B1060BE6B28}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{D8762A0A-3832-47BE-BCF6-8B1060BE6B28}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{D8762A0A-3832-47BE-BCF6-8B1060BE6B28}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{D8762A0A-3832-47BE-BCF6-8B1060BE6B28}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{921B412A-5551-4853-82B4-46AD5A05A03E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{921B412A-5551-4853-82B4-46AD5A05A03E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{921B412A-5551-4853-82B4-46AD5A05A03E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{921B412A-5551-4853-82B4-46AD5A05A03E}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{B1A6A74B-E484-48FB-8745-7A30A06DB631}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{B1A6A74B-E484-48FB-8745-7A30A06DB631}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{B1A6A74B-E484-48FB-8745-7A30A06DB631}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{B1A6A74B-E484-48FB-8745-7A30A06DB631}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8}.Release|Mixed Platforms.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......@@ -937,5 +963,10 @@ Global
{B1A6A74B-E484-48FB-8745-7A30A06DB631} = {2344BE45-7F6B-4A4E-9418-567FA2D9CA8C}
{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8} = {2344BE45-7F6B-4A4E-9418-567FA2D9CA8C}
{54F6AE18-B0CD-4799-9DF0-9B1AAD6A78AF} = {2344BE45-7F6B-4A4E-9418-567FA2D9CA8C}
{F24D89AC-5A93-4F21-A329-DCEFD41EC0FE} = {24E8CBFA-38D2-486F-B772-C10AB2DC7F01}
{D8762A0A-3832-47BE-BCF6-8B1060BE6B28} = {F24D89AC-5A93-4F21-A329-DCEFD41EC0FE}
{921B412A-5551-4853-82B4-46AD5A05A03E} = {F24D89AC-5A93-4F21-A329-DCEFD41EC0FE}
{B1A6A74B-E484-48FB-8745-7A30A06DB631} = {F24D89AC-5A93-4F21-A329-DCEFD41EC0FE}
{0C2925AD-CD97-46FA-A686-E2C1AD19DAD8} = {F24D89AC-5A93-4F21-A329-DCEFD41EC0FE}
EndGlobalSection
EndGlobal
......@@ -94,12 +94,12 @@ public static void InsertMembers(this SyntaxEditor editor, SyntaxNode declaratio
public static void AddInterfaceType(this SyntaxEditor editor, SyntaxNode declaration, SyntaxNode interfaceType)
{
editor.ReplaceNode(declaration, (d, g) => g.AddInterfaceType(declaration, interfaceType));
editor.ReplaceNode(declaration, (d, g) => g.AddInterfaceType(d, interfaceType));
}
public static void AddBaseType(this SyntaxEditor editor, SyntaxNode declaration, SyntaxNode baseType)
{
editor.ReplaceNode(declaration, (d, g) => g.AddBaseType(declaration, baseType));
editor.ReplaceNode(declaration, (d, g) => g.AddBaseType(d, baseType));
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册