C#: Do not insert a synthetic ToString call in interpolation expressions, if the type implements IFormattable.

This commit is contained in:
Michael Nebel
2025-01-14 15:57:21 +01:00
parent ab70a945e4
commit 6a406b28d1
2 changed files with 16 additions and 1 deletions

View File

@@ -532,6 +532,12 @@ namespace Semmle.Extraction.CSharp
return isInline;
}
/// <summary>
/// Returns true if this type implements `System.IFormattable`.
/// </summary>
public static bool ImplementsIFormattable(this ITypeSymbol type) =>
type.AllInterfaces.Any(i => i.Name == "IFormattable" && i.ContainingNamespace.ToString() == "System");
/// <summary>
/// Holds if this type is of the form <code>System.ReadOnlySpan&lt;byte&gt;</code>.
/// </summary>

View File

@@ -1,4 +1,5 @@
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Semmle.Extraction.Kinds;
@@ -20,7 +21,15 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
{
case SyntaxKind.Interpolation:
var interpolation = (InterpolationSyntax)c;
ImplicitToString.Create(Context, interpolation.Expression, this, child++);
var exp = interpolation.Expression;
if (Context.GetTypeInfo(exp).Type is ITypeSymbol type && !type.ImplementsIFormattable())
{
ImplicitToString.Create(Context, exp, this, child++);
}
else
{
Create(Context, exp, this, child++);
}
break;
case SyntaxKind.InterpolatedStringText:
// Create a string literal