- Notifications
You must be signed in to change notification settings - Fork750
Include NonCopyableAnalyzer#1615
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Closed
Uh oh!
There was an error while loading.Please reload this page.
Closed
Changes fromall commits
Commits
Show all changes
4 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
8 changes: 4 additions & 4 deletionsDirectory.Build.props
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
21 changes: 20 additions & 1 deletionpythonnet.sln
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletionssrc/noncopyable_analyzer/LICENSE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
Copyright (c) 2017 Nobuyuki Iwanaga | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
27 changes: 27 additions & 0 deletionssrc/noncopyable_analyzer/NonCopyable.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<PropertyGroup> | ||
<TargetFramework>netstandard2.0</TargetFramework> | ||
<IncludeBuildOutput>false</IncludeBuildOutput> | ||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild> | ||
<LangVersion>latest</LangVersion> | ||
</PropertyGroup> | ||
<PropertyGroup> | ||
<PackageId>PythonNet.NonCopyableAnalyzer</PackageId> | ||
<Authors>Nobuyuki Iwanaga</Authors> | ||
<PackageLicenseUrl>https://github.com/ufcpp/NonCopyableAnalyzer/blob/master/LICENSE</PackageLicenseUrl> | ||
<PackageProjectUrl>https://github.com/ufcpp/NonCopyableAnalyzer</PackageProjectUrl> | ||
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance> | ||
<Description>Analyzer for Non-copyable struct</Description> | ||
<PackageReleaseNotes>Fixed false positive on conversion operators with in argument.</PackageReleaseNotes> | ||
<PackageTags>NonCopyable, analyzers</PackageTags> | ||
<NoPackageAnalysis>true</NoPackageAnalysis> | ||
</PropertyGroup> | ||
<ItemGroup> | ||
<ProjectReference Remove="$(MSBuildThisFile)" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="2.6.0" PrivateAssets="all" /> | ||
</ItemGroup> | ||
</Project> |
256 changes: 256 additions & 0 deletionssrc/noncopyable_analyzer/NonCopyableAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,256 @@ | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
namespace NonCopyable | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public class NonCopyableAnalyzer : DiagnosticAnalyzer | ||
{ | ||
private static DiagnosticDescriptor CreateRule(int num, string type) | ||
=> new DiagnosticDescriptor("NoCopy" + num.ToString("00"), "non-copyable", "🚫 " + type + ". '{0}' is non-copyable.", "Correction", DiagnosticSeverity.Error, isEnabledByDefault: true); | ||
private static DiagnosticDescriptor FieldDeclarationRule = CreateRule(1, "field declaration"); | ||
private static DiagnosticDescriptor InitializerRule = CreateRule(2, "initializer"); | ||
private static DiagnosticDescriptor AssignmentRule = CreateRule(3, "assignment"); | ||
private static DiagnosticDescriptor ArgumentRule = CreateRule(4, "argument"); | ||
private static DiagnosticDescriptor ReturnRule = CreateRule(5, "return"); | ||
private static DiagnosticDescriptor ConversionRule = CreateRule(6, "conversion"); | ||
private static DiagnosticDescriptor PatternRule = CreateRule(7, "pattern matching"); | ||
private static DiagnosticDescriptor TupleRule = CreateRule(8, "tuple"); | ||
private static DiagnosticDescriptor MemberRule = CreateRule(9, "member reference"); | ||
private static DiagnosticDescriptor ReadOnlyInvokeRule = CreateRule(10, "readonly invoke"); | ||
private static DiagnosticDescriptor GenericConstraintRule = CreateRule(11, "generic constraint"); | ||
private static DiagnosticDescriptor DelegateRule = CreateRule(12, "delegate"); | ||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(FieldDeclarationRule, InitializerRule, AssignmentRule, ArgumentRule, ReturnRule, ConversionRule, PatternRule, TupleRule, MemberRule, ReadOnlyInvokeRule, GenericConstraintRule, DelegateRule); | ||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.RegisterCompilationStartAction(csc => | ||
{ | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
var op = (ISymbolInitializerOperation)oc.Operation; | ||
CheckCopyability(oc, op.Value, InitializerRule); | ||
}, OperationKind.FieldInitializer, | ||
OperationKind.ParameterInitializer, | ||
OperationKind.PropertyInitializer, | ||
OperationKind.VariableInitializer); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
// including member initializer | ||
// including collection element initializer | ||
var op = (ISimpleAssignmentOperation)oc.Operation; | ||
if (op.IsRef) return; | ||
CheckCopyability(oc, op.Value, AssignmentRule); | ||
}, OperationKind.SimpleAssignment); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
// including non-ref extension method invocation | ||
var op = (IArgumentOperation)oc.Operation; | ||
if (op.Parameter.RefKind != RefKind.None) return; | ||
CheckCopyability(oc, op.Value, ArgumentRule); | ||
}, OperationKind.Argument); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
var op = (IReturnOperation)oc.Operation; | ||
if (op.ReturnedValue == null) return; | ||
CheckCopyability(oc, op.ReturnedValue, ReturnRule); | ||
}, OperationKind.Return, | ||
OperationKind.YieldReturn); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
var op = (IConversionOperation)oc.Operation; | ||
var v = op.Operand; | ||
if (v.Kind == OperationKind.DefaultValue) return; | ||
var t = v.Type; | ||
if (!t.IsNonCopyable()) return; | ||
if (op.OperatorMethod != null && op.OperatorMethod.Parameters.Length == 1) | ||
{ | ||
var parameter = op.OperatorMethod.Parameters[0]; | ||
if (parameter.RefKind != RefKind.None) return; | ||
} | ||
if (op.Parent is IForEachLoopOperation && | ||
op == ((IForEachLoopOperation)op.Parent).Collection && | ||
op.Conversion.IsIdentity) | ||
{ | ||
return; | ||
} | ||
oc.ReportDiagnostic(Error(v.Syntax, ConversionRule, t.Name)); | ||
}, OperationKind.Conversion); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
var op = (IArrayInitializerOperation)oc.Operation; | ||
if (!((IArrayTypeSymbol)((IArrayCreationOperation)op.Parent).Type).ElementType.IsNonCopyable()) return; | ||
foreach (var v in op.ElementValues) | ||
{ | ||
CheckCopyability(oc, v, InitializerRule); | ||
} | ||
}, OperationKind.ArrayInitializer); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
var op = (IDeclarationPatternOperation)oc.Operation; | ||
var t = ((ILocalSymbol)op.DeclaredSymbol).Type; | ||
if (!t.IsNonCopyable()) return; | ||
oc.ReportDiagnostic(Error(op.Syntax, PatternRule, t.Name)); | ||
}, OperationKind.DeclarationPattern); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
var op = (ITupleOperation)oc.Operation; | ||
// exclude ParenthesizedVariableDesignationSyntax | ||
if (op.Syntax.Kind() != SyntaxKind.TupleExpression) return; | ||
foreach (var v in op.Elements) | ||
{ | ||
CheckCopyability(oc, v, TupleRule); | ||
} | ||
}, OperationKind.Tuple); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
// instance property/event should not be referenced with in parameter/ref readonly local/readonly field | ||
var op = (IMemberReferenceOperation)oc.Operation; | ||
CheckInstanceReadonly(oc, op.Instance, MemberRule); | ||
}, OperationKind.PropertyReference, | ||
OperationKind.EventReference); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
// instance method should not be invoked with in parameter/ref readonly local/readonly field | ||
var op = (IInvocationOperation)oc.Operation; | ||
CheckGenericConstraints(oc, op, GenericConstraintRule); | ||
CheckInstanceReadonly(oc, op.Instance, ReadOnlyInvokeRule); | ||
}, OperationKind.Invocation); | ||
csc.RegisterOperationAction(oc => { | ||
var op = (IDynamicInvocationOperation)oc.Operation; | ||
foreach(var arg in op.Arguments) { | ||
if (!arg.Type.IsNonCopyable()) continue; | ||
oc.ReportDiagnostic(Error(arg.Syntax, GenericConstraintRule)); | ||
} | ||
}, OperationKind.DynamicInvocation); | ||
csc.RegisterOperationAction(oc => | ||
{ | ||
// delagate creation | ||
var op = (IMemberReferenceOperation)oc.Operation; | ||
if (op.Instance == null) return; | ||
if (!op.Instance.Type.IsNonCopyable()) return; | ||
oc.ReportDiagnostic(Error(op.Instance.Syntax, DelegateRule, op.Instance.Type.Name)); | ||
}, OperationKind.MethodReference); | ||
csc.RegisterSymbolAction(sac => | ||
{ | ||
var f = (IFieldSymbol)sac.Symbol; | ||
if (f.IsStatic) return; | ||
if (!f.Type.IsNonCopyable()) return; | ||
if (f.ContainingType.IsReferenceType) return; | ||
if (f.ContainingType.IsNonCopyable()) return; | ||
sac.ReportDiagnostic(Error(f.DeclaringSyntaxReferences[0].GetSyntax(), FieldDeclarationRule, f.Type.Name)); | ||
}, SymbolKind.Field); | ||
}); | ||
// not supported yet: | ||
// OperationKind.CompoundAssignment, | ||
// OperationKind.UnaryOperator, | ||
// OperationKind.BinaryOperator, | ||
} | ||
private static void CheckGenericConstraints(in OperationAnalysisContext oc, IInvocationOperation op, DiagnosticDescriptor rule) | ||
{ | ||
var m = op.TargetMethod; | ||
if (m.IsGenericMethod) | ||
{ | ||
var parameters = m.TypeParameters; | ||
var arguments = m.TypeArguments; | ||
for (int i = 0; i < parameters.Length; i++) | ||
{ | ||
var p = parameters[i]; | ||
var a = arguments[i]; | ||
if (a.IsNonCopyable() && !p.IsNonCopyable()) | ||
oc.ReportDiagnostic(Error(op.Syntax, rule, a.Name)); | ||
} | ||
} | ||
} | ||
private static void CheckInstanceReadonly(in OperationAnalysisContext oc, IOperation instance, DiagnosticDescriptor rule) | ||
{ | ||
if (instance == null) return; | ||
var t = instance.Type; | ||
if (!t.IsNonCopyable()) return; | ||
if (IsInstanceReadonly(instance)) | ||
{ | ||
oc.ReportDiagnostic(Error(instance.Syntax, rule, t.Name)); | ||
} | ||
} | ||
private static Diagnostic Error(SyntaxNode at, DiagnosticDescriptor rule, string name = null) | ||
=> name is null | ||
? Diagnostic.Create(rule, at.GetLocation()) | ||
: Diagnostic.Create(rule, at.GetLocation(), name); | ||
private static bool IsInstanceReadonly(IOperation instance) | ||
{ | ||
bool isReadOnly = false; | ||
switch (instance) | ||
{ | ||
case IFieldReferenceOperation r: | ||
isReadOnly = r.Field.IsReadOnly; | ||
break; | ||
case ILocalReferenceOperation r: | ||
isReadOnly = r.Local.RefKind == RefKind.In; | ||
break; | ||
case IParameterReferenceOperation r: | ||
isReadOnly = r.Parameter.RefKind == RefKind.In; | ||
break; | ||
} | ||
return isReadOnly; | ||
} | ||
private static bool HasNonCopyableParameter(IMethodSymbol m) | ||
{ | ||
foreach (var p in m.Parameters) | ||
{ | ||
if(p.RefKind == RefKind.None) | ||
{ | ||
if (p.Type.IsNonCopyable()) return true; | ||
} | ||
} | ||
return false; | ||
} | ||
private static void CheckCopyability(in OperationAnalysisContext oc, IOperation v, DiagnosticDescriptor rule) | ||
{ | ||
var t = v.Type; | ||
if (!t.IsNonCopyable()) return; | ||
if (v.CanCopy()) return; | ||
oc.ReportDiagnostic(Error(v.Syntax, rule, t.Name)); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.