Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/Rules/MA0075.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,5 @@ MA0075.exclude_tostring_methods=true
# Report Nullable<T>.ToString when T is culture-sensitive
MA0075.consider_nullable_types=true
````

You can also annotate a type with `[Meziantou.Analyzer.Annotations.CultureInsensitiveTypeAttribute]` to disable the rule for this type.
2 changes: 2 additions & 0 deletions docs/Rules/MA0076.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ MA0076.exclude_tostring_methods=true
# Report Nullable<T>.ToString when T is culture-sensitive
MA0076.consider_nullable_types=true
````

You can also annotate a type with `[Meziantou.Analyzer.Annotations.CultureInsensitiveTypeAttribute]` to disable the rule for this type.
2 changes: 2 additions & 0 deletions docs/Rules/MA0107.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ _ = FormattableString.Invariant($"{a}"); // compliant
# Exclude ToString methods from analysis
MA0107.exclude_tostring_methods=true
````

You can also annotate a type with `[Meziantou.Analyzer.Annotations.CultureInsensitiveTypeAttribute]` to disable the rule for this type.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#pragma warning disable CS1591

using System;

namespace Meziantou.Analyzer.Annotations;

/// <summary>
/// Indicates that the type is culture insensitive. This can be used to suppress rules such as <c>MA0075</c>, <c>MA0076</c> or <c>MA0107</c>.
/// <para><code>[CultureInsensitiveType]class Foo { }</code></para>
/// <para><code>[assembly: CultureInsensitiveType(typeof(Foo))]</code></para>
/// </summary>
[System.Diagnostics.Conditional("MEZIANTOU_ANALYZER_ANNOTATIONS")]
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Struct | System.AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed class CultureInsensitiveTypeAttribute : System.Attribute
{
public CultureInsensitiveTypeAttribute() { }
public CultureInsensitiveTypeAttribute(System.Type type) => Type = type;

public Type? Type { get; }
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System.Linq;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Operations;

namespace Meziantou.Analyzer.Internals;

internal sealed class CultureSensitiveFormattingContext(Compilation compilation)
{
public INamedTypeSymbol? CultureInsensitiveTypeAttributeSymbol { get; } = compilation.GetBestTypeByMetadataName("Meziantou.Analyzer.Annotations.CultureInsensitiveTypeAttribute");
public INamedTypeSymbol? FormatProviderSymbol { get; } = compilation.GetBestTypeByMetadataName("System.IFormatProvider");
public INamedTypeSymbol? CultureInfoSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Globalization.CultureInfo");
public INamedTypeSymbol? NumberStyleSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Globalization.NumberStyles");
Expand Down Expand Up @@ -252,7 +253,28 @@ private bool IsCultureSensitiveType(ITypeSymbol? typeSymbol, CultureSensitiveOpt
if (typeSymbol.IsOrInheritFrom(SystemWindowsMediaBrushSymbol))
return false;

return typeSymbol.Implements(SystemIFormattableSymbol);
if (!typeSymbol.Implements(SystemIFormattableSymbol))
return false;

if (typeSymbol.HasAttribute(CultureInsensitiveTypeAttributeSymbol))
return false;

foreach (var attribute in compilation.Assembly.GetAttributes())
{
if (attribute.ConstructorArguments.Length != 1)
continue;

if (!attribute.AttributeClass.IsEqualTo(CultureInsensitiveTypeAttributeSymbol))
continue;

if (attribute.ConstructorArguments[0].Value is INamedTypeSymbol attributeType && attributeType.IsEqualTo(typeSymbol))
return false;
}

if (compilation.Assembly.HasAttribute(CultureInsensitiveTypeAttributeSymbol))
return false;

return true;
}

private bool IsCultureSensitiveType(ITypeSymbol? symbol, IOperation? format, IOperation? instance, CultureSensitiveOptions options)
Expand Down
8 changes: 8 additions & 0 deletions tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Meziantou.Analyzer.Annotations;
using Meziantou.Analyzer.Rules;
using Meziantou.Analyzer.Test.Helpers;
using Microsoft.CodeAnalysis;
Expand Down Expand Up @@ -191,6 +192,13 @@ public ProjectBuilder AddAsyncInterfaceApi() =>

public ProjectBuilder AddSystemTextJson() => AddNuGetReference("System.Text.Json", "4.7.2", "lib/netstandard2.0/");

public ProjectBuilder AddMeziantouAttributes()
{
var location = typeof(RequireNamedArgumentAttribute).Assembly.Location;
References.Add(MetadataReference.CreateFromFile(location));
return this;
}

public ProjectBuilder WithOutputKind(OutputKind outputKind)
{
OutputKind = outputKind;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Meziantou.Analyzer.Annotations\Meziantou.Analyzer.Annotations.csproj" />
<ProjectReference Include="..\..\src\Meziantou.Analyzer.CodeFixers\Meziantou.Analyzer.CodeFixers.csproj" />
<ProjectReference Include="..\..\src\Meziantou.Analyzer\Meziantou.Analyzer.csproj" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using Meziantou.Analyzer.Rules;
using Meziantou.Analyzer.Test.Helpers;
using TestHelper;
Expand All @@ -12,6 +12,7 @@ private static ProjectBuilder CreateProjectBuilder()
{
return new ProjectBuilder()
.WithAnalyzer<DoNotUseImplicitCultureSensitiveToStringAnalyzer>()
.AddMeziantouAttributes()
.WithTargetFramework(TargetFramework.NetLatest);
}

Expand Down Expand Up @@ -352,6 +353,76 @@ void A()
_ = "=" + (value == true);
}
}
""";
await CreateProjectBuilder()
.WithSourceCode(sourceCode)
.ValidateAsync();
}

[Fact]
public async Task IgnoreTypeUsingAssemblyAttribute()
{
var sourceCode = """
[assembly: Meziantou.Analyzer.Annotations.CultureInsensitiveTypeAttribute(typeof(System.DateTime))]

class Test
{
void A()
{
_ = "abc" + new System.DateTime();
}
}
""";
await CreateProjectBuilder()
.WithSourceCode(sourceCode)
.ValidateAsync();
}

[Fact]
public async Task IgnoreTypeUsingAttribute()
{
var sourceCode = """
class Test
{
void A()
{
_ = "abc" + new Sample();
}
}

[Meziantou.Analyzer.Annotations.CultureInsensitiveTypeAttribute]
class Sample : System.IFormattable
{
public string ToString(string? format, System.IFormatProvider? formatProvider)
{
return "abc";
}
}
""";
await CreateProjectBuilder()
.WithSourceCode(sourceCode)
.ValidateAsync();
}

[Fact]
public async Task CustomTypeImplementingIFormattable()
{
var sourceCode = """
class Test
{
void A()
{
_ = "abc" + [|new Sample()|];
}
}

class Sample : System.IFormattable
{
public string ToString(string? format, System.IFormatProvider? formatProvider)
{
return "abc";
}
}
""";
await CreateProjectBuilder()
.WithSourceCode(sourceCode)
Expand Down