|
| 1 | +using System.Linq; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 4 | +using Semmle.Extraction.CSharp.Util; |
| 5 | +using Semmle.Extraction.Kinds; |
| 6 | + |
| 7 | + |
| 8 | +namespace Semmle.Extraction.CSharp.Entities.Expressions |
| 9 | +{ |
| 10 | + internal sealed class ImplicitToString : Expression |
| 11 | + { |
| 12 | + /// <summary> |
| 13 | + /// Gets the `ToString` method for the given type. |
| 14 | + /// </summary> |
| 15 | + private static IMethodSymbol? GetToStringMethod(ITypeSymbol? type) |
| 16 | + { |
| 17 | + return type? |
| 18 | + .GetMembers() |
| 19 | + .OfType<IMethodSymbol>() |
| 20 | + .Where(method => |
| 21 | + method.GetName() == "ToString" && |
| 22 | + method.Parameters.Length == 0 |
| 23 | + ) |
| 24 | + .FirstOrDefault(); |
| 25 | + } |
| 26 | + |
| 27 | + private ImplicitToString(ExpressionNodeInfo info, IMethodSymbol toString) : base(new ExpressionInfo(info.Context, AnnotatedTypeSymbol.CreateNotAnnotated(toString.ReturnType), info.Location, ExprKind.METHOD_INVOCATION, info.Parent, info.Child, isCompilerGenerated: true, info.ExprValue)) |
| 28 | + { |
| 29 | + Factory.Create(info.SetParent(this, -1)); |
| 30 | + |
| 31 | + var target = Method.Create(Context, toString); |
| 32 | + Context.TrapWriter.Writer.expr_call(this, target); |
| 33 | + } |
| 34 | + |
| 35 | + private static bool IsStringType(AnnotatedTypeSymbol? type) => |
| 36 | + type.HasValue && type.Value.Symbol?.SpecialType == SpecialType.System_String; |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Creates a new expression, adding a compiler generated `ToString` call if required. |
| 40 | + /// </summary> |
| 41 | + public static Expression Create(Context cx, ExpressionSyntax node, Expression parent, int child) |
| 42 | + { |
| 43 | + var info = new ExpressionNodeInfo(cx, node, parent, child); |
| 44 | + return CreateFromNode(info.SetImplicitToString(IsStringType(parent.Type) && !IsStringType(info.Type))); |
| 45 | + } |
| 46 | + |
| 47 | + /// <summary> |
| 48 | + /// Wraps the resulting expression in a `ToString` call, if a suitable `ToString` method is available. |
| 49 | + /// </summary> |
| 50 | + public static Expression Wrap(ExpressionNodeInfo info) |
| 51 | + { |
| 52 | + if (GetToStringMethod(info.Type?.Symbol) is IMethodSymbol toString) |
| 53 | + { |
| 54 | + return new ImplicitToString(info, toString); |
| 55 | + } |
| 56 | + return Factory.Create(info); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments