This repository was archived by the owner on Aug 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathProgram.cs
More file actions
906 lines (742 loc) · 41.8 KB
/
Copy pathProgram.cs
File metadata and controls
906 lines (742 loc) · 41.8 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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using JSIL.Compiler.Extensibility;
using JSIL.Internal;
using JSIL.Translator;
using JSIL.Utilities;
using Mono.Cecil;
namespace JSIL.Compiler {
public class Program {
private static bool Quiet = false;
static TypeInfoProvider CachedTypeInfoProvider = null;
static Configuration CachedTypeInfoProviderConfiguration = null;
public static string ShortenPath (string path) {
var cwd = new Uri(Environment.CurrentDirectory);
Uri pathUri;
if (Uri.TryCreate(path, UriKind.Absolute, out pathUri)) {
var relativeUri = cwd.MakeRelativeUri(pathUri);
var shortened = Uri.UnescapeDataString(relativeUri.ToString()).Replace('/', Path.DirectorySeparatorChar);
if (shortened.Length < path.Length)
return shortened;
}
return path;
}
static Configuration LoadConfiguration (string filename) {
var jss = new JavaScriptSerializer();
try {
var json = File.ReadAllText(filename);
var result = jss.Deserialize<Configuration>(json);
result.Path = Path.GetDirectoryName(Path.GetFullPath(filename));
result.ContributingPaths = new[] { Path.GetFullPath(filename) };
InformationWriteLine("// Applied settings from '{0}'.", ShortenPath(filename));
return result;
} catch (Exception ex) {
Console.Error.WriteLine("// Error reading '{0}': {1}", filename, ex);
throw;
}
}
static string MapPath (string path, VariableSet variables, bool ensureExists, bool reportErrors = false) {
var result = variables.ExpandPath(path, false);
if (ensureExists) {
if (!Directory.Exists(result) && !File.Exists(result)) {
if (reportErrors)
Console.Error.WriteLine("// Could not find file '{0}' -> '{1}'!", path, result);
return null;
}
}
return result;
}
static Configuration MergeConfigurations (Configuration baseConfiguration, params Configuration[] toMerge) {
var result = baseConfiguration.Clone();
foreach (var m in toMerge)
m.MergeInto(result);
return (Configuration)result;
}
/// <summary>
/// Skip Invalid Assemblies (Such as "*Setup.exe"s generated by WiX),
/// putting a pattern matching "Setup.exe" in ignored does not seem to be enough.
/// </summary>
[DebuggerStepThrough]
private static AssemblyDefinition TryReadAssembly(string fileName)
{
try
{
return AssemblyDefinition.ReadAssembly(fileName);
}
catch(BadImageFormatException ex)
{
Console.Error.WriteLine("// Invalid .NET Assembly: \"" + fileName + "\". It will not be loaded.");
Console.Error.WriteLine("// Reason: " + ex.Message.Trim().Replace(Environment.NewLine, Environment.NewLine + "// "));
return null;
}
}
static string[] PurgeDuplicateFilesFromBuildGroup (
string[] buildGroupFiles,
AssemblyCache assemblyCache,
HashSet<string> skippedAssemblies
) {
var result = new List<string>();
var topLevelAssemblies =
(from fn in buildGroupFiles
select new {
Filename = fn,
Assembly = TryReadAssembly(fn)
})
.Where(o => o.Assembly != null)
.ToArray();
var executables =
(from kvp in topLevelAssemblies
where kvp.Filename.EndsWith(".exe")
select new {
Filename = kvp.Filename,
Assembly = kvp.Assembly,
AllReferencesRecursive = new List<AssemblyNameReference>()
}).ToArray();
foreach (var executable in executables) {
var assembliesToScan = new Stack<AssemblyDefinition>();
assembliesToScan.Push(executable.Assembly);
while (assembliesToScan.Count > 0) {
var assembly = assembliesToScan.Pop();
foreach (var module in assembly.Modules) {
foreach (var anr in module.AssemblyReferences) {
executable.AllReferencesRecursive.Add(anr);
var matchingAssembly = topLevelAssemblies.FirstOrDefault(
(tla) => tla.Assembly.FullName == anr.FullName
);
if (matchingAssembly != null)
assembliesToScan.Push(matchingAssembly.Assembly);
}
}
}
}
foreach (var kvpOuter in topLevelAssemblies) {
foreach (var kvpInner in executables) {
if (kvpInner.Filename == kvpOuter.Filename)
continue;
// If an executable references a DLL, we can be sure the DLL is going to get built anyway.
foreach (var anr in kvpInner.AllReferencesRecursive) {
if (anr.FullName == kvpOuter.Assembly.FullName) {
InformationWriteLine("// Not translating '{0}' directly because '{1}' references it.", Path.GetFileName(kvpOuter.Filename), Path.GetFileName(kvpInner.Filename));
skippedAssemblies.Add(kvpOuter.Filename);
goto skip;
}
}
}
result.Add(kvpOuter.Filename);
skip:
;
}
return result.ToArray();
}
static Configuration ParseCommandLine (
IEnumerable<string> arguments, List<BuildGroup> buildGroups,
Dictionary<string, IProfile> profiles, Dictionary<string, IAnalyzer> analyzers,
Dictionary<string, Func<IEmitterGroupFactory>> emitterFactories,
AssemblyCache assemblyCache
) {
var baseConfig = new Configuration();
var commandLineConfig = new Configuration();
IProfile defaultProfile = new Profiles.Default();
var profileAssemblies = new List<string>();
var analyzerAssemblies = new List<string>();
var emitterAssemblies = new List<string>();
bool[] autoloadProfiles = new bool[] { true };
bool[] autoloadAnalyzers = new bool[] { true };
bool[] autoloadEmitters = new bool[] { true };
List<string> filenames;
{
var os = new Mono.Options.OptionSet {
{"o=|out=",
"Specifies the output directory for generated javascript and manifests.",
(path) => commandLineConfig.OutputDirectory = Path.GetFullPath(path) },
{"outLibraries=",
"Specifies the output directory for JSIL Libraries.",
(path) => commandLineConfig.JsLibrariesOutputDirectory = Path.GetFullPath(path) },
{"q|quiet",
"Suppresses non-error/non-warning stderr messages.",
(_) => commandLineConfig.Quiet = Quiet = true },
{"nac|noautoconfig",
"Suppresses automatic loading of same-named .jsilconfig files located next to solutions and/or assemblies.",
(b) => commandLineConfig.AutoLoadConfigFiles = b == null },
{"nt|nothreads",
"Suppresses use of multiple threads to speed up the translation process.",
(b) => commandLineConfig.UseThreads = b == null },
{"sbc|suppressbugcheck",
"Suppresses JSIL bug checks that detect bugs in .NET runtimes and standard libraries.",
(b) => commandLineConfig.RunBugChecks = b == null },
"Solution Builder options",
{"configuration=",
"When building one or more solution files, specifies the build configuration to use (like 'Debug').",
(v) => commandLineConfig.SolutionBuilder.Configuration = v },
{"platform=",
"When building one or more solution files, specifies the build platform to use (like 'x86').",
(v) => commandLineConfig.SolutionBuilder.Platform = v },
{"target=",
"When building one or more solution files, specifies the build target to use (like 'Build'). The default is 'Build'.",
(v) => commandLineConfig.SolutionBuilder.Target = v },
{"logVerbosity=",
"When building one or more solution files, specifies the level of log verbosity. Valid options are 'Quiet', 'Minimal', 'Normal', 'Detailed', and 'Diagnostic'.",
(v) => commandLineConfig.SolutionBuilder.LogVerbosity = v },
"Assembly options",
{"p=|proxy=",
"Loads a type proxy assembly to provide type information for the translator.",
(name) => commandLineConfig.Assemblies.Proxies.Add(Path.GetFullPath(name)) },
{"i=|ignore=",
"Specifies a regular expression pattern for assembly names that should be ignored during the translation process.",
(regex) => commandLineConfig.Assemblies.Ignored.Add(regex) },
{"s=|stub=",
"Specifies a regular expression pattern for assembly names that should be stubbed during the translation process. " +
"Stubbing forces all methods to be externals.",
(regex) => commandLineConfig.Assemblies.Stubbed.Add(regex) },
{"nd|nodeps",
"Suppresses the automatic loading and translation of assembly dependencies.",
(b) => commandLineConfig.IncludeDependencies = b == null},
{"nodefaults",
"Suppresses the default list of stubbed assemblies.",
(b) => commandLineConfig.ApplyDefaults = b == null},
{"nolocal",
"Disables using local proxy types from translated assemblies.",
(b) => commandLineConfig.UseLocalProxies = b == null},
{"fv=|frameworkVersion=",
"Specifies the version of the .NET framework proxies to use. " +
"This ensures that correct type information is provided (as different versions of the framework use different standard libraries). " +
"The only accepted value is currently '4.0'. Default: '4.0'",
(fv) => commandLineConfig.FrameworkVersion = double.Parse(fv)},
"Profile options",
{"nap|noautoloadprofiles",
"Disables automatic loading of profile assemblies from the compiler directory.",
(b) => autoloadProfiles[0] = (b == null)},
{"pa=|profileAssembly=",
"Loads one or more project profiles from the specified profile assembly. Note that this does not force the profiles to be used.",
profileAssemblies.Add},
"CodeGenerator options",
{"os",
"Suppresses struct copy elimination.",
(b) => commandLineConfig.CodeGenerator.EliminateStructCopies = b == null},
{"ot",
"Suppresses temporary local variable elimination.",
(b) => commandLineConfig.CodeGenerator.EliminateTemporaries = b == null},
{"oo",
"Suppresses simplification of operator expressions and special method calls.",
(b) => commandLineConfig.CodeGenerator.SimplifyOperators = b == null},
{"ol",
"Suppresses simplification of loop blocks.",
(b) => commandLineConfig.CodeGenerator.SimplifyLoops = b == null},
"Emitter options",
{"nae|noautoloademitters",
"Disables automatic loading of emitter assemblies from the compiler directory.",
(b) => autoloadEmitters[0] = (b == null)},
{"ea=|emitterAssembly=",
"Specifies an assembly to load emitters from.",
emitterAssemblies.Add},
{"e=|emitter=",
"Specifies an emitter factory to use instead of the default.",
(emitterName) => commandLineConfig.EmitterFactories.Add(emitterName)}
};
filenames = os.Parse(arguments);
if (filenames.Count == 0) {
var asmName = Assembly.GetExecutingAssembly().GetName();
Console.WriteLine("==== JSILc v{0}.{1}.{2} ====", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision);
Console.WriteLine("Specify one or more compiled assemblies (dll/exe) to translate them. Symbols will be loaded if they exist in the same directory.");
Console.WriteLine("You can also specify Visual Studio solution files (sln) to build them and automatically translate their output(s).");
Console.WriteLine("Specify the path of a .jsilconfig file to load settings from it.");
os.WriteOptionDescriptions(Console.Out);
return null;
}
}
{
if (autoloadProfiles[0])
profileAssemblies.AddRange(Directory.GetFiles(
GetJSILDirectory(),
"JSIL.Profiles.*.dll"
));
if (autoloadAnalyzers[0])
analyzerAssemblies.AddRange(Directory.GetFiles(
GetJSILDirectory(),
"JSIL.Analysis.*.dll"
));
if (autoloadEmitters[0])
emitterAssemblies.AddRange(Directory.GetFiles(
GetJSILDirectory(),
"JSIL.Emitters.*.dll"
));
foreach (var filename in profileAssemblies) {
var fullPath = Path.GetFullPath(filename);
try {
IProfile profileInstance = CreateExtensionInstance<IProfile>(fullPath);
if (profileInstance != null)
profiles.Add(profileInstance.GetType().Name, profileInstance);
} catch (Exception exc) {
Console.Error.WriteLine("Warning: Failed to load profile '{0}': {1}", filename, exc);
}
}
foreach (var filename in analyzerAssemblies) {
var fullPath = Path.GetFullPath(filename);
try {
IAnalyzer analyzerInstance = CreateExtensionInstance<IAnalyzer>(fullPath);
if (analyzerInstance != null)
analyzers.Add(analyzerInstance.GetType().Name, analyzerInstance);
} catch (Exception exc) {
Console.Error.WriteLine("Warning: Failed to load analyzer '{0}': {1}", filename, exc);
}
}
foreach (var filename in emitterAssemblies) {
var fullPath = Path.GetFullPath(filename);
try {
var factoryInstanceCreator = CreateExtensionCreator<IEmitterGroupFactory>(fullPath);
if (factoryInstanceCreator != null)
emitterFactories.Add(factoryInstanceCreator.Item2.Name, factoryInstanceCreator.Item1);
} catch (Exception exc) {
Console.Error.WriteLine("Warning: Failed to load emitter '{0}': {1}", filename, exc);
}
}
}
var commandLineConfigFilenames =
(from fn in filenames
where Path.GetExtension(fn) == ".jsilconfig"
select fn).ToArray();
// Fail early on nonexistent configuration files
foreach (var filename in commandLineConfigFilenames)
if (!File.Exists(filename))
throw new FileNotFoundException(filename);
commandLineConfig = MergeConfigurations(
commandLineConfig,
(from fn in commandLineConfigFilenames
select LoadConfiguration(fn)).ToArray()
);
foreach (var solution in
(from fn in filenames where Path.GetExtension(fn) == ".sln" select fn)
) {
var solutionFullPath = Path.GetFullPath(solution);
var solutionDir = Path.GetDirectoryName(solutionFullPath);
if (solutionDir == null) {
Console.Error.WriteLine("// Can't process solution '{0}' - path seems malformed", solution);
continue;
}
// Fail early if a solution file is missing
if (!File.Exists(solutionFullPath))
throw new FileNotFoundException(solutionFullPath);
var solutionConfigPath = Path.Combine(
solutionDir,
String.Format("{0}.jsilconfig", Path.GetFileName(solutionFullPath))
);
var solutionConfig = File.Exists(solutionConfigPath)
? new Configuration[] { LoadConfiguration(solutionConfigPath) }
: new Configuration[] { };
var mergedSolutionConfig = MergeConfigurations(baseConfig, solutionConfig);
var config = MergeConfigurations(mergedSolutionConfig, commandLineConfig);
var buildStarted = DateTime.UtcNow.Ticks;
var buildResult = SolutionBuilder.SolutionBuilder.Build(
solutionFullPath,
config.SolutionBuilder.Configuration,
config.SolutionBuilder.Platform,
config.SolutionBuilder.Target ?? "Build",
config.SolutionBuilder.LogVerbosity
);
var jss = new JavaScriptSerializer {
MaxJsonLength = (1024 * 1024) * 64
};
var buildResultJson = jss.Serialize(buildResult);
buildResult = jss.Deserialize<SolutionBuilder.BuildResult>(buildResultJson);
var buildEnded = DateTime.UtcNow.Ticks;
IProfile profile = defaultProfile;
foreach (var candidateProfile in profiles.Values) {
if (!candidateProfile.IsAppropriateForSolution(buildResult))
continue;
InformationWriteLine("// Auto-selected the profile '{0}' for this project.", candidateProfile.GetType().Name);
profile = candidateProfile;
break;
}
var localVariables = config.ApplyTo(new VariableSet());
localVariables["SolutionDirectory"] = () => solutionDir;
// HACK to let you use assemblyname/etc when copying output files.
var buildResultAssembly =
buildResult.OutputFiles.FirstOrDefault((fn) => Path.GetExtension(fn) == ".exe") ??
buildResult.OutputFiles.FirstOrDefault((fn) => Path.GetExtension(fn) == ".dll");
if (buildResultAssembly != null) {
localVariables.SetAssemblyPath(buildResultAssembly);
}
var processStarted = DateTime.UtcNow.Ticks;
profile.ProcessBuildResult(
localVariables,
profile.GetConfiguration(config),
buildResult
);
var processEnded = DateTime.UtcNow.Ticks;
{
var logPath = localVariables.ExpandPath(String.Format(
"%outputdirectory%/{0}.buildlog", Path.GetFileName(solution)
), false);
if (!Directory.Exists(Path.GetDirectoryName(logPath)))
Directory.CreateDirectory(Path.GetDirectoryName(logPath));
using (var logWriter = new StreamWriter(logPath, false, Encoding.UTF8)) {
logWriter.WriteLine(
"Build of solution '{0}' processed {1} task(s) and produced {2} result file(s):",
solution, buildResult.AllItemsBuilt.Length, buildResult.OutputFiles.Length
);
foreach (var of in buildResult.OutputFiles)
logWriter.WriteLine(of);
logWriter.WriteLine("----");
logWriter.WriteLine("Elapsed build time: {0:0000.0} second(s).", TimeSpan.FromTicks(buildEnded - buildStarted).TotalSeconds);
logWriter.WriteLine("Selected profile '{0}' to process results of this build.", profile.GetType().Name);
logWriter.WriteLine("Elapsed processing time: {0:0000.0} second(s).", TimeSpan.FromTicks(processEnded - processStarted).TotalSeconds);
}
}
var outputFiles = buildResult.OutputFiles.Concat(
(from eo in config.SolutionBuilder.ExtraOutputs
let expanded = localVariables.ExpandPath(eo, true)
select expanded)
).ToArray();
if (outputFiles.Length > 0) {
var sa = new HashSet<string>();
var group = new BuildGroup {
BaseConfiguration = mergedSolutionConfig,
BaseVariables = localVariables,
FilesToBuild = PurgeDuplicateFilesFromBuildGroup(outputFiles, assemblyCache, sa),
Profile = profile,
};
group.SkippedAssemblies = sa.ToArray();
buildGroups.Add(group);
}
}
var assemblyNames = (from fn in filenames
where Path.GetExtension(fn).Contains(",") ||
Path.GetExtension(fn).Contains(" ") ||
Path.GetExtension(fn).Contains("=")
select fn).ToArray();
var resolver = new Mono.Cecil.DefaultAssemblyResolver();
var metaResolver = new CachingMetadataResolver(resolver);
var resolverParameters = new ReaderParameters {
AssemblyResolver = resolver,
MetadataResolver = metaResolver,
ReadSymbols = false,
ReadingMode = ReadingMode.Deferred,
};
var resolvedAssemblyPaths = (from an in assemblyNames
let asm = resolver.Resolve(an, resolverParameters)
where asm != null
select asm.MainModule.FullyQualifiedName).ToArray();
var mainGroup = (from fn in filenames
where
(new[] { ".exe", ".dll" }.Contains(Path.GetExtension(fn)))
select fn)
.Concat(resolvedAssemblyPaths)
.ToArray();
if (mainGroup.Length > 0) {
var variables = commandLineConfig.ApplyTo(new VariableSet());
// Fail early if any assemblies are missing
foreach (var filename in mainGroup) {
if (!File.Exists(filename))
throw new FileNotFoundException(filename);
}
buildGroups.Add(new BuildGroup {
BaseConfiguration = baseConfig,
BaseVariables = variables,
FilesToBuild = mainGroup,
Profile = defaultProfile
});
}
return commandLineConfig;
}
internal static Tuple<Func<T>, Type> CreateExtensionCreator<T>(string fullPath)
{
var assembly = Assembly.LoadFile(fullPath);
foreach (var type in assembly.GetTypes())
{
if (
type.FindInterfaces(
(interfaceType, o) => interfaceType == (Type)o, typeof(T)
).Length != 1
)
continue;
var ctor = type.GetConstructor(
BindingFlags.Public | BindingFlags.Instance,
null, System.Type.EmptyTypes, null
);
var profileInstance = (T)ctor.Invoke(new object[0]);
return new Tuple<Func<T>, Type>(() => (T) ctor.Invoke(new object[0]), type);
}
return null;
}
internal static T CreateExtensionInstance<T>(string fullPath) {
var creator = CreateExtensionCreator<T>(fullPath);
return creator != null ? creator.Item1() : default(T);
}
internal static string GetJSILDirectory () {
return Path.GetDirectoryName(JSIL.Internal.Util.GetPathOfAssembly(Assembly.GetExecutingAssembly()));
}
static ProgressHandler MakeProgressHandler (string description) {
const int scale = 40;
return (progress) => {
if (!Quiet)
Console.Error.Write("// {0} ", description);
var previous = new int[1] { 0 };
progress.ProgressChanged += (s, p, max) => {
var current = p * scale / max;
var delta = current - previous[0];
if (delta > 0) {
previous[0] = current;
if (!Quiet) {
for (var i = 0; i < delta; i++)
Console.Error.Write(".");
}
}
};
progress.Finished += (s, e) => {
var delta = scale - previous[0];
if (!Quiet) {
for (var i = 0; i < delta; i++)
Console.Error.Write(".");
}
InformationWriteLine(" done.");
};
};
}
static IEmitterGroupFactory[] GetEmitterFactories (
Configuration configuration,
Dictionary<string, IEmitterGroupFactory> emitterFactories
) {
var emitters = new List<IEmitterGroupFactory>();
if (configuration.EmitterFactories.Count == 0) {
emitters.Add(emitterFactories[typeof(JavascriptEmitterGroupFactory).Name]);
}
foreach (var emitterFactory in configuration.EmitterFactories) {
IEmitterGroupFactory factory;
if (!emitterFactories.TryGetValue(emitterFactory, out factory))
{
if (!emitterFactories.TryGetValue(emitterFactory + "EmitterFactory", out factory))
{
Console.WriteLine("// Loaded emitter factories:");
foreach (var kvp in emitterFactories)
Console.WriteLine(kvp.Key);
throw new Exception("No emitter factory named '" + emitterFactory + "' or '" + emitterFactory + "EmitterFactory'");
}
}
emitters.Add(factory);
}
return emitters.ToArray();
}
static AssemblyTranslator CreateTranslator (
Configuration configuration, AssemblyManifest manifest, AssemblyCache assemblyCache,
Dictionary<string, IEmitterGroupFactory> emitterFactories,
Dictionary<string, IAnalyzer> analyzers
) {
TypeInfoProvider typeInfoProvider = null;
InformationWriteLine(
"// Using .NET framework {0} in {1} GC mode. Tuned GC {2}.",
Environment.Version.ToString(),
System.Runtime.GCSettings.IsServerGC ? "server" : "workstation",
configuration.TuneGarbageCollection.GetValueOrDefault(true) ? "enabled" : "disabled"
);
if (
configuration.ReuseTypeInfoAcrossAssemblies.GetValueOrDefault(true) &&
(CachedTypeInfoProvider != null)
) {
if (CachedTypeInfoProviderConfiguration.Assemblies.Equals(configuration.Assemblies))
typeInfoProvider = CachedTypeInfoProvider;
}
IEmitterGroupFactory[] emitterGroupFactories = GetEmitterFactories(configuration, emitterFactories);
var translator = new AssemblyTranslator(
configuration, typeInfoProvider, manifest, new AssemblyDataResolver(configuration, assemblyCache),
onProxyAssemblyLoaded: (name, classification) =>
InformationWriteLine("// Loaded proxies from '{0}'", ShortenPath(name)),
analyzers: analyzers.Values,
emitterGroupFactories: emitterGroupFactories
);
translator.Decompiling += MakeProgressHandler ("Decompiling ");
translator.RunningTransforms += MakeProgressHandler ("Translating ");
translator.Writing += MakeProgressHandler ("Writing JS ");
translator.AssemblyLoaded += (fn, classification) =>
InformationWriteLine("// Loaded {0} ({1})", ShortenPath(fn), classification);
translator.CouldNotLoadSymbols += (fn, ex) => {
};
translator.CouldNotResolveAssembly += (fn, ex) =>
Console.Error.WriteLine("// Could not load module {0}: {1}", fn, ex.Message);
translator.CouldNotDecompileMethod += (fn, ex) =>
Console.Error.WriteLine("// Could not decompile method {0}: {1}", fn, ex);
if (configuration.ProxyWarnings.GetValueOrDefault(false)) {
translator.ProxyNotMatched += (ti) => {
Console.Error.WriteLine("// Proxy {0} never matched any types.", ti);
};
translator.ProxyMemberNotMatched += (qmi) => {
Console.Error.WriteLine("// Proxy member {0} never matched any members.", qmi);
};
}
if (typeInfoProvider == null) {
if (CachedTypeInfoProvider != null)
CachedTypeInfoProvider.Dispose();
CachedTypeInfoProvider = translator.GetTypeInfoProvider();
CachedTypeInfoProviderConfiguration = configuration;
}
return translator;
}
public static void Main (string[] arguments) {
try {
InternalMain(arguments);
} catch (Exception exc) {
Console.WriteLine(exc);
Environment.ExitCode = 1024;
return;
}
}
static void InternalMain (string[] arguments) {
SolutionBuilder.SolutionBuilder.HandleCommandLine();
var buildGroups = new List<BuildGroup>();
var profiles = new Dictionary<string, IProfile>();
var analyzers = new Dictionary<string, IAnalyzer>();
var emitterFactoryCreators = new Dictionary<string, Func<IEmitterGroupFactory>>();
var manifest = new AssemblyManifest();
var assemblyCache = new AssemblyCache();
var commandLineConfiguration = ParseCommandLine(arguments, buildGroups, profiles, analyzers, emitterFactoryCreators, assemblyCache);
if ((buildGroups.Count < 1) || (commandLineConfiguration == null)) {
Console.Error.WriteLine("// No assemblies specified to translate. Exiting.");
}
int totalFailureCount = 0;
foreach (var buildGroup in buildGroups) {
var config = buildGroup.BaseConfiguration;
var variables = buildGroup.BaseVariables;
foreach (var filename in buildGroup.FilesToBuild) {
if (config.Assemblies.Ignored.Any(
(ignoreRegex) => Regex.IsMatch(filename, ignoreRegex, RegexOptions.IgnoreCase))
) {
InformationWriteLine("// Ignoring build result '{0}' based on configuration.", Path.GetFileName(filename));
continue;
}
string fileConfigPath;
var fileConfigSearchDir = Path.GetDirectoryName(filename);
var separators = new char[] { '/', '\\' };
do {
fileConfigPath = Path.Combine(
fileConfigSearchDir,
String.Format("{0}.jsilconfig", Path.GetFileName(filename))
);
if (!File.Exists(fileConfigPath))
fileConfigSearchDir = Path.GetFullPath(Path.Combine(fileConfigSearchDir, ".."));
else
break;
} while (fileConfigSearchDir.IndexOfAny(separators, 3) > 0);
var fileConfig = File.Exists(fileConfigPath)
? new Configuration[] { LoadConfiguration(fileConfigPath), commandLineConfiguration }
: new Configuration[] { commandLineConfiguration };
var localConfig = MergeConfigurations(config, fileConfig);
if (localConfig.ApplyDefaults.GetValueOrDefault(true))
{
localConfig = MergeConfigurations(
LoadConfiguration(Path.Combine(
GetJSILDirectory(),
"defaults.jsilconfig"
)),
localConfig
);
}
var localProfile = buildGroup.Profile;
if (localConfig.Profile != null) {
if (profiles.ContainsKey(localConfig.Profile))
localProfile = profiles[localConfig.Profile];
else
throw new Exception(String.Format(
"No profile named '{0}' was found. Did you load the correct profile assembly?", localConfig.Profile
));
}
localConfig = localProfile.GetConfiguration(localConfig);
var localVariables = localConfig.ApplyTo(variables);
localVariables.SetAssemblyPath(filename);
var newProxies = (from p in localConfig.Assemblies.Proxies
let newP = MapPath(p, localVariables, true, true)
where newP != null
select newP).ToArray();
localConfig.Assemblies.Proxies.Clear();
localConfig.Assemblies.Proxies.AddRange(newProxies);
var newAdditionalTranslate = (from p in localConfig.Assemblies.TranslateAdditional
let newP = MapPath(p, localVariables, true, true)
where newP != null
select newP).ToArray();
localConfig.Assemblies.TranslateAdditional.Clear();
localConfig.Assemblies.TranslateAdditional.AddRange(newAdditionalTranslate);
foreach (var analyzer in analyzers.Values)
{
Dictionary<string, object> settings = null;
localConfig.AnalyzerSettings.TryGetValue(analyzer.SettingsKey, out settings);
analyzer.SetConfiguration(settings);
}
var emitterFactories = emitterFactoryCreators.ToDictionary(item => item.Key, item => item.Value());
emitterFactories[typeof(JavascriptEmitterGroupFactory).Name] = new JavascriptEmitterGroupFactory();
emitterFactories[typeof(DefinitelyTypedEmitterGroupFactory).Name] = new DefinitelyTypedEmitterGroupFactory();
buildGroup.Profile.RegisterPostprocessors(emitterFactories.Values, localConfig, filename, buildGroup.SkippedAssemblies);
using (var translator = CreateTranslator(
localConfig, manifest, assemblyCache, emitterFactories, analyzers
)) {
var ignoredMethods = new List<KeyValuePair<string, string[]>>();
translator.IgnoredMethod += (methodName, variableNames) =>
ignoredMethods.Add(new KeyValuePair<string, string[]>(methodName, variableNames));
var outputs = buildGroup.Profile.Translate(localVariables, translator, localConfig, filename, localConfig.UseLocalProxies.GetValueOrDefault(true));
if (localConfig.OutputDirectory == null)
throw new Exception("No output directory was specified!");
localConfig.OutputDirectory = MapPath(localConfig.OutputDirectory, localVariables, false);
CopiedOutputGatherer.EnsureDirectoryExists(localConfig.OutputDirectory);
InformationWriteLine("// Saving output to '{0}'.", ShortenPath(localConfig.OutputDirectory) + Path.DirectorySeparatorChar);
if (!string.IsNullOrEmpty(localConfig.JsLibrariesOutputDirectory))
{
localConfig.JsLibrariesOutputDirectory = MapPath(localConfig.JsLibrariesOutputDirectory, localVariables, false);
CopiedOutputGatherer.EnsureDirectoryExists(localConfig.JsLibrariesOutputDirectory);
}
// Ensures that the log file contains the name of the profile that was actually used.
localConfig.Profile = localProfile.GetType().Name;
if (ignoredMethods.Count > 0)
Console.Error.WriteLine("// {0} method(s) were ignored during translation. See the log for a list.", ignoredMethods.Count);
EmitLog(localConfig.OutputDirectory, localConfig, filename, outputs, ignoredMethods);
buildGroup.Profile.WriteOutputs(localVariables, outputs, localConfig, Quiet);
totalFailureCount += translator.Failures.Count;
}
}
}
if (Environment.UserInteractive && Debugger.IsAttached) {
Console.Error.WriteLine("// Press the any key to continue.");
Console.ReadKey();
}
Environment.ExitCode = totalFailureCount;
}
static void EmitLog (
string logPath, Configuration configuration,
string inputFile, TranslationResultCollection outputs,
IEnumerable<KeyValuePair<string, string[]>> ignoredMethods
) {
var logText = new StringBuilder();
var asmName = Assembly.GetExecutingAssembly().GetName();
logText.AppendLine(String.Format("// JSILc v{0}.{1}.{2}", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision));
logText.AppendLine(String.Format("// Build took {0:0000.00} second(s).", outputs.Elapsed.TotalSeconds));
logText.AppendLine(String.Format("// The following configuration was used when translating '{0}':", inputFile));
logText.AppendLine((new JavaScriptSerializer()).Serialize(configuration));
logText.AppendLine("// The configuration was generated from the following configuration files:");
foreach (var cf in configuration.ContributingPaths)
logText.AppendLine(cf);
logText.AppendLine("// The following outputs were produced:");
foreach (var translationResult in outputs.TranslationResults) {
foreach (var fe in translationResult.OrderedFiles)
logText.AppendLine(fe.Filename);
}
logText.AppendLine("// The following method(s) were ignored due to untranslatable variables:");
foreach (var im in ignoredMethods)
logText.AppendFormat("{0} because of {1}{2}", im.Key, String.Join(", ", im.Value), Environment.NewLine);
logText.AppendLine("// Miscellaneous log output follows:");
logText.AppendLine(outputs.Log.ToString());
File.WriteAllText(
Path.Combine(logPath, String.Format("{0}.jsillog", Path.GetFileName(inputFile))),
logText.ToString()
);
}
public static void InformationWriteLine (string text, params object[] values) {
if (Quiet)
return;
Console.Error.WriteLine(text, values);
}
}
}