-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelegateBodySyntaxExtractor.cs
More file actions
157 lines (135 loc) · 4.67 KB
/
DelegateBodySyntaxExtractor.cs
File metadata and controls
157 lines (135 loc) · 4.67 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
using System;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace EasySourceGenerators.Generators.IncrementalGenerators;
/// <summary>
/// Extracts the delegate body source code from a <c>UseProvidedBody(...)</c> invocation
/// within a generator method's syntax tree. The extracted body is re-indented to match
/// the target method body indentation (8 spaces).
/// </summary>
internal static class DelegateBodySyntaxExtractor
{
private const string MethodBodyIndent = " ";
/// <summary>
/// Attempts to find a <c>UseProvidedBody(...)</c> call in the given generator method syntax
/// and extract the lambda body. Returns <c>null</c> if no such call is found.
/// For expression lambdas, returns a single <c>return {expr};</c> line.
/// For block lambdas, returns the block body re-indented to the method body level.
/// </summary>
internal static string? TryExtractDelegateBody(MethodDeclarationSyntax generatorMethodSyntax)
{
InvocationExpressionSyntax? invocation = generatorMethodSyntax
.DescendantNodes()
.OfType<InvocationExpressionSyntax>()
.FirstOrDefault(inv =>
inv.Expression is MemberAccessExpressionSyntax memberAccess &&
memberAccess.Name.Identifier.Text == "UseProvidedBody");
if (invocation == null)
{
return null;
}
ArgumentSyntax? argument = invocation.ArgumentList.Arguments.FirstOrDefault();
if (argument?.Expression is not LambdaExpressionSyntax lambda)
{
return null;
}
if (lambda.Body is ExpressionSyntax expression)
{
string expressionText = expression.ToFullString().Trim();
return expressionText;
}
if (lambda.Body is BlockSyntax block)
{
return ExtractBlockBody(block);
}
return null;
}
/// <summary>
/// Extracts the content of a block body (between <c>{</c> and <c>}</c>),
/// determines the base indentation, and re-indents all lines to the method body level.
/// Blank lines between statements are preserved with method body indentation.
/// </summary>
private static string? ExtractBlockBody(BlockSyntax block)
{
string blockText = block.ToFullString();
string[] lines = blockText.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
int openIndex = -1;
int closeIndex = -1;
for (int i = 0; i < lines.Length; i++)
{
if (openIndex == -1 && lines[i].TrimEnd().EndsWith("{", StringComparison.Ordinal))
{
openIndex = i;
break;
}
}
for (int i = lines.Length - 1; i >= 0; i--)
{
string trimmed = lines[i].Trim();
if (trimmed.StartsWith("}", StringComparison.Ordinal))
{
closeIndex = i;
break;
}
}
if (openIndex == -1 || closeIndex == -1 || closeIndex <= openIndex)
{
return null;
}
string[] contentLines = new string[closeIndex - openIndex - 1];
Array.Copy(lines, openIndex + 1, contentLines, 0, contentLines.Length);
if (contentLines.Length == 0)
{
return null;
}
int minIndent = int.MaxValue;
foreach (string line in contentLines)
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
int indent = 0;
foreach (char c in line)
{
if (c == ' ')
{
indent++;
}
else if (c == '\t')
{
indent += 4;
}
else
{
break;
}
}
if (indent < minIndent)
{
minIndent = indent;
}
}
if (minIndent == int.MaxValue)
{
minIndent = 0;
}
StringBuilder result = new();
for (int i = 0; i < contentLines.Length; i++)
{
string line = contentLines[i];
if (string.IsNullOrWhiteSpace(line))
{
result.AppendLine(MethodBodyIndent);
}
else
{
string stripped = minIndent <= line.Length ? line.Substring(minIndent) : line.TrimStart();
string trimmedEnd = stripped.TrimEnd();
result.AppendLine(MethodBodyIndent + trimmedEnd);
}
}
return result.ToString().TrimEnd('\n', '\r');
}
}