-
Notifications
You must be signed in to change notification settings - Fork 102
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix Biginteger default. #1242
Open
Jim8y
wants to merge
4
commits into
neo-project:master
Choose a base branch
from
Jim8y:fix-biginteger-default
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
fix Biginteger default. #1242
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
This file contains 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 |
---|---|---|
@@ -1,6 +1,6 @@ | ||
### New Rules | ||
|
||
| Rule ID | Category | Severity | Notes | | ||
Check warning on line 3 in src/Neo.SmartContract.Analyzer/AnalyzerReleases.Unshipped.md GitHub Actions / Test
|
||
|---------|----------|----------|--------------------------------------------| | ||
| NC4002 | Type | Error | FloatUsageAnalyzer | | ||
| NC4003 | Type | Error | DecimalUsageAnalyzer | | ||
|
@@ -26,3 +26,4 @@ | |
| NC4024 | Usage | Error | MultipleCatchBlockAnalyzer | | ||
| NC4025 | Method | Error | EnumMethodsUsageAnalyzer | | ||
| NC4026 | Usage | Error | SystemDiagnosticsUsageAnalyzer | | ||
| NC4027 | Usage | Error | BigIntegerUninitializedAnalyzer | |
147 changes: 147 additions & 0 deletions
147
src/Neo.SmartContract.Analyzer/BigIntegerUninitializedAnalyzer.cs
This file contains 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,147 @@ | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using System.Collections.Immutable; | ||
using System.Composition; | ||
using System.Linq; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
|
||
namespace Neo.SmartContract.Analyzer | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public class BigIntegerUninitializedAnalyzer : DiagnosticAnalyzer | ||
{ | ||
public const string DiagnosticId = "NC4027"; | ||
|
||
private static readonly DiagnosticDescriptor Rule = new( | ||
DiagnosticId, | ||
"Uninitialized BigInteger", | ||
"BigInteger must be initialized when declared", | ||
"Usage", | ||
DiagnosticSeverity.Error, | ||
isEnabledByDefault: true); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics | ||
=> ImmutableArray.Create(Rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.EnableConcurrentExecution(); | ||
context.RegisterSyntaxNodeAction(AnalyzeSyntaxNode, SyntaxKind.VariableDeclaration); | ||
} | ||
|
||
private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context) | ||
{ | ||
var variableDeclaration = (VariableDeclarationSyntax)context.Node; | ||
|
||
// Check if the type is BigInteger | ||
if (context.SemanticModel.GetTypeInfo(variableDeclaration.Type).Type?.ToString() != "System.Numerics.BigInteger") | ||
return; | ||
|
||
// Check if the declaration is inside a struct | ||
bool isInStruct = variableDeclaration.Ancestors().OfType<StructDeclarationSyntax>().Any(); | ||
|
||
foreach (var variable in variableDeclaration.Variables) | ||
{ | ||
if (variable.Initializer == null) | ||
{ | ||
if (!isInStruct) | ||
{ | ||
// Report diagnostic for non-struct BigInteger declarations without initialization | ||
var diagnostic = Diagnostic.Create(Rule, variable.GetLocation()); | ||
context.ReportDiagnostic(diagnostic); | ||
} | ||
else | ||
{ | ||
// For structs, check if there's a constructor that initializes this field | ||
var structDeclaration = variableDeclaration.Ancestors().OfType<StructDeclarationSyntax>().First(); | ||
var constructors = structDeclaration.Members.OfType<ConstructorDeclarationSyntax>(); | ||
|
||
bool isInitializedInConstructor = false; | ||
foreach (var constructor in constructors) | ||
{ | ||
// Check if the field is initialized in any constructor | ||
var assignments = constructor.Body?.DescendantNodes() | ||
.OfType<AssignmentExpressionSyntax>() | ||
.Where(assignment => | ||
{ | ||
if (assignment.Left is MemberAccessExpressionSyntax memberAccess) | ||
{ | ||
return memberAccess.Name.Identifier.ValueText == variable.Identifier.ValueText; | ||
} | ||
return false; | ||
}); | ||
|
||
if (assignments != null && assignments.Any()) | ||
{ | ||
isInitializedInConstructor = true; | ||
break; | ||
} | ||
} | ||
|
||
// if (!isInitializedInConstructor && !constructors.Any()) | ||
// { | ||
// // Report diagnostic if the BigInteger field is not initialized in any constructor | ||
// // and there are no explicit constructors | ||
// var diagnostic = Diagnostic.Create(Rule, variable.GetLocation()); | ||
// context.ReportDiagnostic(diagnostic); | ||
// } | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(BigIntegerUninitializedCodeFixProvider)), Shared] | ||
public class BigIntegerUninitializedCodeFixProvider : CodeFixProvider | ||
{ | ||
public sealed override ImmutableArray<string> FixableDiagnosticIds | ||
=> ImmutableArray.Create(BigIntegerUninitializedAnalyzer.DiagnosticId); | ||
|
||
public sealed override FixAllProvider GetFixAllProvider() | ||
=> WellKnownFixAllProviders.BatchFixer; | ||
|
||
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
var diagnostic = context.Diagnostics.First(); | ||
var diagnosticSpan = diagnostic.Location.SourceSpan; | ||
|
||
var declaration = root?.FindToken(diagnosticSpan.Start) | ||
.Parent?.AncestorsAndSelf() | ||
.OfType<VariableDeclaratorSyntax>() | ||
.First(); | ||
|
||
if (declaration is null) return; | ||
|
||
context.RegisterCodeFix( | ||
CodeAction.Create( | ||
title: "Initialize with zero", | ||
createChangedDocument: c => InitializeWithZero(context.Document, declaration, c), | ||
equivalenceKey: "Initialize with zero"), | ||
diagnostic); | ||
} | ||
|
||
private static async Task<Document> InitializeWithZero(Document document, | ||
VariableDeclaratorSyntax declarator, | ||
CancellationToken cancellationToken) | ||
{ | ||
var initializer = SyntaxFactory.EqualsValueClause( | ||
SyntaxFactory.LiteralExpression( | ||
SyntaxKind.NumericLiteralExpression, | ||
SyntaxFactory.Literal(0))); | ||
|
||
var newDeclarator = declarator.WithInitializer(initializer); | ||
|
||
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
var newRoot = root?.ReplaceNode(declarator, newDeclarator); | ||
|
||
return document.WithSyntaxRoot(newRoot!); | ||
} | ||
} | ||
} |
This file contains 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
This file contains 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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Its better to check types with namespace