-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generator.cs
429 lines (372 loc) · 12.6 KB
/
Generator.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//
// Author:
// Marek Habersack <[email protected]>
//
// Copyright (c) 2010, Marek Habersack
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
// * Neither the name of Marek Habersack nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Reflection;
using System.Xml;
using Mono.Cecil;
using Mono.Collections.Generic;
namespace StubGen
{
public class Generator
{
static readonly Dictionary <string, string> license2resource = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase)
{
{"Apache2", "Apache2LicencePolicy.xml"},
{"GPL2", "GPL2LicencePolicy.xml"},
{"GPL3", "GPL3LicencePolicy.xml"},
{"LGPL2", "LGPL3LicencePolicy.xml"},
{"NewBSD", "NewBSDLicencePolicy.xml"},
{"MIT", "MITX11LicencePolicy.xml"}
};
static readonly List <Macro> macros = new List<Macro>
{
{ new Macro { Name="FileName", Handler=MacroFileName } },
{ new Macro { Name="FileNameWithoutExtension", Handler=MacroFileNameWithoutExtension } },
{ new Macro { Name="Directory", Handler=MacroDirectory } },
{ new Macro { Name="FullFileName", Handler=MacroFullFileName } },
{ new Macro { Name="AuthorName", Handler=MacroAuthorName } },
{ new Macro { Name="AuthorEmail", Handler=MacroAuthorEmail } },
{ new Macro { Name="CopyrightHolder", Handler=MacroCopyrightHolder } },
{ new Macro { Name="Year", Handler=MacroYear } },
};
public static readonly string NewLine = Environment.NewLine;
static Dictionary <string, string> licenseCache = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase);
static string currentFilePath;
static StubGenOptions sgopts;
static bool AssemblyPresent (string name)
{
// TODO: should probably call gacutil
try {
Assembly.Load (name);
return true;
} catch {
return false;
}
}
public static void Run (string assemblyPath, StubGenOptions opts, string outDir)
{
sgopts = opts;
string license = GetLicenseBlock (opts.LicenseName);
bool overwrite = opts.OverwriteAll;
ModuleDefinition module = ModuleDefinition.ReadModule (assemblyPath);
Console.Error.WriteLine ("\tTarget runtime: {0}", module.Runtime.Format ());
if (module.HasAssemblyReferences) {
var typesPerAsm = new SortedDictionary <string, ulong> (StringComparer.Ordinal);
AssemblyNameReference asmname;
foreach (ModuleDefinition m in AssemblyDefinition.ReadAssembly (assemblyPath).Modules) {
foreach (TypeReference tref in m.GetTypeReferences ().OnlyVisible (true)) {
asmname = tref.Scope as AssemblyNameReference;
if (asmname == null)
continue;
if (typesPerAsm.ContainsKey (asmname.FullName))
typesPerAsm [asmname.FullName]++;
else
typesPerAsm [asmname.FullName] = 1;
}
}
var refs = new List <string> ();
Console.Error.WriteLine ("\tAssembly references:");
foreach (AssemblyNameReference aref in module.AssemblyReferences)
refs.Add (aref.FullName);
refs.Sort (StringComparer.Ordinal);
var unused = new List <string> ();
bool present;
ulong count;
foreach (string s in refs) {
present = AssemblyPresent (s);
if (!typesPerAsm.TryGetValue (s, out count))
count = 0;
if (count == 0)
unused.Add (s);
Console.Error.Write ("\t [");
if (present)
Console.Error.Write ("present]");
else {
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.Write ("missing]");
Console.ForegroundColor = ConsoleColor.DarkRed;
}
Console.Error.WriteLine (" {0}", s);
Console.ResetColor ();
}
if (unused.Count > 0) {
Console.Error.WriteLine ();
Console.Error.WriteLine ("\tAssemblies referenced but not used by public APIs:");
unused.Sort ();
foreach (string s in unused)
Console.Error.WriteLine ("\t {0}", s);
}
}
OutputAssemblyInfo (module, outDir, license, overwrite);
foreach (TypeDefinition type in module.Types) {
if (type.IsNotPublic)
continue;
try {
currentFilePath = FilePathForType (outDir, type);
if (!overwrite && File.Exists (currentFilePath)) {
currentFilePath = null;
continue;
}
using (FileStream fs = File.Open (currentFilePath, FileMode.Create, FileAccess.Write)) {
using (var sw = new StreamWriter (fs, Encoding.UTF8)) {
WriteHeader (sw, license);
Outline.Run (currentFilePath, license, sw, type, opts);
}
}
} catch (Exception ex) {
Console.WriteLine ("\tFailure. Unable to generate file for type {0}. {1}", type.FullName, ex.Message);
if (opts.Debug)
Console.WriteLine (ex);
}
}
}
static void WriteHeader (StreamWriter writer, string license)
{
if (sgopts.NoHeader)
return;
writer.WriteLine (ReplaceMacros (license));
}
static void OutputAssemblyInfo (ModuleDefinition module, string outDir, string license, bool overwrite)
{
currentFilePath = Path.Combine (outDir, "Assembly");
if (!Directory.Exists (currentFilePath))
Directory.CreateDirectory (currentFilePath);
currentFilePath = Path.Combine (currentFilePath, "AssemblyInfo.cs");
if (!overwrite && File.Exists (currentFilePath))
return;
// TODO: output TypeForwarded{From,To}
using (FileStream fs = File.OpenWrite (currentFilePath)) {
using (var sw = new StreamWriter (fs, Encoding.UTF8)) {
WriteHeader (sw, license);
var sb = new StringBuilder ();
var usings = new List <string> () {
{"System"},
{"System.Reflection"}
};
if (module.Assembly.HasCustomAttributes)
OutputAssemblyCustomAttributes (sb, usings, module);
if (module.Assembly.HasSecurityDeclarations)
OutputAssemblySecurityDeclarations (sb, usings, module);
usings.Sort ();
foreach (string u in usings)
sw.WriteLine ("using {0};", u);
sw.WriteLine ();
sw.WriteLine (sb.ToString ());
}
}
}
static void OutputAssemblyCustomAttributes (StringBuilder sb, List <string> usings, ModuleDefinition module)
{
Collection <CustomAttribute> attrs = module.Assembly.CustomAttributes;
if (attrs == null || attrs.Count == 0)
return;
string str;
TypeReference type;
bool first;
foreach (CustomAttribute attr in attrs) {
type = attr.AttributeType;
if (type.FullName == "System.Runtime.CompilerServices.ReferenceAssemblyAttribute")
continue;
str = type.Namespace;
usings.AddUsing (str);
str = type.Name;
if (str.EndsWith ("Attribute", StringComparison.Ordinal))
str = str.Substring (0, str.Length - 9);
sb.AppendFormat ("[assembly: {0}", str);
first = true;
bool needParen = false;
if (attr.HasConstructorArguments) {
needParen = true;
sb.Append (" (");
foreach (CustomAttributeArgument arg in attr.ConstructorArguments) {
if (!first)
sb.Append (", ");
else
first = false;
sb.Append (Utils.FormatValue (arg.Value, arg.Type, usings));
}
}
if (attr.HasFields) {
if (!needParen) {
needParen = true;
sb.Append (" (");
}
foreach (Mono.Cecil.CustomAttributeNamedArgument arg in attr.Fields) {
if (!first)
sb.Append (", ");
else
first = false;
sb.AppendFormat ("{0}={1}", arg.Name, Utils.FormatValue (arg.Argument.Value, arg.Argument.Type, usings));
}
}
if (attr.HasProperties) {
if (!needParen) {
needParen = true;
sb.Append (" (");
}
foreach (Mono.Cecil.CustomAttributeNamedArgument arg in attr.Properties) {
if (!first)
sb.Append (", ");
else
first = false;
sb.AppendFormat ("{0}={1}", arg.Name, Utils.FormatValue (arg.Argument.Value, arg.Argument.Type, usings));
}
}
if (needParen)
sb.Append (")");
sb.AppendLine ("]");
}
}
static void OutputAssemblySecurityDeclarations (StringBuilder sb, List <string> usings, ModuleDefinition module)
{
// TODO: implement
}
static string FilePathForType (string outDir, TypeDefinition type)
{
string dir = Path.Combine (outDir, type.Namespace);
if (!Directory.Exists (dir))
Directory.CreateDirectory (dir);
return Path.Combine (dir, type.Name + ".cs");
}
static string GetLicenseBlock (string name)
{
if (String.IsNullOrEmpty (name))
return null;
string str;
if (licenseCache.TryGetValue (name, out str))
return str;
if (license2resource.TryGetValue (name, out str)) {
try {
Assembly asm = Assembly.GetExecutingAssembly ();
Stream st = asm.GetManifestResourceStream ("StubGen.resources." + str);
if (st == null) {
Console.Error.Write ("\tNo resource for license '{0}'", name);
return null;
}
byte[] bytes = new byte [st.Length];
st.Read (bytes, 0, (int)st.Length);
str = ExtractTextFromXML (name, Encoding.UTF8.GetString (bytes));
bytes = null;
} catch (Exception ex) {
Console.Error.WriteLine ("\tFailed to get resource for license '{0}'. {1}", name, ex.Message);
return null;
}
} else {
if (!File.Exists (name)) {
Console.Error.Write ("\tLicense file '{0}' not found.", name);
return null;
}
str = File.ReadAllText (name);
}
if (String.IsNullOrEmpty (str)) {
licenseCache.Add (name, null);
return null;
}
string[] lines = str.Split ('\n');
var sb = new StringBuilder ();
foreach (string l in lines)
sb.Append ("// " + l + NewLine);
str = sb.ToString ();
licenseCache.Add (name, str);
return str;
}
static string ReplaceMacros (string input)
{
foreach (Macro m in macros)
input = input.Replace ("${" + m.Name + "}", m.Handler ());
return input;
}
static string MacroFileName ()
{
if (String.IsNullOrEmpty (currentFilePath))
return null;
return Path.GetFileName (currentFilePath);
}
static string MacroFileNameWithoutExtension ()
{
if (String.IsNullOrEmpty (currentFilePath))
return null;
return Path.GetFileNameWithoutExtension (currentFilePath);
}
static string MacroDirectory ()
{
if (String.IsNullOrEmpty (currentFilePath))
return null;
return Path.GetDirectoryName (currentFilePath);
}
static string MacroFullFileName ()
{
if (String.IsNullOrEmpty (currentFilePath))
return null;
return currentFilePath;
}
static string MacroAuthorName ()
{
if (sgopts == null)
return null;
return sgopts.AuthorName;
}
static string MacroAuthorEmail ()
{
if (sgopts == null)
return null;
return sgopts.AuthorEmail;
}
static string MacroCopyrightHolder ()
{
if (sgopts == null)
return null;
return sgopts.CopyrightHolder;
}
static string MacroYear ()
{
return DateTime.Now.Year.ToString ();
}
static string ExtractTextFromXML (string name, string input)
{
try {
var doc = new XmlDocument ();
doc.LoadXml (input);
XmlNode node = doc.SelectSingleNode ("StandardHeader");
if (node == null)
return null;
XmlAttribute attr = node.Attributes ["Text"];
if (attr == null)
return null;
return attr.Value;
} catch (Exception ex) {
Console.Error.WriteLine ("\tFailed to parse license '{0}' XML. {1}", name, ex.Message);
}
return null;
}
}
}