Skip to content

Commit

Permalink
Merge pull request #2960 from Evangelink/enable-CA1305
Browse files Browse the repository at this point in the history
Enable rule CA1305 and fix all violations
  • Loading branch information
mavasani authored Oct 31, 2019
2 parents 68dfd4b + 9fa3104 commit e70727e
Show file tree
Hide file tree
Showing 80 changed files with 380 additions and 307 deletions.
6 changes: 1 addition & 5 deletions eng/Analyzers_ShippingRules.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,10 @@
<!-- ValidateArgumentsOfPublicMethods - only useful for libraries with supported public API surface, we don't have any -->
<Rule Id="CA1062" Action="None" />
</Rules>

<!-- TODO: Remove the below suppression once https://github.com/dotnet/roslyn-analyzers/issues/965 has been fixed. -->

<Rules AnalyzerId="System.Runtime.Analyzers" RuleNamespace="System.Runtime.Analyzers">
<!-- DoNotPassLiteralsAsLocalizedParameters - primarily useful for libraries where public APIs throw exceptions, and the messages need to be localized -->
<Rule Id="CA1303" Action="None" />

<!-- SpecifyIFormatProvider -->
<Rule Id="CA1305" Action="None" />
</Rules>

<Rules AnalyzerId="Microsoft.CodeAnalysis.Analyzers" RuleNamespace="Microsoft.CodeAnalysis.Analyzers">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// 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.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
Expand Down Expand Up @@ -110,7 +111,7 @@ private void VerifyFix(string language, DiagnosticAnalyzer analyzer, CodeFixProv
newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document));

