public void EnumeratesAssemblyDependencies () { var cr = CompilerUtil.Compile(new[] { Path.Combine( ComparisonTest.TestSourceFolder, @"SpecialTestCases", "EnumeratesAssemblyDependencies.cs" ) }, Path.Combine("DependencyTests", "EnumeratesAssemblyDependencies"), "", ComparisonTest.CurrentMetaRevision); var assembly = cr.Assembly; var translator = new AssemblyTranslator( new Translator.Configuration { IncludeDependencies = false } ); var assemblyDefinition = translator.LoadAssembly(assembly.Location); translator = new AssemblyTranslator( new Translator.Configuration { IncludeDependencies = true } ); var assemblyPlusDependencies = translator.LoadAssembly(assembly.Location); Assert.AreNotEqual( (from ad in assemblyDefinition select ad.FullName).ToArray(), (from ad in assemblyPlusDependencies select ad.FullName).ToArray() ); }
static AssemblyTranslator CreateTranslator( Configuration configuration, AssemblyManifest manifest, AssemblyCache assemblyCache ) { TypeInfoProvider typeInfoProvider = null; Console.Error.WriteLine( "// Using .NET framework {0} in {1} GC mode. Tuned GC {2}.", Environment.Version.ToString(), System.Runtime.GCSettings.IsServerGC ? "server" : "workstation", #if TARGETTING_FX_4_5 configuration.TuneGarbageCollection.GetValueOrDefault(true) ? "enabled" : "disabled" #else "disabled (must be built in .NET 4.5 mode)" #endif ); if ( configuration.ReuseTypeInfoAcrossAssemblies.GetValueOrDefault(true) && (CachedTypeInfoProvider != null) ) { if (CachedTypeInfoProviderConfiguration.Assemblies.Equals(configuration.Assemblies)) { typeInfoProvider = CachedTypeInfoProvider; } } var translator = new AssemblyTranslator( configuration, typeInfoProvider, manifest, assemblyCache, onProxyAssemblyLoaded: (name, classification) => Console.Error.WriteLine("// Loaded proxies from '{0}'", ShortenPath(name)) ); translator.Decompiling += MakeProgressHandler("Decompiling "); translator.RunningTransforms += MakeProgressHandler("Translating "); translator.Writing += MakeProgressHandler("Writing JS "); translator.AssemblyLoaded += (fn, classification) => Console.Error.WriteLine("// 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 (typeInfoProvider == null) { if (CachedTypeInfoProvider != null) { CachedTypeInfoProvider.Dispose(); } CachedTypeInfoProvider = translator.GetTypeInfoProvider(); CachedTypeInfoProviderConfiguration = configuration; } return(translator); }
public virtual TranslationResult Translate(AssemblyTranslator translator, string assemblyPath, bool scanForProxies) { var result = translator.Translate(assemblyPath, scanForProxies); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return(result); }
static void ParseOption(AssemblyTranslator translator, string option) { var m = Regex.Match(option, "-(-?)(?'key'[a-zA-Z]*)([=:](?'value'.*))?", RegexOptions.ExplicitCapture); if (m.Success) { switch (m.Groups["key"].Value) { case "out": case "o": translator.OutputDirectory = Path.GetFullPath(m.Groups["value"].Value); break; case "nodeps": case "nd": translator.IncludeDependencies = false; break; case "ignore": case "i": translator.IgnoredAssemblies.Add(new Regex(m.Groups["value"].Value, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture)); break; case "stub": case "s": translator.StubbedAssemblies.Add(new Regex(m.Groups["value"].Value, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture)); break; case "proxy": case "p": translator.AddProxyAssembly(Path.GetFullPath(m.Groups["value"].Value), false); break; } } }
public void Analyze (AssemblyTranslator translator, AssemblyDefinition[] assemblies, TypeInfoProvider typeInfoProvider) { if (!Configuration.DeadCodeElimination) return; assemblyDefinitions.Clear(); assemblyDefinitions.AddRange(assemblies); deadCodeInfo.TypeInfoProvider = typeInfoProvider; stopwatchElapsed = new Stopwatch(); stopwatchElapsed.Start(); var foundEntrypoints = from assembly in assemblyDefinitions from modules in assembly.Modules where modules.EntryPoint != null select modules.EntryPoint; deadCodeInfo.AddAssemblies(assemblyDefinitions); foreach (MethodDefinition method in foundEntrypoints) { deadCodeInfo.WalkMethod(method); } deadCodeInfo.FinishProcessing(); stopwatchElapsed.Stop(); Console.WriteLine("// Dead code analysis took {0} ms", stopwatchElapsed.ElapsedMilliseconds); }
public void Analyze(AssemblyTranslator translator, AssemblyDefinition[] assemblies, TypeInfoProvider typeInfoProvider) { if (!Configuration.DeadCodeElimination) { return; } assemblyDefinitions.Clear(); assemblyDefinitions.AddRange(assemblies); deadCodeInfo.TypeInfoProvider = typeInfoProvider; stopwatchElapsed = new Stopwatch(); stopwatchElapsed.Start(); var foundEntrypoints = from assembly in assemblyDefinitions from modules in assembly.Modules where modules.EntryPoint != null select modules.EntryPoint; deadCodeInfo.AddAssemblies(assemblyDefinitions); foreach (MethodDefinition method in foundEntrypoints) { deadCodeInfo.WalkMethod(method); } deadCodeInfo.FinishProcessing(); stopwatchElapsed.Stop(); Console.WriteLine("// Dead code analysis took {0} ms", stopwatchElapsed.ElapsedMilliseconds); }
public void EnumeratesAssemblyDependencies() { var assembly = CompilerUtil.CompileCS(new[] { Path.Combine( ComparisonTest.TestSourceFolder, @"SpecialTestCases\EnumeratesAssemblyDependencies.cs" ) }, "DependencyTests\\EnumeratesAssemblyDependencies"); var translator = new AssemblyTranslator( new Translator.Configuration { IncludeDependencies = false } ); var assemblyDefinition = translator.LoadAssembly(assembly.Location); translator = new AssemblyTranslator( new Translator.Configuration { IncludeDependencies = true } ); var assemblyPlusDependencies = translator.LoadAssembly(assembly.Location); Assert.AreNotEqual( (from ad in assemblyDefinition select ad.FullName).ToArray(), (from ad in assemblyPlusDependencies select ad.FullName).ToArray() ); }
public virtual TranslationResult Translate(AssemblyTranslator translator, string assemblyPath, bool scanForProxies) { var result = translator.Translate(assemblyPath, scanForProxies); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return result; }
public void EmitHeader(bool stubbed) { Formatter.Comment(AssemblyTranslator.GetHeaderText()); Formatter.NewLine(); Formatter.WriteRaw("'use strict';"); Formatter.NewLine(); if (stubbed) { Formatter.Comment("Generating type stubs only"); Formatter.NewLine(); } if (_referenceOverrides != null) { Formatter.LPar(); Formatter.OpenFunction(string.Empty, null); } Formatter.DeclareAssembly(); Formatter.NewLine(); if (_referenceOverrides != null) { Formatter.WriteReferencesOverrides(_referenceOverrides); } }
static void Main(string[] arguments) { var translator = new AssemblyTranslator(); translator.StartedLoadingAssembly += (fn) => { Console.Error.WriteLine("// Loading {0}...", fn); }; translator.StartedDecompilingAssembly += (fn, s) => { if (s) Console.Error.WriteLine("// Generating stub for {0}...", fn); else Console.Error.WriteLine("// Translating {0}...", fn); }; translator.CouldNotLoadSymbols += (fn, ex) => { Console.Error.WriteLine("// Could not load symbols for module {0}: {1}", fn, ex.Message); }; 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.Message); }; translator.StartedDecompilingMethod += (fn) => { Console.Error.Write("// Decompiling {0}... ", fn); }; translator.FinishedDecompilingMethod += (fn) => { Console.Error.WriteLine("done."); }; var filenames = new HashSet<string>(arguments); foreach (var filename in arguments) { if (filename.StartsWith("-")) { filenames.Remove(filename); ParseOption(translator, filename); } } 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("Usage: JSILc [options] assembly [assembly]"); Console.WriteLine("Options:"); Console.WriteLine("--out:<folder>"); Console.WriteLine(" Specifies the directory into which the generated javascript should be written."); Console.WriteLine("--proxy:<assembly>"); Console.WriteLine(" Specifies the location of a proxy assembly that contains type information for other assemblies."); Console.WriteLine("--nodeps"); Console.WriteLine(" Disables translating dependencies."); Console.WriteLine("--ignore:<regex>"); Console.WriteLine(" Specifies a regular expression filter used to ignore certain dependencies."); Console.WriteLine("--stub:<regex>"); Console.WriteLine(" Specifies a regular expression filter used to specify that certain dependencies should only be generated as stubs."); return; } foreach (var filename in filenames) { translator.Translate(filename); } }
public virtual TranslationResult Translate(VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies) { var result = translator.Translate(assemblyPath, scanForProxies); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return(result); }
public JavascriptAssemblyEmitter( AssemblyTranslator assemblyTranslator, JavascriptFormatter formatter ) { Translator = assemblyTranslator; Formatter = formatter; }
public virtual TranslationResult Translate ( VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); return result; }
public virtual TranslationResultCollection Translate( VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); return(result); }
static void ApplyDefaults(AssemblyTranslator translator) { Console.Error.WriteLine("// Applying default settings. To suppress, use --nodefaults."); translator.StubbedAssemblies.Add(new Regex(@"mscorlib,")); translator.StubbedAssemblies.Add(new Regex(@"System.*")); translator.StubbedAssemblies.Add(new Regex(@"Microsoft.*")); translator.StubbedAssemblies.Add(new Regex(@"Accessibility,")); }
public bool ShouldSkipMember(AssemblyTranslator translator, MemberReference member) { if (!Configuration.DeadCodeElimination) { return(false); } return(!deadCodeInfo.IsUsed(member)); }
public virtual TranslationResult Translate(AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies) { var result = translator.Translate(assemblyPath, scanForProxies); ResourceConverter.ConvertResources(configuration, assemblyPath, result); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return(result); }
public JavascriptAssemblyEmitter( AssemblyTranslator assemblyTranslator, JavascriptFormatter formatter, IDictionary <AssemblyManifest.Token, string> referenceOverrides ) { Translator = assemblyTranslator; Formatter = formatter; _referenceOverrides = referenceOverrides; }
public virtual TranslationResult Translate(AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies) { var result = translator.Translate(assemblyPath, scanForProxies); ResourceConverter.ConvertResources(configuration, assemblyPath, result); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return result; }
public IAssemblyEmitter MakeAssemblyEmitter(AssemblyTranslator translator, AssemblyDefinition assembly, JavascriptFormatter formatter) { if (translator.IsStubbed(assembly) || translator.IsIgnored(assembly)) { return(new NullAssemblyEmitter()); } else { return(new WasmSExprAssemblyEmitter(translator, assembly, formatter)); } }
bool IAnalyzer.ShouldSkipMember(AssemblyTranslator translator, MemberReference member) { var result = ShouldSkipMember(member); if (result.Item1) { Warn(translator, member, result.Item2); } return(result.Item1); }
public override TranslationResult Translate(AssemblyTranslator translator, string assemblyPath, bool scanForProxies) { var result = translator.Translate(assemblyPath, scanForProxies); result.AddFile("XNA.Colors.js", new ArraySegment <byte>(Encoding.UTF8.GetBytes( Common.MakeXNAColors() )), 0); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return(result); }
public override TranslationResult Translate(AssemblyTranslator translator, string assemblyPath, bool scanForProxies) { var result = translator.Translate(assemblyPath, scanForProxies); result.AddFile("XNA.Colors.js", new ArraySegment<byte>(Encoding.UTF8.GetBytes( Common.MakeXNAColors() )), 0); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return result; }
static AssemblyTranslator CreateTranslator( Configuration configuration, AssemblyManifest manifest, AssemblyCache assemblyCache ) { TypeInfoProvider typeInfoProvider = null; if ( configuration.ReuseTypeInfoAcrossAssemblies.GetValueOrDefault(true) && (CachedTypeInfoProvider != null) ) { if (CachedTypeInfoProviderConfiguration.Assemblies.Equals(configuration.Assemblies)) { typeInfoProvider = CachedTypeInfoProvider; } } var translator = new AssemblyTranslator( configuration, typeInfoProvider, manifest, assemblyCache, onProxyAssemblyLoaded: (name, classification) => { Console.Error.WriteLine("// Loaded proxies from '{0}'", ShortenPath(name)); } ); translator.Decompiling += MakeProgressHandler("Decompiling "); translator.RunningTransforms += MakeProgressHandler("Translating "); translator.Writing += MakeProgressHandler("Writing JS "); translator.AssemblyLoaded += (fn, classification) => { Console.Error.WriteLine("// 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.Message); }; if (typeInfoProvider == null) { if (CachedTypeInfoProvider != null) { CachedTypeInfoProvider.Dispose(); } CachedTypeInfoProvider = translator.GetTypeInfoProvider(); CachedTypeInfoProviderConfiguration = configuration; } return(translator); }
public virtual TranslationResult Translate( AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); ProcessSkippedAssembly(configuration, assemblyPath, result); return result; }
public virtual TranslationResult Translate( AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); ProcessSkippedAssembly(configuration, assemblyPath, result); return(result); }
public override TranslationResult Translate ( VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); PostProcessAllTranslatedAssemblies(configuration, assemblyPath, result); return result; }
public override TranslationResult Translate ( VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); PostProcessAllTranslatedAssemblies(configuration, assemblyPath, result); result.AddFile("Script", "XNA.Colors.js", new ArraySegment<byte>(Encoding.UTF8.GetBytes( Common.MakeXNAColors() )), 0); return result; }
public virtual void WriteOutputs(VariableSet variables, TranslationResult result, string path, string manifestPrefix) { AssemblyTranslator.GenerateManifest(result.AssemblyManifest, result.AssemblyPath, result); Console.WriteLine(manifestPrefix + "manifest.js"); foreach (var fe in result.OrderedFiles) { Console.WriteLine(fe.Filename); } result.WriteToDirectory(path, manifestPrefix); }
public override TranslationResult Translate( VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); PostProcessAllTranslatedAssemblies(configuration, assemblyPath, result); result.AddFile("Script", "XNA.Colors.js", new ArraySegment <byte>(Encoding.UTF8.GetBytes( Common.MakeXNAColors() )), 0); return(result); }
public override TranslationResult Translate( VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); PostProcessAllTranslatedAssemblies(configuration, assemblyPath, result); return(result); }
private void Warn(AssemblyTranslator translator, MemberReference member, string reason) { if (ShouldSilence(translator, member)) { return; } if (PreviousWarnings.Contains(member.FullName)) { return; } PreviousWarnings.Add(member.FullName); Console.WriteLine("// Skipping {0}: {1}", member.Name, reason); }
public IAssemblyEmitter MakeAssemblyEmitter( AssemblyTranslator translator, AssemblyDefinition assembly, JavascriptFormatter formatter, IDictionary <AssemblyManifest.Token, string> referenceOverrides ) { if (translator.IsStubbed(assembly) || translator.IsIgnored(assembly)) { return(new NullAssemblyEmitter()); } else { return(new WasmSExprAssemblyEmitter(translator, assembly, formatter)); } }
public override TranslationResult Translate( VariableSet variables, AssemblyTranslator translator, Configuration configuration, string assemblyPath, bool scanForProxies ) { var result = translator.Translate(assemblyPath, scanForProxies); ResourceConverter.ConvertEmbeddedResources(configuration, assemblyPath, result); result.AddFile("Script", "XNA.Colors.js", new ArraySegment<byte>(Encoding.UTF8.GetBytes( Common.MakeXNAColors() )), 0); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result); return result; }
static AssemblyTranslator CreateTranslator( Configuration configuration, AssemblyManifest manifest, AssemblyCache assemblyCache ) { TypeInfoProvider typeInfoProvider = null; if ( configuration.ReuseTypeInfoAcrossAssemblies.GetValueOrDefault(true) && (CachedTypeInfoProvider != null) ) { if (CachedTypeInfoProviderConfiguration.Assemblies.Equals(configuration.Assemblies)) typeInfoProvider = CachedTypeInfoProvider; } var translator = new AssemblyTranslator( configuration, typeInfoProvider, manifest, assemblyCache, onProxyAssemblyLoaded: (name) => { Console.Error.WriteLine("// Loaded proxies from '{0}'", ShortenPath(name)); } ); translator.Decompiling += MakeProgressHandler ("Decompiling "); translator.RunningTransforms += MakeProgressHandler ("Translating "); translator.Writing += MakeProgressHandler ("Writing JS "); translator.AssemblyLoaded += (fn) => { Console.Error.WriteLine("// Loaded {0}", ShortenPath(fn)); }; 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.Message); }; if (typeInfoProvider == null) { if (CachedTypeInfoProvider != null) CachedTypeInfoProvider.Dispose(); CachedTypeInfoProvider = translator.GetTypeInfoProvider(); CachedTypeInfoProviderConfiguration = configuration; } return translator; }
public void EmitHeader(bool stubbed) { Formatter.Comment(AssemblyTranslator.GetHeaderText()); Formatter.NewLine(); Formatter.WriteRaw("'use strict';"); Formatter.NewLine(); if (stubbed) { Formatter.Comment("Generating type stubs only"); Formatter.NewLine(); } Formatter.DeclareAssembly(); Formatter.NewLine(); }
private bool ShouldSilence(AssemblyTranslator translator, MemberReference member) { var typeInfo = translator.TypeInfoProvider.GetTypeInformation(member.DeclaringType); if (typeInfo.IsIgnored || typeInfo.IsExternal) { return(true); } var asm = member.DeclaringType.Module.Assembly; if (translator.IsStubbed(asm) || translator.IsIgnored(asm)) { return(true); } return(false); }
static AssemblyTranslator CreateTranslator(Configuration configuration, AssemblyManifest manifest, AssemblyCache assemblyCache) { var translator = new AssemblyTranslator(configuration, null, manifest, assemblyCache); translator.Decompiling += MakeProgressHandler("Decompiling "); translator.Optimizing += MakeProgressHandler("Optimizing "); translator.Writing += MakeProgressHandler("Generating JS "); translator.AssemblyLoaded += (fn) => { Console.Error.WriteLine("// Loaded {0}", ShortenPath(fn)); }; 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.Message); }; return(translator); }
static AssemblyTranslator CreateTranslator(Configuration configuration, AssemblyManifest manifest, AssemblyCache assemblyCache) { var translator = new AssemblyTranslator(configuration, null, manifest, assemblyCache); translator.Decompiling += MakeProgressHandler("Decompiling "); translator.Optimizing += MakeProgressHandler ("Optimizing "); translator.Writing += MakeProgressHandler ("Generating JS "); translator.AssemblyLoaded += (fn) => { Console.Error.WriteLine("// Loaded {0}", ShortenPath(fn)); }; 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.Message); }; return translator; }
public void EnumeratesAssemblyDependencies() { TempFileCollection temporaryFiles; var assembly = CompilerUtil.CompileCS(@" using System; using System.Text.RegularExpressions; public static class Program { public static void Main () { var regex = new Regex(""[A-Za-z]*""); var text = ""Hello, World!""; var match = regex.Match(text); Console.WriteLine(""{0} {1}"", match.Success, match.Groups[0].Value); } }", out temporaryFiles); var translator = new AssemblyTranslator( new Translator.Configuration { IncludeDependencies = false } ); var assemblyDefinition = translator.LoadAssembly(assembly.Location); translator = new AssemblyTranslator( new Translator.Configuration { IncludeDependencies = true } ); var assemblyPlusDependencies = translator.LoadAssembly(assembly.Location); Assert.AreNotEqual( (from ad in assemblyDefinition select ad.FullName).ToArray(), (from ad in assemblyPlusDependencies select ad.FullName).ToArray() ); }
public FunctionTransformPipeline( AssemblyTranslator translator, QualifiedMemberIdentifier identifier, JSFunctionExpression function, SpecialIdentifiers si ) { Translator = translator; Identifier = identifier; Function = function; SpecialIdentifiers = si; FillPipeline(); if (!Translator.FunctionCache.ActiveTransformPipelines.TryAdd(Identifier, this)) { throw new ThreadStateException(); } if (CheckForStaticAnalysisChanges) { OriginalFunctionBody = Function.Body.ToString(); OriginalSecondPass = Translator.FunctionCache.GetSecondPass(function.Method, function.Method.QualifiedIdentifier); } }
/// <summary> /// Compiles the provided C# and then translates it into JavaScript. /// On success, returns the JS. On failure, throws. /// </summary> public static CompiledSnippet Compile(string csharp, bool deleteTempFiles) { var result = new CompiledSnippet { OriginalSource = csharp }; int tempDirId = Interlocked.Increment(ref NextTempDirId); var tempPath = Path.Combine(Path.GetTempPath(), "JSIL.Try", tempDirId.ToString()); if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); try { string resultPath, entryPointName, compilerOutput, resultFullName; long compileStarted = DateTime.UtcNow.Ticks; CompileAssembly( tempPath, csharp, out compilerOutput, out resultPath, out resultFullName, out entryPointName ); result.CompileElapsed = TimeSpan.FromTicks(DateTime.UtcNow.Ticks - compileStarted).TotalSeconds; if ((resultPath == null) || !File.Exists(resultPath)) { if (String.IsNullOrWhiteSpace(compilerOutput)) throw new Exception("Compile failed with unknown error."); else throw new Exception(compilerOutput); } var translatorConfiguration = new Configuration { ApplyDefaults = false, Assemblies = { Stubbed = { "mscorlib,", "System.*", "Microsoft.*" }, Ignored = { "Microsoft.VisualC,", "Accessibility,", "SMDiagnostics,", "System.EnterpriseServices,", "JSIL.Meta," } }, FrameworkVersion = 4.0, GenerateSkeletonsForStubbedAssemblies = false, GenerateContentManifest = false, IncludeDependencies = false, UseSymbols = true, UseThreads = false }; var translatorOutput = new StringBuilder(); var typeInfo = CachedTypeInfo.Value; // Don't use a cached type provider if this snippet contains a proxy. bool disableCaching = csharp.Contains("JSProxy"); using (var translator = new AssemblyTranslator( translatorConfiguration, // Reuse the cached type info provider, if one exists. disableCaching ? null : typeInfo, // Can't reuse a manifest meaningfully here. null, // Reuse the assembly cache so that mscorlib doesn't get loaded every time. AssemblyCache )) { translator.CouldNotDecompileMethod += (s, exception) => { lock (translatorOutput) translatorOutput.AppendFormat( "Could not decompile method '{0}': {1}{2}", s, exception.Message, Environment.NewLine ); }; translator.CouldNotResolveAssembly += (s, exception) => { lock (translatorOutput) translatorOutput.AppendFormat( "Could not resolve assembly '{0}': {1}{2}", s, exception.Message, Environment.NewLine ); }; translator.Warning += (s) => { lock (translatorOutput) translatorOutput.AppendLine(s); }; var translateStarted = DateTime.UtcNow.Ticks; var translationResult = translator.Translate(resultPath, true); AssemblyTranslator.GenerateManifest( translator.Manifest, Path.GetDirectoryName(resultPath), translationResult ); result.EntryPoint = String.Format( "{0}.{1}", translator.Manifest.GetPrivateToken(resultFullName).IDString, entryPointName ); result.Warnings = translatorOutput.ToString().Trim(); result.TranslateElapsed = TimeSpan.FromTicks(DateTime.UtcNow.Ticks - translateStarted).TotalSeconds; result.JavaScript = translationResult.WriteToString(); if (typeInfo != null) { // Remove the temporary assembly from the type info provider. typeInfo.Remove(translationResult.Assemblies.ToArray()); } else if (!disableCaching) { // We didn't have a type info provider to reuse, so store the translator's. CachedTypeInfo.Value = typeInfo = translator.GetTypeInfoProvider(); } /* result.Warnings += String.Format( "{1} assemblies loaded{0}", Environment.NewLine, AppDomain.CurrentDomain.GetAssemblies().Length ); */ /* result.Warnings += String.Format( "TypeInfo.Count = {1}{0}AssemblyCache.Count = {2}{0}", Environment.NewLine, TypeInfo.Count, AssemblyCache.Count ); */ } /* GC.Collect(); result.Warnings += String.Format( "{1} byte(s) GC heap {0}", Environment.NewLine, GC.GetTotalMemory(true) ); */ return result; } finally { try { if (deleteTempFiles) Directory.Delete(tempPath, true); } catch (Exception exc) { Console.WriteLine("Failed to empty temporary directory: {0}", exc.Message); } } }
static void Main(string[] arguments) { var translator = new AssemblyTranslator(); translator.LoadingAssembly += (fn, progress) => { Console.Error.WriteLine("// Loading {0}...", fn); }; translator.Decompiling += (progress) => { Console.Error.Write("// Decompiling "); var previous = new int[1] { 0 }; progress.ProgressChanged += (s, p, max) => { var current = p * 20 / max; if (current != previous[0]) { previous[0] = current; Console.Error.Write("."); } }; progress.Finished += (s, e) => { Console.Error.WriteLine(" done"); }; }; translator.Optimizing += (progress) => { Console.Error.Write("// Optimizing "); var previous = new int[1] { 0 }; progress.ProgressChanged += (s, p, max) => { var current = p * 20 / max; if (current != previous[0]) { previous[0] = current; Console.Error.Write("."); } }; progress.Finished += (s, e) => { Console.Error.WriteLine(" done"); }; }; translator.Writing += (progress) => { Console.Error.Write("// Writing JS "); var previous = new int[1] { 0 }; progress.ProgressChanged += (s, p, max) => { var current = p * 20 / max; if (current != previous[0]) { previous[0] = current; Console.Error.Write("."); } }; progress.Finished += (s, e) => { Console.Error.WriteLine(" done"); }; }; translator.CouldNotLoadSymbols += (fn, ex) => { Console.Error.WriteLine("// {0}", ex.Message); }; 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.Message); }; var filenames = new HashSet<string>(arguments); bool includeDefaults = true; foreach (var filename in arguments) { if (filename.StartsWith("-")) { filenames.Remove(filename); if (filename == "--nodefaults") { includeDefaults = false; } else { ParseOption(translator, filename); } } } 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("Usage: JSILc [options] assembly [assembly]"); Console.WriteLine("Options:"); Console.WriteLine("--out:<folder>"); Console.WriteLine(" Specifies the directory into which the generated javascript should be written."); Console.WriteLine("--nodeps"); Console.WriteLine(" Disables translating dependencies."); Console.WriteLine("--nodefaults"); Console.WriteLine(" Disables the built-in default stub list. Use this if you actually want to translate huge Microsoft assemblies like mscorlib."); Console.WriteLine("--proxy:<assembly>"); Console.WriteLine(" Specifies the location of a proxy assembly that contains type information for other assemblies."); Console.WriteLine("--ignore:<regex>"); Console.WriteLine(" Specifies a regular expression filter used to ignore certain dependencies."); Console.WriteLine("--stub:<regex>"); Console.WriteLine(" Specifies a regular expression filter used to specify that certain dependencies should only be generated as stubs."); return; } if (includeDefaults) ApplyDefaults(translator); foreach (var filename in filenames) translator.Translate(filename); }
public bool ShouldSkipMember (AssemblyTranslator translator, MemberReference member) { if (!Configuration.DeadCodeElimination) return false; return !deadCodeInfo.IsUsed(member); }
public TOutput Translate <TOutput> ( Func <TranslationResult, TOutput> processResult, Func <Configuration> makeConfiguration = null, Action <Exception> onTranslationFailure = null, Action <AssemblyTranslator> initializeTranslator = null, bool?scanForProxies = null, IEnumerable <IAnalyzer> analyzers = null ) { Configuration configuration; if (makeConfiguration != null) { configuration = makeConfiguration(); } else { configuration = MakeDefaultConfiguration(); } configuration = ApplyMetacomments(configuration); if (StubbedAssemblies != null) { configuration.Assemblies.Stubbed.AddRange(StubbedAssemblies); } TOutput result; using (var translator = new JSIL.AssemblyTranslator( configuration, TypeInfo, null, assemblyDataResolver: new AssemblyDataResolver(configuration, AssemblyCache), analyzers: analyzers )) { if (initializeTranslator != null) { initializeTranslator(translator); } var assemblyPath = AssemblyUtility.AssemblyLocation; TranslationResult translationResult = null; try { translationResult = translator.Translate( assemblyPath, scanForProxies == null ? TypeInfo == null : (bool)scanForProxies ); AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, translationResult); result = processResult(translationResult); } finally { if (onTranslationFailure != null) { foreach (var failure in translator.Failures) { onTranslationFailure(failure); } } // If we're using a preconstructed type information provider, we need to remove the type information // from the assembly we just translated if ((TypeInfo != null) && (translationResult != null)) { Assert.AreEqual(1, translationResult.Assemblies.Count); TypeInfo.Remove(translationResult.Assemblies.ToArray()); } // If we're using a preconstructed assembly cache, make sure the test case assembly didn't get into // the cache, since that would leak memory. if (AssemblyCache != null) { AssemblyCache.TryRemove(AssemblyUtility.AssemblyFullName); } } } return(result); }
static void Main(string[] arguments) { var translator = new AssemblyTranslator(); translator.LoadingAssembly += (fn, progress) => { Console.Error.WriteLine("// Loading {0}. ", fn); }; translator.Decompiling += (progress) => { Console.Error.Write("// Decompiling "); var previous = new int[1] { 0 }; progress.ProgressChanged += (s, p, max) => { var current = p * 20 / max; if (current != previous[0]) { previous[0] = current; Console.Error.Write("."); } }; progress.Finished += (s, e) => { Console.Error.WriteLine(" done"); }; }; translator.Optimizing += (progress) => { Console.Error.Write("// Optimizing "); var previous = new int[1] { 0 }; progress.ProgressChanged += (s, p, max) => { var current = p * 20 / max; if (current != previous[0]) { previous[0] = current; Console.Error.Write("."); } }; progress.Finished += (s, e) => { Console.Error.WriteLine(" done"); }; }; translator.Writing += (progress) => { Console.Error.Write("// Writing JS "); var previous = new int[1] { 0 }; progress.ProgressChanged += (s, p, max) => { var current = p * 20 / max; if (current != previous[0]) { previous[0] = current; Console.Error.Write("."); } }; progress.Finished += (s, e) => { Console.Error.WriteLine(" done"); }; }; translator.CouldNotLoadSymbols += (fn, ex) => { Console.Error.WriteLine("// {0}", ex.Message); }; 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.Message); }; var filenames = new HashSet<string>(arguments); bool includeDefaults = true; foreach (var filename in arguments) { if (filename.StartsWith("-")) { filenames.Remove(filename); if (filename == "--nodefaults") { includeDefaults = false; } else { ParseOption(translator, filename); } } } 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("Usage: JSILc [options] ..."); 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("Options:"); Console.WriteLine("--out:<folder>"); Console.WriteLine(" Specifies the directory into which the generated javascript should be written."); Console.WriteLine("--nodeps"); Console.WriteLine(" Disables translating dependencies."); Console.WriteLine("--nodefaults"); Console.WriteLine(" Disables the built-in default stub list. Use this if you actually want to translate huge Microsoft assemblies like mscorlib."); Console.WriteLine("--oS"); Console.WriteLine(" Disables struct copy optimizations"); Console.WriteLine("--oO"); Console.WriteLine(" Disables operator optimizations"); Console.WriteLine("--oL"); Console.WriteLine(" Disables loop optimizations"); Console.WriteLine("--oT"); Console.WriteLine(" Disables temporary variable elimination"); Console.WriteLine("--proxy:<assembly>"); Console.WriteLine(" Specifies the location of a proxy assembly that contains type information for other assemblies."); Console.WriteLine("--ignore:<regex>"); Console.WriteLine(" Specifies a regular expression filter used to ignore certain dependencies."); Console.WriteLine("--stub:<regex>"); Console.WriteLine(" Specifies a regular expression filter used to specify that certain dependencies should only be generated as stubs."); return; } if (includeDefaults) ApplyDefaults(translator); while (filenames.Count > 0) { var filename = filenames.First(); filenames.Remove(filename); var extension = Path.GetExtension(filename); switch (extension.ToLower()) { case ".exe": case ".dll": translator.Translate(filename); break; case ".sln": foreach (var resultFilename in SolutionBuilder.Build(filename)) { filenames.Add(resultFilename); } break; default: Console.Error.WriteLine("// Don't know what to do with file '{0}'.", filename); break; } } }
public WasmSExprAssemblyEmitter(AssemblyTranslator translator, AssemblyDefinition assembly, JavascriptFormatter formatter) { Translator = translator; Assembly = assembly; Formatter = formatter; }
public void InitializeTransformPipeline(AssemblyTranslator translator, FunctionTransformPipeline transformPipeline) { }
static AssemblyTranslator CreateTranslator( Configuration configuration, AssemblyManifest manifest, AssemblyCache assemblyCache, Dictionary <string, IEmitterFactory> 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; } } IEmitterFactory emitterFactory = GetEmitterFactory(configuration, emitterFactories); var translator = new AssemblyTranslator( configuration, typeInfoProvider, manifest, new AssemblyDataResolver(configuration, assemblyCache), onProxyAssemblyLoaded: (name, classification) => InformationWriteLine("// Loaded proxies from '{0}'", ShortenPath(name)), emitterFactory: emitterFactory, analyzers: analyzers.Values ); 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); }
/// <summary> /// Compiles the provided C# and then translates it into JavaScript. /// On success, returns the JS. On failure, throws. /// </summary> public static CompiledSnippet Compile(string csharp, bool deleteTempFiles) { var result = new CompiledSnippet { OriginalSource = csharp }; int tempDirId = Interlocked.Increment(ref NextTempDirId); var tempPath = Path.Combine(Path.GetTempPath(), "JSIL.Try", tempDirId.ToString()); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } try { string resultPath, entryPointName, compilerOutput, resultFullName; long compileStarted = DateTime.UtcNow.Ticks; CompileAssembly( tempPath, csharp, out compilerOutput, out resultPath, out resultFullName, out entryPointName ); result.CompileElapsed = TimeSpan.FromTicks(DateTime.UtcNow.Ticks - compileStarted).TotalSeconds; if ((resultPath == null) || !File.Exists(resultPath)) { if (String.IsNullOrWhiteSpace(compilerOutput)) { throw new Exception("Compile failed with unknown error."); } else { throw new Exception(compilerOutput); } } var translatorConfiguration = new Configuration { ApplyDefaults = false, Assemblies = { Stubbed = { "mscorlib,", "System.*", "Microsoft.*" }, Ignored = { "Microsoft.VisualC,", "Accessibility,", "SMDiagnostics,", "System.EnterpriseServices,", "JSIL.Meta," } }, FrameworkVersion = 4.0, GenerateSkeletonsForStubbedAssemblies = false, GenerateContentManifest = false, IncludeDependencies = false, UseSymbols = true, UseThreads = false }; var translatorOutput = new StringBuilder(); var typeInfo = CachedTypeInfo.Value; // Don't use a cached type provider if this snippet contains a proxy. bool disableCaching = csharp.Contains("JSProxy"); using (var translator = new AssemblyTranslator( translatorConfiguration, // Reuse the cached type info provider, if one exists. disableCaching ? null : typeInfo, // Can't reuse a manifest meaningfully here. null, // Reuse the assembly cache so that mscorlib doesn't get loaded every time. AssemblyCache )) { translator.CouldNotDecompileMethod += (s, exception) => { lock (translatorOutput) translatorOutput.AppendFormat( "Could not decompile method '{0}': {1}{2}", s, exception.Message, Environment.NewLine ); }; translator.CouldNotResolveAssembly += (s, exception) => { lock (translatorOutput) translatorOutput.AppendFormat( "Could not resolve assembly '{0}': {1}{2}", s, exception.Message, Environment.NewLine ); }; translator.Warning += (s) => { lock (translatorOutput) translatorOutput.AppendLine(s); }; var translateStarted = DateTime.UtcNow.Ticks; var translationResult = translator.Translate(resultPath, true); AssemblyTranslator.GenerateManifest( translator.Manifest, Path.GetDirectoryName(resultPath), translationResult ); result.EntryPoint = String.Format( "{0}.{1}", translator.Manifest.GetPrivateToken(resultFullName).IDString, entryPointName ); result.Warnings = translatorOutput.ToString().Trim(); result.TranslateElapsed = TimeSpan.FromTicks(DateTime.UtcNow.Ticks - translateStarted).TotalSeconds; result.JavaScript = translationResult.WriteToString(); if (typeInfo != null) { // Remove the temporary assembly from the type info provider. typeInfo.Remove(translationResult.Assemblies.ToArray()); } else if (!disableCaching) { // We didn't have a type info provider to reuse, so store the translator's. CachedTypeInfo.Value = typeInfo = translator.GetTypeInfoProvider(); } /* * result.Warnings += String.Format( * "{1} assemblies loaded{0}", * Environment.NewLine, AppDomain.CurrentDomain.GetAssemblies().Length * ); */ /* * result.Warnings += String.Format( * "TypeInfo.Count = {1}{0}AssemblyCache.Count = {2}{0}", * Environment.NewLine, TypeInfo.Count, AssemblyCache.Count * ); */ } /* * * GC.Collect(); * * result.Warnings += String.Format( * "{1} byte(s) GC heap {0}", * Environment.NewLine, GC.GetTotalMemory(true) * ); */ return(result); } finally { try { if (deleteTempFiles) { Directory.Delete(tempPath, true); } } catch (Exception exc) { Console.WriteLine("Failed to empty temporary directory: {0}", exc.Message); } } }