-
-
Notifications
You must be signed in to change notification settings - Fork 54
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New rule: MA0132 do not use implicit conversion from DateTime to Date…
…TimeOffset (#505)
- Loading branch information
Showing
6 changed files
with
129 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# MA0132 - Do not convert implicitly to DateTimeOffset | ||
|
||
Implicit conversions from `DateTime` to `DateTimeOffset` are dangerous. The result depends on `DateTime.Kind` which is often `Unspecified`, and so, fallback to a local time. | ||
This may not be desired. Also, this may indicate that you are mixing `DateTime` and `DateTimeOffset` in your application, which may be unintentional. | ||
|
||
````c# | ||
DateTime dt = ...; | ||
|
||
dt - DateTimeOffset.UtcNow; // non-compliant as there is an implicit conversion from DateTime to DateTimeOffset | ||
DateTimeOffset.UtcNow - DateTimeOffset.UtcNow; // ok | ||
new DateTimeOffset(dt) - DateTimeOffset.UtcNow; // ok | ||
(DateTimeOffset)dt - DateTimeOffset.UtcNow; // ok | ||
```` |
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
54 changes: 54 additions & 0 deletions
54
src/Meziantou.Analyzer/Rules/DoNotImplicitlyConvertDateTimeToDateTimeOffsetAnalyzer.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,54 @@ | ||
using System; | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
|
||
namespace Meziantou.Analyzer.Rules; | ||
|
||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public sealed class DoNotImplicitlyConvertDateTimeToDateTimeOffsetAnalyzer : DiagnosticAnalyzer | ||
{ | ||
private static readonly DiagnosticDescriptor s_rule = new( | ||
RuleIdentifiers.DoNotImplicitlyConvertDateTimeToDateTimeOffset, | ||
title: "Do not convert implicitly to DateTimeOffset", | ||
messageFormat: "Do not convert implicitly to DateTimeOffset", | ||
RuleCategories.Design, | ||
DiagnosticSeverity.Warning, | ||
isEnabledByDefault: true, | ||
description: "", | ||
helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.DoNotImplicitlyConvertDateTimeToDateTimeOffset)); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.EnableConcurrentExecution(); | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
||
context.RegisterCompilationStartAction(context => | ||
{ | ||
var datetimeOffsetSymbol = context.Compilation.GetBestTypeByMetadataName("System.DateTimeOffset"); | ||
if (datetimeOffsetSymbol == null) | ||
return; | ||
|
||
context.RegisterOperationAction(context => AnalyzeConversion(context, datetimeOffsetSymbol), OperationKind.Conversion); | ||
}); | ||
} | ||
|
||
private static void AnalyzeConversion(OperationAnalysisContext context, INamedTypeSymbol dateTimeOffsetSymbol) | ||
{ | ||
var operation = (IConversionOperation)context.Operation; | ||
if (!operation.Conversion.IsImplicit) | ||
return; | ||
|
||
if (operation.Type.IsEqualTo(dateTimeOffsetSymbol) && operation.Operand.Type.IsDateTime()) | ||
{ | ||
// DateTime.Now and DateTime.UtcNow set the DateTime.Kind, so the conversion result is well-known | ||
if (operation.Operand is IMemberReferenceOperation { Member.Name: "UtcNow" or "Now", Member.ContainingType.SpecialType: SpecialType.System_DateTime }) | ||
return; | ||
|
||
context.ReportDiagnostic(s_rule, operation); | ||
} | ||
} | ||
} |
52 changes: 52 additions & 0 deletions
52
tests/Meziantou.Analyzer.Test/Rules/DoNotCompareDateTimeWithDateTimeOffsetAnalyzerTests.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,52 @@ | ||
using System.Threading.Tasks; | ||
using Meziantou.Analyzer.Rules; | ||
using Microsoft.CodeAnalysis; | ||
using TestHelper; | ||
using Xunit; | ||
|
||
namespace Meziantou.Analyzer.Test.Rules; | ||
public class DoNotCompareDateTimeWithDateTimeOffsetAnalyzerTests | ||
{ | ||
private static ProjectBuilder CreateProjectBuilder() | ||
{ | ||
return new ProjectBuilder() | ||
.WithOutputKind(OutputKind.ConsoleApplication) | ||
.WithAnalyzer<DoNotImplicitlyConvertDateTimeToDateTimeOffsetAnalyzer>(); | ||
} | ||
|
||
[Fact] | ||
public async Task ImplicitConversion_BinaryOperation_Subtract_UtcNow() | ||
{ | ||
await CreateProjectBuilder() | ||
.WithSourceCode(""" | ||
using System; | ||
_ = DateTime.UtcNow - DateTimeOffset.UtcNow; | ||
""") | ||
.ValidateAsync(); | ||
} | ||
|
||
[Fact] | ||
public async Task ImplicitConversion_BinaryOperation_Subtract() | ||
{ | ||
await CreateProjectBuilder() | ||
.WithSourceCode(""" | ||
using System; | ||
_ = [|default(DateTime)|] - DateTimeOffset.UtcNow; | ||
""") | ||
.ValidateAsync(); | ||
} | ||
|
||
[Fact] | ||
public async Task ExplicitConversion_BinaryOperation_Subtract() | ||
{ | ||
await CreateProjectBuilder() | ||
.WithSourceCode(""" | ||
using System; | ||
_ = (DateTimeOffset)default(DateTime) - DateTimeOffset.UtcNow; | ||
""") | ||
.ValidateAsync(); | ||
} | ||
} |