/
UserDefinedNewInstanceMethodMapping.cs
64 lines (54 loc) · 2.71 KB
/
UserDefinedNewInstanceMethodMapping.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Riok.Mapperly.Abstractions.ReferenceHandling;
using Riok.Mapperly.Symbols;
namespace Riok.Mapperly.Descriptors.Mappings.UserMappings;
/// <summary>
/// Represents a mapping method declared but not implemented by the user which results in a new target object instance.
/// </summary>
public class UserDefinedNewInstanceMethodMapping(
IMethodSymbol method,
MethodParameter sourceParameter,
MethodParameter? referenceHandlerParameter,
ITypeSymbol targetType,
bool enableReferenceHandling
) : MethodMapping(method, sourceParameter, referenceHandlerParameter, targetType), IDelegateUserMapping
{
public IMethodSymbol Method { get; } = method;
public INewInstanceMapping? DelegateMapping { get; private set; }
public void SetDelegateMapping(INewInstanceMapping mapping) => DelegateMapping = mapping;
public override IEnumerable<StatementSyntax> BuildBody(TypeMappingBuildContext ctx)
{
if (DelegateMapping == null)
{
return new[] { ctx.SyntaxFactory.ExpressionStatement(ctx.SyntaxFactory.ThrowMappingNotImplementedExceptionStatement()), };
}
// if reference handling is enabled and no reference handler parameter is declared
// the generated mapping method is called with a new reference handler instance
// otherwise the generated method is embedded
if (enableReferenceHandling && ReferenceHandlerParameter == null)
{
// new RefHandler();
var createRefHandler = ctx.SyntaxFactory.CreateInstance<PreserveReferenceHandler>();
ctx = ctx.WithRefHandler(createRefHandler);
return new[] { ctx.SyntaxFactory.Return(DelegateMapping.Build(ctx)) };
}
if (DelegateMapping is MethodMapping delegateMethodMapping)
return delegateMethodMapping.BuildBody(ctx);
return new[] { ctx.SyntaxFactory.Return(DelegateMapping.Build(ctx)) };
}
/// <summary>
/// A <see cref="UserDefinedNewInstanceMethodMapping"/> is callable by other mappings
/// if either reference handling is not activated, or the user defined a reference handler parameter.
/// </summary>
public override bool CallableByOtherMappings => !enableReferenceHandling || ReferenceHandlerParameter != null;
internal override void EnableReferenceHandling(INamedTypeSymbol iReferenceHandlerType)
{
// the parameters of user defined methods should not be manipulated
// if the user did not define a parameter a new reference handler is initialized
if (DelegateMapping is MethodMapping methodMapping)
{
methodMapping.EnableReferenceHandling(iReferenceHandlerType);
}
}
}