Assert.True(false,
string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
string.Format(CultureInfo.InvariantCulture, "Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
document.GetSyntaxRootAsync().Result.ToFullString()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
Expand Down Expand Up @@ -81,7 +82,7 @@ protected void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[]
}

/// <summary>
/// General method that gets a collection of actual diagnostics found in the source after the analyzer is run,
/// General method that gets a collection of actual diagnostics found in the source after the analyzer is run,
/// then verifies each of them.
/// </summary>
/// <param name="sources">An array of strings to create source documents from to run the analyzers on</param>
Expand Down Expand Up @@ -114,7 +115,7 @@ private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResult
string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE.";

Assert.True(false,
string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
string.Format(CultureInfo.InvariantCulture, "Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput));
}

for (int i = 0; i < expectedResults.Length; i++)
Expand All @@ -127,7 +128,7 @@ private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResult
if (actual.Location != Location.None)
{
Assert.True(false,
string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}",
string.Format(CultureInfo.InvariantCulture, "Expected:\nA project diagnostic with No location\nActual:\n{0}",
FormatDiagnostics(analyzer, actual)));
}
}
Expand All @@ -139,7 +140,7 @@ private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResult
if (additionalLocations.Length != expected.Spans.Length - 1)
{
Assert.True(false,
string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n",
string.Format(CultureInfo.InvariantCulture, "Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n",
expected.Spans.Length - 1, additionalLocations.Length,
FormatDiagnostics(analyzer, actual)));
}
Expand All @@ -153,21 +154,21 @@ private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResult
if (actual.Id != expected.Id)
{
Assert.True(false,
string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
string.Format(CultureInfo.InvariantCulture, "Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Id, actual.Id, FormatDiagnostics(analyzer, actual)));
}

if (actual.Severity != expected.Severity)
{
Assert.True(false,
string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
string.Format(CultureInfo.InvariantCulture, "Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual)));
}

if (actual.GetMessage() != expected.Message)
{
Assert.True(false,
string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
string.Format(CultureInfo.InvariantCulture, "Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual)));
}
}
Expand All @@ -185,7 +186,7 @@ private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagno
FileLinePositionSpan actualSpan = actual.GetLineSpan();

Assert.True(actualSpan.Path == expected.Span.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Span.Path.Contains("Test.")),
string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
string.Format(CultureInfo.InvariantCulture, "Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Span.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic)));

Microsoft.CodeAnalysis.Text.LinePosition actualLinePosition = actualSpan.StartLinePosition;
Expand All @@ -196,7 +197,7 @@ private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagno
if (actualLinePosition.Line + 1 != expected.Span.StartLinePosition.Line)
{
Assert.True(false,
string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
string.Format(CultureInfo.InvariantCulture, "Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Span.StartLinePosition.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic)));
}
}
Expand All @@ -207,7 +208,7 @@ private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagno
if (actualLinePosition.Character + 1 != expected.Span.StartLinePosition.Character)
{
Assert.True(false,
string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
string.Format(CultureInfo.InvariantCulture, "Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n",
expected.Span.StartLinePosition.Character, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic)));
}
}
Expand Down Expand Up @@ -238,7 +239,7 @@ private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diag
Location location = diagnostics[i].Location;
if (location == Location.None)
{
builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id);
builder.AppendFormat(CultureInfo.InvariantCulture, "GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id);
}
else
{
Expand All @@ -248,7 +249,7 @@ private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diag
string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ? "GetCSharpResultAt" : "GetBasicResultAt";
Microsoft.CodeAnalysis.Text.LinePosition linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;

builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
builder.AppendFormat(CultureInfo.InvariantCulture, "{0}({1}, {2}, {3}.{4})",
resultMethodName,
linePosition.Line + 1,
linePosition.Character + 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System;
using System.Collections.Immutable;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Analyzer.Utilities;
Expand Down Expand Up @@ -33,15 +34,15 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
// Register fixes.

// 1) Apply C# DiagnosticAnalyzerAttribute.
string title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.CSharp);
string title = string.Format(CultureInfo.CurrentCulture, CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.CSharp);
AddFix(title, context, root, classDecl, generator, LanguageNames.CSharp);

// 2) Apply VB DiagnosticAnalyzerAttribute.
title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.VisualBasic);
title = string.Format(CultureInfo.CurrentCulture, CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_1, LanguageNames.VisualBasic);
AddFix(title, context, root, classDecl, generator, LanguageNames.VisualBasic);

// 3) Apply both C# and VB DiagnosticAnalyzerAttributes.
title = string.Format(CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_2, LanguageNames.CSharp, LanguageNames.VisualBasic);
title = string.Format(CultureInfo.CurrentCulture, CodeAnalysisDiagnosticsResources.ApplyDiagnosticAnalyzerAttribute_2, LanguageNames.CSharp, LanguageNames.VisualBasic);
AddFix(title, context, root, classDecl, generator, LanguageNames.CSharp, LanguageNames.VisualBasic);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// 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.Globalization;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis.CSharp.Analyzers.MetaAnalyzers;
using Microsoft.CodeAnalysis.Diagnostics;
Expand Down Expand Up @@ -534,7 +535,7 @@ private static DiagnosticResult GetExpectedDiagnostic(string language, int line,
throw new ArgumentException("Unsupported action kind", nameof(kind));
}

string message = string.Format(CodeAnalysisDiagnosticsResources.StartActionWithNoRegisteredActionsMessage, parameterName, arg2);
string message = string.Format(CultureInfo.CurrentCulture, CodeAnalysisDiagnosticsResources.StartActionWithNoRegisteredActionsMessage, parameterName, arg2);

string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb";
return new DiagnosticResult(DiagnosticIds.StartActionWithNoRegisteredActionsRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// 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.Globalization;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis.CSharp.Analyzers.MetaAnalyzers;
using Microsoft.CodeAnalysis.Diagnostics;
Expand Down Expand Up @@ -375,7 +376,7 @@ private static DiagnosticResult GetExpectedDiagnostic(int line, int column, stri
throw new ArgumentException("Unsupported argument kind", nameof(kind));
}

string message = string.Format(CodeAnalysisDiagnosticsResources.StartActionWithOnlyEndActionMessage, parameterName, endActionName, statelessActionName, arg4);
string message = string.Format(CultureInfo.CurrentCulture, CodeAnalysisDiagnosticsResources.StartActionWithOnlyEndActionMessage, parameterName, endActionName, statelessActionName, arg4);

return new DiagnosticResult(DiagnosticIds.StartActionWithOnlyEndActionRuleId, DiagnosticHelpers.DefaultDiagnosticSeverity)
.WithLocation(line, column)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private static async Task<Document> MakePublic(Document document, SyntaxNode get
{
editor.SetAccessibility(property, Accessibility.Public);

// Having just made the property public, if it has a setter with no Accessibility set, then we've just made the setter public.
// Having just made the property public, if it has a setter with no Accessibility set, then we've just made the setter public.
// Instead restore the setter's original accessibility so that we don't fire a violation with the generated code.
SyntaxNode setter = editor.Generator.GetAccessor(property, DeclarationKind.SetAccessor);
if (setter != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.Helpers;

namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
Expand Down Expand Up @@ -107,7 +108,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext symbolContext, INamedTyp
{
Debug.Assert(missingValues != null);

string missingValuesString = missingValues.Select(v => v.ToString()).Aggregate((i, j) => i + ", " + j);
string missingValuesString = missingValues.Select(v => v.ToString(CultureInfo.InvariantCulture)).Aggregate((i, j) => i + ", " + j);
symbolContext.ReportDiagnostic(symbol.CreateDiagnostic(Rule2217, symbol.Name, missingValuesString));
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
// 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.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;

namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
Expand Down Expand Up @@ -71,7 +72,7 @@ public async override Task RegisterCodeFixesAsync(CodeFixContext context)

if (symbolToChange != null)
{
string title = string.Format(MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix1, symbolToChange.Name);
string title = string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix1, symbolToChange.Name);

context.RegisterCodeFix(new MyCodeAction(title,
async ct => await MakeProtected(context.Document, symbolToChange, checkSetter, ct).ConfigureAwait(false),
Expand All @@ -84,7 +85,7 @@ public async override Task RegisterCodeFixesAsync(CodeFixContext context)
ISymbol symbolToChange = methodSymbol.IsAccessorMethod() ? methodSymbol.AssociatedSymbol : methodSymbol;
if (symbolToChange != null)
{
string title = string.Format(MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix2, symbolToChange.Name);
string title = string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix2, symbolToChange.Name);

context.RegisterCodeFix(new MyCodeAction(title,
async ct => await ChangeToPublicInterfaceImplementation(context.Document, symbolToChange, ct).ConfigureAwait(false),
Expand All @@ -93,7 +94,7 @@ public async override Task RegisterCodeFixesAsync(CodeFixContext context)
}
}

context.RegisterCodeFix(new MyCodeAction(string.Format(MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix3, methodSymbol.ContainingType.Name),
context.RegisterCodeFix(new MyCodeAction(string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix3, methodSymbol.ContainingType.Name),
async ct => await MakeContainingTypeSealed(context.Document, methodSymbol, ct).ConfigureAwait(false),
equivalenceKey: MicrosoftCodeQualityAnalyzersResources.InterfaceMethodsShouldBeCallableByChildTypesFix3),
context.Diagnostics);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System.Collections.Immutable;
using System.Composition;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
Expand Down Expand Up @@ -45,7 +46,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
string newName = diagnostic.Properties[ParameterNamesShouldMatchBaseDeclarationAnalyzer.NewNamePropertyName];
context.RegisterCodeFix(
CodeAction.Create(
string.Format(MicrosoftCodeQualityAnalyzersResources.RenameToTitle, newName),
string.Format(CultureInfo.CurrentCulture, MicrosoftCodeQualityAnalyzersResources.RenameToTitle, newName),
cancellationToken => GetUpdatedDocumentForParameterRenameAsync(context.Document, declaredSymbol, newName, cancellationToken),
nameof(ParameterNamesShouldMatchBaseDeclarationFixer) + newName),
diagnostic);
Expand Down
Loading

0 comments on commit e70727e

Please sign in to comment.