Skip to content
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

New Rule T0004: Use Regex.SafeIsMatch #9144

Merged
merged 3 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2024 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

namespace SonarAnalyzer.Rules.CSharp.Styling;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class UseRegexSafeIsMatch : StylingAnalyzer
{
public UseRegexSafeIsMatch() : base("T0004", "Use '{0}{1}' instead.") { }

protected override void Initialize(SonarAnalysisContext context) =>
context.RegisterNodeAction(c =>
{
var memberAccess = (MemberAccessExpressionSyntax)c.Node;
if (memberAccess.NameIs("IsMatch", "Match", "Matches")
&& c.SemanticModel.GetSymbolInfo(memberAccess).Symbol is IMethodSymbol method
&& method.ContainingType.Is(KnownType.System_Text_RegularExpressions_Regex))
{
c.ReportIssue(Rule, method.IsStatic ? memberAccess : memberAccess.Name, method.IsStatic ? "SafeRegex." : "Safe", method.Name);
}
},
SyntaxKind.SimpleMemberAccessExpression);
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

namespace SonarAnalyzer.Helpers;

internal static class CSharpSyntaxHelper
public static class CSharpSyntaxHelper
{
public static readonly ExpressionSyntax NullLiteralExpression =
SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression);
Expand Down Expand Up @@ -221,7 +221,7 @@ public static bool IsStringEmpty(this ExpressionSyntax expression, SemanticModel
public static bool NameIs(this SyntaxNode node, string name, params string[] orNames) =>
node.GetName() is { } nodeName
&& (nodeName.Equals(name, StringComparison.Ordinal)
|| orNames.Any(x => nodeName.Equals(x, StringComparison.Ordinal)));
|| Array.Exists(orNames, x => nodeName.Equals(x, StringComparison.Ordinal)));

public static bool HasConstantValue(this ExpressionSyntax expression, SemanticModel semanticModel) =>
expression.RemoveParentheses().IsAnyKind(LiteralSyntaxKinds) || expression.FindConstantValue(semanticModel) != null;
Expand Down
2 changes: 1 addition & 1 deletion analyzers/src/SonarAnalyzer.Common/Helpers/TypeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

namespace SonarAnalyzer.Helpers;

internal static class TypeHelper
public static class TypeHelper
{
#region TypeKind

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2024 SonarSource SA
* mailto: contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

using SonarAnalyzer.TestFramework.MetadataReferences;

namespace SonarAnalyzer.CSharp.Styling.Test.Rules;

[TestClass]
public class UseRegexSafeIsMatchTest
{
[TestMethod]
public void UseRegexSafeIsMatch() =>
StylingVerifierBuilder.Create<UseRegexSafeIsMatch>().AddPaths("UseRegexSafeIsMatch.cs").AddReferences(MetadataReferenceFacade.RegularExpressions).Verify();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System.Text.RegularExpressions;
using RealRegex = System.Text.RegularExpressions.Regex;

class UseRegexSafeIsMatchNonCompliant
{
private Regex regex;
private RealRegex realRegex;

void InstanceRegex(string content)
{
regex.IsMatch(content); // Noncompliant {{Use 'SafeIsMatch' instead.}}
// ^^^^^^^
regex.IsMatch(content, 0); // Noncompliant
regex.Matches(content); // Noncompliant {{Use 'SafeMatches' instead.}}
regex.Matches(content, 0); // Noncompliant
regex.Match(content); // Noncompliant {{Use 'SafeMatch' instead.}}
regex.Match(content, 0); // Noncompliant
realRegex.IsMatch(content); // Noncompliant
realRegex.IsMatch(content, 0); // Noncompliant
realRegex.Matches(content); // Noncompliant
realRegex.Matches(content, 0); // Noncompliant
realRegex.Match(content); // Noncompliant
realRegex.Match(content, 0); // Noncompliant
pavel-mikula-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
Regex.IsMatch(content, "pattern"); // Noncompliant {{Use 'SafeRegex.IsMatch' instead.}}
// ^^^^^^^^^^^^^
pavel-mikula-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
Regex.IsMatch(content, "pattern", RegexOptions.None); // Noncompliant
Regex.Matches(content, "pattern"); // Noncompliant {{Use 'SafeRegex.Matches' instead.}}
Regex.Matches(content, "pattern", RegexOptions.None); // Noncompliant
Regex.Match(content, "pattern"); // Noncompliant {{Use 'SafeRegex.Match' instead.}}
Regex.Match(content, "pattern", RegexOptions.None); // Noncompliant
RealRegex.IsMatch(content, "pattern"); // Noncompliant
RealRegex.IsMatch(content, "pattern", RegexOptions.None); // Noncompliant
RealRegex.Matches(content, "pattern"); // Noncompliant
RealRegex.Matches(content, "pattern", RegexOptions.None); // Noncompliant
RealRegex.Match(content, "pattern"); // Noncompliant
RealRegex.Match(content, "pattern", RegexOptions.None); // Noncompliant
}
}

class UseRegexSafeIsMatchCompliant
{
private class Regex
{
public bool IsMatch(string input) => false;
public MatchCollection Matches(string input) => null;
public Match Match(string input) => null;
public static bool IsMatch(string input, string pattern) => false;
public static MatchCollection Matches(string input, string pattern) => null;
public static Match Match(string input, string pattern) => null;
}

private Regex regex;

void InstanceRegex(string content)
{
regex.IsMatch(content);
regex.Matches(content);
regex.Match(content);
Regex.IsMatch(content, "pattern");
Regex.Matches(content, "pattern");
Regex.Match(content, "pattern");
}
}