forked from MessagePack-CSharp/MessagePack-CSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MessagePackCompilation.cs
316 lines (279 loc) · 11.5 KB
/
MessagePackCompilation.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
namespace MessagePackCompiler
{
public class MessagePackCompilation
{
public static async Task<CSharpCompilation> CreateFromProjectAsync(string[] csprojs, string[] preprocessorSymbols, CancellationToken cancellationToken)
{
var parseOption = new CSharpParseOptions(LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessorSymbols);
var syntaxTrees = new List<SyntaxTree>();
var metadata = new[]
{
typeof(object),
typeof(Enumerable),
typeof(Task<>),
typeof(IgnoreDataMemberAttribute),
typeof(System.Collections.Generic.List<>),
typeof(System.Collections.Concurrent.ConcurrentDictionary<,>),
}
.Select(x => x.Assembly.Location)
.Distinct()
.Select(x => MetadataReference.CreateFromFile(x))
.ToList();
var sources = new List<string>();
var locations = new List<string>();
foreach (var csproj in csprojs)
{
CollectDocument(csproj, sources, locations);
}
var hasAnnotations = false;
foreach (var file in sources.Distinct())
{
var text = await File.ReadAllTextAsync(file.Replace('\\', Path.DirectorySeparatorChar), Encoding.UTF8, cancellationToken);
var syntax = CSharpSyntaxTree.ParseText(text, parseOption);
syntaxTrees.Add(syntax);
if (Path.GetFileNameWithoutExtension(file) == "Attributes")
{
var root = await syntax.GetRootAsync(cancellationToken);
if (root.DescendantNodes().OfType<ClassDeclarationSyntax>().Any(x => x.Identifier.Text == "MessagePackObjectAttribute"))
{
hasAnnotations = true;
}
}
}
if (!hasAnnotations)
{
syntaxTrees.Add(CSharpSyntaxTree.ParseText(DummyAnnotation, parseOption));
}
var nazoloc = locations.Distinct();
foreach (var item in locations.Distinct().Where(x => !x.Contains("MonoBleedingEdge")))
{
metadata.Add(MetadataReference.CreateFromFile(item));
}
var compilation = CSharpCompilation.Create(
"MessagepackCodeGenTemp",
syntaxTrees,
metadata,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true));
return compilation;
}
static void CollectDocument(string csproj, List<string> source, List<string> metadataLocations)
{
XDocument document;
using (var sr = new StreamReader(csproj, true))
{
var reader = new XmlTextReader(sr);
reader.Namespaces = false;
document = XDocument.Load(reader, LoadOptions.None);
}
var csProjRoot = Path.GetDirectoryName(csproj);
var framworkRoot = Path.GetDirectoryName(typeof(object).Assembly.Location);
// Legacy
// <Project ToolsVersion=...>
// New
// <Project Sdk="Microsoft.NET.Sdk">
var proj = document.Element("Project");
var legacyFormat = proj.Attribute("Sdk")?.Value != "Microsoft.NET.Sdk";
if (!legacyFormat)
{
// TODO:parase compile remove
foreach (var file in IterateCsFileWithoutBinObj(Path.GetDirectoryName(csproj)))
{
source.Add(file);
}
// TODO:resolve NuGet reference
// RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
}
{
// files
foreach (var item in document.Descendants("Compile"))
{
var include = item.Attribute("Include")?.Value;
if (include != null)
{
source.Add(Path.Combine(csProjRoot, include));
}
}
// shared
foreach (var item in document.Descendants("Import"))
{
if (item.Attribute("Label")?.Value == "Shared")
{
var sharedRoot = Path.GetDirectoryName(Path.Combine(csProjRoot, item.Attribute("Project").Value));
foreach (var file in IterateCsFileWithoutBinObj(Path.GetDirectoryName(sharedRoot)))
{
source.Add(file);
}
}
}
// proj-ref
foreach (var item in document.Descendants("ProjectReference"))
{
var refCsProjPath = item.Attribute("Include")?.Value;
if (refCsProjPath != null)
{
CollectDocument(Path.Combine(csProjRoot, refCsProjPath), source, metadataLocations);
}
}
// metadata
foreach (var item in document.Descendants("Reference"))
{
var hintPath = item.Element("HintPath")?.Value;
if (hintPath == null)
{
var path = Path.Combine(framworkRoot, item.Attribute("Include").Value + ".dll");
metadataLocations.Add(path);
}
else
{
metadataLocations.Add(Path.Combine(csProjRoot, hintPath));
}
}
}
}
public static async Task<CSharpCompilation> CreateFromDirectoryAsync(string directoryRoot, string[] preprocessorSymbols, CancellationToken cancellationToken)
{
var parseOption = new CSharpParseOptions(LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessorSymbols);
var hasAnnotations = false;
var syntaxTrees = new List<SyntaxTree>();
foreach (var file in IterateCsFileWithoutBinObj(directoryRoot))
{
var text = await File.ReadAllTextAsync(file.Replace('\\', Path.DirectorySeparatorChar), Encoding.UTF8, cancellationToken);
var syntax = CSharpSyntaxTree.ParseText(text, parseOption);
syntaxTrees.Add(syntax);
if (Path.GetFileNameWithoutExtension(file) == "Attributes")
{
var root = await syntax.GetRootAsync(cancellationToken);
if (root.DescendantNodes().OfType<ClassDeclarationSyntax>().Any(x => x.Identifier.Text == "MessagePackObjectAttribute"))
{
hasAnnotations = true;
}
}
}
if (!hasAnnotations)
{
syntaxTrees.Add(CSharpSyntaxTree.ParseText(DummyAnnotation, parseOption));
}
var metadata = new[]
{
typeof(object),
typeof(Enumerable),
typeof(Task<>),
typeof(IgnoreDataMemberAttribute),
typeof(System.Collections.Generic.List<>),
typeof(System.Collections.Concurrent.ConcurrentDictionary<,>),
}
.Select(x => x.Assembly.Location)
.Distinct()
.Select(x => MetadataReference.CreateFromFile(x))
.ToList();
var compilation = CSharpCompilation.Create(
"MessagepackCodeGenTemp",
syntaxTrees,
metadata,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true));
return compilation;
}
static IEnumerable<string> IterateCsFileWithoutBinObj(string root)
{
foreach (var item in Directory.EnumerateFiles(root, "*.cs", SearchOption.TopDirectoryOnly))
{
yield return item;
}
foreach (var dir in Directory.GetDirectories(root, "*", SearchOption.TopDirectoryOnly))
{
var dirName = new DirectoryInfo(dir).Name;
if (dirName == "bin" || dirName == "obj") continue;
foreach (var item in IterateCsFileWithoutBinObj(dir))
{
yield return item;
}
}
}
const string DummyAnnotation = @"
using System;
namespace MessagePack
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public class MessagePackObjectAttribute : Attribute
{
public bool KeyAsPropertyName { get; private set; }
public MessagePackObjectAttribute(bool keyAsPropertyName = false)
{
this.KeyAsPropertyName = keyAsPropertyName;
}
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class KeyAttribute : Attribute
{
public int? IntKey { get; private set; }
public string StringKey { get; private set; }
public KeyAttribute(int x)
{
this.IntKey = x;
}
public KeyAttribute(string x)
{
this.StringKey = x;
}
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class IgnoreMemberAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class UnionAttribute : Attribute
{
public int Key { get; private set; }
public Type SubType { get; private set; }
public UnionAttribute(int key, Type subType)
{
this.Key = key;
this.SubType = subType;
}
}
[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = true)]
public class SerializationConstructorAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MessagePackFormatterAttribute : Attribute
{
public Type FormatterType { get; private set; }
public object[] Arguments { get; private set; }
public MessagePackFormatterAttribute(Type formatterType)
{
this.FormatterType = formatterType;
}
public MessagePackFormatterAttribute(Type formatterType, params object[] arguments)
{
this.FormatterType = formatterType;
this.Arguments = arguments;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace MessagePack
{
public interface IMessagePackSerializationCallbackReceiver
{
void OnBeforeSerialize();
void OnAfterDeserialize();
}
}
";
}
}