Skip to content

Commit

Permalink
fix: fix spacing for casts and enum parse mappings (#747)
Browse files Browse the repository at this point in the history
Remove NoramlizeWhitespace in unit tests to ensure correct formatting in unit tests
  • Loading branch information
latonz authored Sep 13, 2023
1 parent 4fa4163 commit 137f2fb
Show file tree
Hide file tree
Showing 20 changed files with 207 additions and 294 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Riok.Mapperly.Emit.Syntax;
using Riok.Mapperly.Helpers;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Riok.Mapperly.Emit.Syntax.SyntaxFactoryHelper;
Expand Down Expand Up @@ -55,7 +56,7 @@ private SwitchExpressionArmSyntax BuildArmIgnoreCase(string ignoreCaseSwitchDesi
{
// { } s
var pattern = RecursivePattern()
.WithPropertyPatternClause(PropertyPatternClause())
.WithPropertyPatternClause(PropertyPatternClause().AddTrailingSpace())
.WithDesignation(SingleVariableDesignation(Identifier(ignoreCaseSwitchDesignatedVariableName)));

// source.Value1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public override IEnumerable<StatementSyntax> Build(TypeMappingBuildContext ctx,
var castedVariable = ctx.NameBuilder.New(ExplicitCastVariableName);
target = IdentifierName(castedVariable);

yield return LocalDeclarationStatement(DeclareVariable(castedVariable, cast));
yield return ctx.SyntaxFactory.DeclareLocalVariable(castedVariable, cast);
}

if (_ensureCapacity != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public IfStatementSyntax If(
ElseClauseSyntax? elseClause = null;
if (elseStatements != null)
{
elseClause = ElseClause(Block(elseStatements)).AddLeadingLineFeed(Indentation).AddTrailingLineFeed(Indentation);
elseClause = ElseClause(Block(elseStatements)).AddLeadingLineFeed(Indentation);
}

return IfStatement(
Expand Down
2 changes: 1 addition & 1 deletion src/Riok.Mapperly/Emit/Syntax/SyntaxFactoryHelper.Null.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public StatementSyntax IfNullReturnOrThrow(ExpressionSyntax expression, Expressi
{
StatementSyntax ifExpression = returnOrThrowExpression switch
{
ThrowExpressionSyntax throwSyntax => ThrowStatement(throwSyntax.Expression),
ThrowExpressionSyntax throwSyntax => AddIndentation().ThrowStatement(throwSyntax.Expression),
_ => AddIndentation().Return(returnOrThrowExpression),
};

Expand Down
29 changes: 14 additions & 15 deletions test/Riok.Mapperly.Tests/GeneratedMethod.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Riok.Mapperly.Tests;

public class GeneratedMethod
{
private const string MethodIndentation = " ";

public GeneratedMethod(MethodDeclarationSyntax declarationSyntax)
{
Name = declarationSyntax.Identifier.ToString();
Expand All @@ -27,17 +24,19 @@ public GeneratedMethod(MethodDeclarationSyntax declarationSyntax)
/// <returns>The cleaned body.</returns>
private static string ExtractBody(MethodDeclarationSyntax declarationSyntax)
{
var body =
declarationSyntax.Body
?.NormalizeWhitespace()
.ToFullString()
.Trim(' ', '\r', '\n')
.Trim('{', '}')
.Trim(' ', '\r', '\n')
.ReplaceLineEndings() ?? string.Empty;
var lines = body.Split(Environment.NewLine);
return lines.Length == 0
? string.Empty
: string.Join(Environment.NewLine, lines.Select(l => l.StartsWith(MethodIndentation) ? l[MethodIndentation.Length..] : l));
if (declarationSyntax.Body == null)
return string.Empty;

var body = declarationSyntax.Body
.ToFullString()
.Trim(' ', '\r', '\n')
.TrimStart('{')
.TrimEnd('}')
.Trim('\r', '\n')
.ReplaceLineEndings();
var lines = body.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
var indentionCount = lines[0].TakeWhile(x => x == ' ').Count();
var indention = lines[0][..indentionCount];
return string.Join(Environment.NewLine, lines.Select(l => l.StartsWith(indention) ? l[indentionCount..] : l)).Trim(' ', '\r', '\n');
}
}
16 changes: 0 additions & 16 deletions test/Riok.Mapperly.Tests/Mapping/DictionaryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ public void DictionaryToSameDictionaryDeepCloning()
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand All @@ -51,7 +50,6 @@ public void DictionaryToDictionaryExplicitCastedValue()
{
target[item.Key] = (int)item.Value;
}

return target;
"""
);
Expand All @@ -71,7 +69,6 @@ public void DictionaryToDictionaryNullableToNonNullable()
{
target[item.Key] = item.Value == null ? throw new System.ArgumentNullException(nameof(item.Value)) : item.Value.Value;
}

return target;
"""
);
Expand All @@ -98,7 +95,6 @@ TestSourceBuilderOptions.Default with
{
target[item.Key] = item.Value == null ? default : item.Value.Value;
}

return target;
"""
);
Expand All @@ -118,7 +114,6 @@ public void DictionaryToIDictionaryExplicitCastedValue()
{
target[item.Key] = (int)item.Value;
}

return target;
"""
);
Expand All @@ -138,7 +133,6 @@ public void KeyValueEnumerableToIDictionary()
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand All @@ -158,7 +152,6 @@ public void CustomDictionaryToIDictionary()
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand All @@ -178,7 +171,6 @@ public void CustomKeyValueListToIDictionary()
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand All @@ -199,7 +191,6 @@ public void DictionaryToCustomDictionary()
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand All @@ -223,7 +214,6 @@ public void DictionaryToCustomDictionaryWithObjectFactory()
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand Down Expand Up @@ -285,7 +275,6 @@ public void KeyValueEnumerableToExistingDictionary()
{
target.EnsureCapacity(sourceCount + target.Count);
}

foreach (var item in source)
{
target[item.Key] = item.Value;
Expand Down Expand Up @@ -323,7 +312,6 @@ string IDictionary<string, string>.this[string key]
{
targetDict[item.Key] = item.Value;
}

return target;
"""
);
Expand Down Expand Up @@ -357,7 +345,6 @@ public string this[string key]
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand Down Expand Up @@ -394,7 +381,6 @@ string IDictionary<string, string>.this[string key]
{
targetDict[item.Key] = item.Value;
}

return target;
"""
);
Expand Down Expand Up @@ -428,7 +414,6 @@ string IDictionary<string, string>.this[string key]
{
targetDict[item.Key] = item.Value;
}

return target;
"""
);
Expand Down Expand Up @@ -461,7 +446,6 @@ public string this[string key]
{
target[item.Key] = item.Value;
}

return target;
"""
);
Expand Down
6 changes: 3 additions & 3 deletions test/Riok.Mapperly.Tests/Mapping/EnumFallbackValueTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ public void StringToEnumFallbackValueShouldSwitchIgnoreCase()
"""
return source switch
{
{ } s when s.Equals(nameof(global::E1.A), System.StringComparison.OrdinalIgnoreCase) => global::E1.A,
{ } s when s.Equals(nameof(global::E1.B), System.StringComparison.OrdinalIgnoreCase) => global::E1.B,
{ } s when s.Equals(nameof(global::E1.C), System.StringComparison.OrdinalIgnoreCase) => global::E1.C,
{} s when s.Equals(nameof(global::E1.A), System.StringComparison.OrdinalIgnoreCase) => global::E1.A,
{} s when s.Equals(nameof(global::E1.B), System.StringComparison.OrdinalIgnoreCase) => global::E1.B,
{} s when s.Equals(nameof(global::E1.C), System.StringComparison.OrdinalIgnoreCase) => global::E1.C,
_ => global::E1.Unknown,
};
"""
Expand Down
10 changes: 5 additions & 5 deletions test/Riok.Mapperly.Tests/Mapping/EnumTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,14 @@ public void NullableEnumToOtherNullableEnumShouldCast()
TestHelper
.GenerateMapper(source)
.Should()
.HaveSingleMethodBody("return source == null ? default(global::E2? ) : (global::E2)source.Value;");
.HaveSingleMethodBody("return source == null ? default(global::E2?) : (global::E2)source.Value;");
}

[Fact]
public void EnumToOtherNullableEnumShouldCast()
{
var source = TestSourceBuilder.Mapping("E1", "E2?", "enum E1 {A, B, C}", "enum E2 {A, B, C}");
TestHelper.GenerateMapper(source).Should().HaveSingleMethodBody("return (global::E2? )(global::E2)source;");
TestHelper.GenerateMapper(source).Should().HaveSingleMethodBody("return (global::E2?)(global::E2)source;");
}

[Fact]
Expand Down Expand Up @@ -260,9 +260,9 @@ public void StringToEnumShouldSwitchIgnoreCase()
"""
return source switch
{
{ } s when s.Equals(nameof(global::E1.A), System.StringComparison.OrdinalIgnoreCase) => global::E1.A,
{ } s when s.Equals(nameof(global::E1.B), System.StringComparison.OrdinalIgnoreCase) => global::E1.B,
{ } s when s.Equals(nameof(global::E1.C), System.StringComparison.OrdinalIgnoreCase) => global::E1.C,
{} s when s.Equals(nameof(global::E1.A), System.StringComparison.OrdinalIgnoreCase) => global::E1.A,
{} s when s.Equals(nameof(global::E1.B), System.StringComparison.OrdinalIgnoreCase) => global::E1.B,
{} s when s.Equals(nameof(global::E1.C), System.StringComparison.OrdinalIgnoreCase) => global::E1.C,
_ => System.Enum.Parse<global::E1>(source, true),
};
"""
Expand Down
13 changes: 3 additions & 10 deletions test/Riok.Mapperly.Tests/Mapping/EnumerableDeepCloningTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public void ArrayOfNullablePrimitiveTypesToNonNullableArrayDeepCloning()
{
target[i] = source[i] == null ? throw new System.NullReferenceException($"Sequence {nameof(source)}, contained a null value at index {i}.") : source[i].Value;
}

return target;
"""
);
Expand All @@ -58,12 +57,11 @@ public void ArrayOfPrimitiveTypesToNullablePrimitiveTypesArrayDeepCloning()
.Should()
.HaveSingleMethodBody(
"""
var target = new int? [source.Length];
var target = new int?[source.Length];
for (var i = 0; i < source.Length; i++)
{
target[i] = (int? )source[i];
target[i] = (int?)source[i];
}

return target;
"""
);
Expand All @@ -88,7 +86,6 @@ public void ArrayCustomClassToArrayCustomClassDeepCloning()
{
target[i] = MapToB(source[i]);
}

return target;
"""
);
Expand All @@ -105,7 +102,7 @@ public void ArrayToArrayOfStringDeepCloning()
public void ArrayToArrayOfNullableStringDeepCloning()
{
var source = TestSourceBuilder.Mapping("string[]", "string?[]", TestSourceBuilderOptions.WithDeepCloning);
TestHelper.GenerateMapper(source).Should().HaveSingleMethodBody("return (string? [])source.Clone();");
TestHelper.GenerateMapper(source).Should().HaveSingleMethodBody("return (string?[])source.Clone();");
}

[Fact]
Expand Down Expand Up @@ -134,7 +131,6 @@ public void ArrayToArrayOfMutableStructDeepCloning()
{
target[i] = MapToA(source[i]);
}

return target;
"""
);
Expand Down Expand Up @@ -168,7 +164,6 @@ public void CollectionToArrayOfMutableStructDeepCloning()
target[i] = MapToA(item);
i++;
}

return target;
"""
);
Expand Down Expand Up @@ -199,7 +194,6 @@ public void ArrayToArrayOfMutableStructDeepCloningLoopNameTaken()
{
target[i1] = MapToA(i[i1]);
}

return target;
"""
);
Expand All @@ -223,7 +217,6 @@ public void ArrayToArrayOfMutableStructDeepCloningTargetNameTaken()
{
target1[i] = MapToA(target[i]);
}

return target1;
"""
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public void EnumerableToExistingCustomCollection()
{
target.EnsureCapacity(sourceCount + target.Count);
}

foreach (var item in source)
{
target.Add(item);
Expand Down
3 changes: 0 additions & 3 deletions test/Riok.Mapperly.Tests/Mapping/EnumerableSetTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ public void ExistingEnumerableToExistingSet()
{
target.Values.Add(item);
}

return target;
"""
);
Expand All @@ -102,12 +101,10 @@ public void ExistingEnumerableToExistingHashSet()
{
target.Values.EnsureCapacity(sourceCount + target.Values.Count);
}

foreach (var item in source.Values)
{
target.Values.Add(item);
}

return target;
"""
);
Expand Down
Loading

0 comments on commit 137f2fb

Please sign in to comment.