Exemplo n.º 1
0
Arquivo: Base.cs Projeto: xen2/JSIL
        public virtual TranslationResult Translate(AssemblyTranslator translator, string assemblyPath, bool scanForProxies)
        {
            var result = translator.Translate(assemblyPath, scanForProxies);

            AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result);
            return(result);
        }
Exemplo n.º 2
0
        public virtual TranslationResult Translate(AssemblyTranslator translator, string assemblyPath, bool scanForProxies)
        {
            var result = translator.Translate(assemblyPath, scanForProxies);

            AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result);
            return result;
        }
Exemplo n.º 3
0
        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);
            }
        }
Exemplo n.º 4
0
Arquivo: Base.cs Projeto: Don191/JSIL
        public virtual TranslationResult Translate (
            VariableSet variables, AssemblyTranslator translator, Configuration configuration, 
            string assemblyPath, bool scanForProxies
        ) {
            var result = translator.Translate(assemblyPath, scanForProxies);

            return result;
        }
Exemplo n.º 5
0
Arquivo: Base.cs Projeto: ilmsg/JSIL
        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);
        }
Exemplo n.º 6
0
        public virtual TranslationResultCollection Translate(
            VariableSet variables, AssemblyTranslator translator, Configuration configuration,
            string assemblyPath, bool scanForProxies
            )
        {
            var result = translator.Translate(assemblyPath, scanForProxies);

            return(result);
        }
Exemplo n.º 7
0
        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;
        }
Exemplo n.º 8
0
        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);
        }
Exemplo n.º 9
0
        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;
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        public virtual TranslationResult Translate(
            AssemblyTranslator translator,
            Configuration configuration,
            string assemblyPath,
            bool scanForProxies
            )
        {
            var result = translator.Translate(assemblyPath, scanForProxies);

            ProcessSkippedAssembly(configuration, assemblyPath, result);

            return(result);
        }
Exemplo n.º 12
0
        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;
        }
Exemplo n.º 13
0
        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;
        }
Exemplo n.º 14
0
        public virtual TranslationResult Translate(
            AssemblyTranslator translator, 
            Configuration configuration, 
            string assemblyPath, 
            bool scanForProxies
        )
        {
            var result = translator.Translate(assemblyPath, scanForProxies);

            ProcessSkippedAssembly(configuration, assemblyPath, result);

            return result;
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        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);
        }
Exemplo n.º 17
0
        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;
        }
Exemplo n.º 18
0
        /// <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);
                }
            }
        }
Exemplo n.º 19
0
        public CompileResult Compile()
        {
            var loader = new AssemblyLoader(settings);

            using (var ctx = loader.Load())
            {
                var asms = ctx.Assemblies;

                var outputNames = new List <string>();

                if (settings.OutputFileName != null)
                {
                    outputNames.Add(settings.OutputFileName);

                    // SINGLE FILE MODE

                    File.Delete(settings.OutputFileName);

                    if (settings.OutputRuntimeJs)
                    {
                        File.AppendAllText(settings.OutputFileName, GetRuntimeJs());
                    }
                }
                else if (settings.OutputRuntimeJs)
                {
                    WriteRuntimeJs();
                }

                var staticAnalyzer = new StaticAnalyzer(ctx);

                foreach (var asm in asms)
                {
                    if (!asm.Settings.Translate)
                    {
                        continue;
                    }

                    staticAnalyzer.Analyze(asm);
                }

                var translator = new AssemblyTranslator(ctx);

                foreach (var asm in asms)
                {
                    if (!asm.Settings.Translate)
                    {
                        continue;
                    }

                    var asmExpression = translator.Translate(asms, asm);

                    string outputFileName;

                    if (settings.OutputFileName != null)
                    {
                        outputFileName = settings.OutputFileName;
                    }
                    else
                    {
                        outputFileName = asm.ReflectionAssembly.GetName().Name + ".js";
                        File.Delete(outputFileName);

                        outputNames.Add(outputFileName);
                    }

                    File.AppendAllText(outputFileName,
                                       "var " + asm.Identifier + "; (" +
                                       asmExpression.ToString() + ")(" + asm.Identifier + " || (" +
                                       asm.Identifier + " = {}));" + Environment.NewLine);
                }

                var entrypointAssembly = ctx
                                         .Assemblies
                                         .FirstOrDefault(a => a.EntryPoint != null);

                if (settings.OutputHtmlRunner)
                {
                    if (entrypointAssembly == null)
                    {
                        Console.WriteLine("No entry point found for HTML runner");
                    }
                    else
                    {
                        File.Delete(settings.OutputFileName + ".html");

                        File.AppendAllText(
                            settings.OutputFileName + ".html",
                            @"
<html>
    <head>
        <title>" + entrypointAssembly.Name + @"</title>
        " + string.Join(@"
        ", outputNames.Select(o => @"<script src=""" + o + @"""></script>")) + @"
        <script>
            " + entrypointAssembly.Identifier + @".entryPoint();
        </script>
    </head>
    <body>
    </body>
</html>
".Trim());
                    }
                }

                return(new CompileResult
                {
                    OutputFileName = settings.OutputFileName,
                    EntryPointAssembly = entrypointAssembly == null ? null : entrypointAssembly.Identifier
                });
            }
        }
Exemplo n.º 20
0
        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;
                }
            }
        }
Exemplo n.º 21
0
        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);
        }
Exemplo n.º 22
0
        /// <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);
                }
            }
        }