Skip to content

Commit

Permalink
C#: Do not insert a synthetic ToString call in interpolation expressi…
Browse files Browse the repository at this point in the history
…ons, if the type implements IFormattable.
  • Loading branch information
michaelnebel committed Jan 14, 2025
1 parent ab70a94 commit 6a406b2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,12 @@ attribute.AttributeClass is INamedTypeSymbol nt &&
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>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Semmle.Extraction.Kinds;
Expand All @@ -20,7 +21,15 @@ protected override void PopulateExpression(TextWriter trapFile)
{
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
Expand Down

0 comments on commit 6a406b2

Please sign in to comment.