-
Notifications
You must be signed in to change notification settings - Fork 3
/
Program.cs
231 lines (194 loc) · 10.1 KB
/
Program.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
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
namespace Ryder.Lightweight
{
/// <summary>
/// Program used to create the 'Ryder.Lightweight.cs' file.
/// </summary>
internal static class Program
{
private const string OUTPUT_FILENAME = "Ryder.Lightweight.cs";
/// <summary>
/// Entry point of the program: generates the 'Ryder.Lightweight.cs' file.
/// </summary>
public static int Main(string[] args)
{
string ns = null;
string dir = Directory.GetCurrentDirectory();
string output = Path.Combine(Directory.GetCurrentDirectory(), OUTPUT_FILENAME);
bool makePublic = false;
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--public":
case "-p":
makePublic = true;
break;
case "--namespace":
case "-n":
if (args.Length == i + 1)
{
Console.Error.WriteLine("No namespace given.");
return 1;
}
ns = args[++i];
break;
case "--directory":
case "-d":
if (args.Length == i + 1)
{
Console.Error.WriteLine("No directory given.");
return 1;
}
dir = args[++i];
break;
case "--output":
case "-o":
if (args.Length == i + 1)
{
Console.Error.WriteLine("No directory given.");
return 1;
}
output = args[++i];
break;
default:
Console.Error.WriteLine($"Unknown argument: '{args[i]}'.");
return 1;
}
}
string methodRedirectionPath = Path.Combine(dir, "Redirection.Method.cs");
string helpersPath = Path.Combine(dir, "Helpers.cs");
if (!File.Exists(methodRedirectionPath) || !File.Exists(helpersPath))
{
Console.Error.WriteLine("Invalid directory given.");
return 1;
}
try
{
// Read files
string methodRedirectionContent = File.ReadAllText(methodRedirectionPath);
string helpersContent = File.ReadAllText(helpersPath);
// Parse content to trees, and get their root / classes / usings
SyntaxTree methodRedirectionTree = SyntaxFactory.ParseSyntaxTree(methodRedirectionContent, path: methodRedirectionPath);
SyntaxTree helpersTree = SyntaxFactory.ParseSyntaxTree(helpersContent, path: helpersPath);
CompilationUnitSyntax methodRedirection = methodRedirectionTree.GetCompilationUnitRoot();
CompilationUnitSyntax helpers = helpersTree.GetCompilationUnitRoot();
UsingDirectiveSyntax[] usings = methodRedirection.Usings.Select(x => x.Name.ToString())
.Concat(helpers.Usings.Select(x => x.Name.ToString()))
.Distinct()
.OrderBy(x => x)
.Select(x => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(x)))
.ToArray();
ClassDeclarationSyntax methodRedirectionClass = methodRedirection.DescendantNodes()
.OfType<ClassDeclarationSyntax>()
.First();
ClassDeclarationSyntax helpersClass = helpers.DescendantNodes()
.OfType<ClassDeclarationSyntax>()
.First();
// Set visibility of main class
if (!makePublic)
{
var modifiers = methodRedirectionClass.Modifiers;
var publicModifier = modifiers.First(x => x.Kind() == SyntaxKind.PublicKeyword);
methodRedirectionClass = methodRedirectionClass.WithModifiers(
modifiers.Replace(publicModifier, SyntaxFactory.Token(SyntaxKind.InternalKeyword))
);
}
// Set visibility of helpers class
helpersClass = helpersClass.WithModifiers(
helpersClass.Modifiers.Replace(
helpersClass.Modifiers.First(x => x.Kind() == SyntaxKind.InternalKeyword),
SyntaxFactory.Token(SyntaxKind.PrivateKeyword)
)
);
// Change helpers class extension methods to normal methods
var extMethods = helpersClass.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.Where(x => x.ParameterList.DescendantTokens().Any(tok => tok.Kind() == SyntaxKind.ThisKeyword));
var extMethodsNames = extMethods.Select(x => x.Identifier.Text);
helpersClass = helpersClass.ReplaceNodes(
helpersClass.DescendantNodes().OfType<ParameterSyntax>().Where(x => x.Modifiers.Any(SyntaxKind.ThisKeyword)),
(x,_) => x.WithModifiers(x.Modifiers.Remove(x.Modifiers.First(y => y.Kind() == SyntaxKind.ThisKeyword)))
);
// Disable overrides
var members = methodRedirectionClass.Members;
for (int i = 0; i < members.Count; i++)
{
var member = members[i];
if (!(member is MethodDeclarationSyntax method))
{
if (member is ConstructorDeclarationSyntax ctor)
members = members.Replace(ctor, ctor.WithIdentifier(SyntaxFactory.Identifier("Redirection")));
continue;
}
var overrideModifier = method.Modifiers.FirstOrDefault(x => x.Kind() == SyntaxKind.OverrideKeyword);
if (overrideModifier == default(SyntaxToken))
continue;
method = method.WithModifiers(
method.Modifiers.Remove(overrideModifier)
);
members = members.Replace(member, method);
}
// Add missing field
var field = SyntaxFactory.FieldDeclaration(
SyntaxFactory.VariableDeclaration(
SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
SyntaxFactory.SeparatedList(new[] {
SyntaxFactory.VariableDeclarator("isRedirecting")
})
)
);
const string DOCS = @"
/// <summary>
/// Provides the ability to redirect calls from one method to another.
/// </summary>
";
var disposableType = SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(nameof(IDisposable)));
methodRedirectionClass = methodRedirectionClass.WithMembers(members)
// Add docs
.WithLeadingTrivia(SyntaxFactory.Comment(DOCS))
// Rename to 'Redirection'
.WithIdentifier(SyntaxFactory.Identifier("Redirection"))
// Disable inheritance, but implement IDisposable
.WithBaseList(SyntaxFactory.BaseList().AddTypes(disposableType))
// Embed helpers, missing field
.AddMembers(field, helpersClass);
// Generate namespace (or member, if no namespace is specified)
MemberDeclarationSyntax @namespace = ns == null
? (MemberDeclarationSyntax)methodRedirectionClass
: SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(ns)).AddMembers(methodRedirectionClass);
var extCalls = @namespace.DescendantNodes()
.OfType<InvocationExpressionSyntax>()
.Where(x => x.Expression is MemberAccessExpressionSyntax access && extMethodsNames.Contains(access.Name.Identifier.Text));
var helpersAccess = SyntaxFactory.IdentifierName("Helpers");
@namespace = @namespace.ReplaceNodes(
extCalls,
(x, _) => SyntaxFactory.InvocationExpression(((MemberAccessExpressionSyntax)x.Expression).WithExpression(helpersAccess)).WithArgumentList(x.ArgumentList.WithArguments(x.ArgumentList.Arguments.Insert(0, SyntaxFactory.Argument(((MemberAccessExpressionSyntax)x.Expression).Expression)))));
// Generate syntax root
CompilationUnitSyntax root = SyntaxFactory.CompilationUnit()
.AddUsings(usings)
.AddMembers(@namespace);
// Print root to file
using (FileStream fs = File.OpenWrite(output))
using (TextWriter writer = new StreamWriter(fs))
{
fs.SetLength(0);
Formatter.Format(root, new AdhocWorkspace()).WriteTo(writer);
}
}
catch (Exception e)
{
Console.Error.WriteLine("Error encountered:");
Console.Error.WriteLine(e.Message);
return 1;
}
return 0;
}
}
}