Browse Source

Fix #1865: At least one of the first two operands in string concatenation needs to be of type `string`, so we can't always drop `ToString()` calls.

pull/1880/head
Daniel Grunwald 5 years ago
parent
commit
b9675f58b3
  1. 8
      ICSharpCode.Decompiler.Tests/TestCases/Correctness/StringConcat.cs
  2. 11
      ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs

8
ICSharpCode.Decompiler.Tests/TestCases/Correctness/StringConcat.cs

@ -107,11 +107,19 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness @@ -107,11 +107,19 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
Console.WriteLine(s);
}
static void TestCharPlusChar(string a)
{
Console.WriteLine("TestCharPlusChar:");
Console.WriteLine(a[0] + a[1]);
Console.WriteLine(a[0].ToString() + a[1].ToString());
}
static void Main()
{
TestClass();
TestStruct();
TestStructMutation();
TestCharPlusChar("ab");
}
}
}

11
ICSharpCode.Decompiler/CSharp/Transforms/ReplaceMethodCallsWithOperators.cs

@ -61,11 +61,16 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms @@ -61,11 +61,16 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
if (IsStringConcat(method) && CheckArgumentsForStringConcat(arguments)) {
bool isInExpressionTree = invocationExpression.Ancestors.OfType<LambdaExpression>().Any(
lambda => lambda.Annotation<IL.ILFunction>()?.Kind == IL.ILFunctionKind.ExpressionTree);
Expression expr = arguments[0].Detach();
Expression arg0 = arguments[0].Detach();
Expression arg1 = arguments[1].Detach();
if (!isInExpressionTree) {
expr = RemoveRedundantToStringInConcat(expr, method, isLastArgument: false).Detach();
arg1 = RemoveRedundantToStringInConcat(arg1, method, isLastArgument: arguments.Length == 2).Detach();
if (arg1.GetResolveResult().Type.IsKnownType(KnownTypeCode.String)) {
arg0 = RemoveRedundantToStringInConcat(arg0, method, isLastArgument: false).Detach();
}
}
for (int i = 1; i < arguments.Length; i++) {
var expr = new BinaryOperatorExpression(arg0, BinaryOperatorType.Add, arg1);
for (int i = 2; i < arguments.Length; i++) {
var arg = arguments[i].Detach();
if (!isInExpressionTree) {
arg = RemoveRedundantToStringInConcat(arg, method, isLastArgument: i == arguments.Length - 1).Detach();

Loading…
Cancel
Save