Пример #1
0
        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);
        }
Пример #2
0
        public string RunJavascript(string[] args, out string generatedJavascript, out long elapsedTranslation, out long elapsedJs)
        {
            var tempFilename = Path.GetTempFileName();
            var translator = new JSIL.AssemblyTranslator(TypeInfo) {
                IncludeDependencies = false
            };

            if (StubbedAssemblies != null)
                translator.StubbedAssemblies.AddRange(StubbedAssemblies);

            string translatedJs;
            var translationStarted = DateTime.UtcNow.Ticks;
            using (var ms = new MemoryStream()) {
                var assemblies = translator.Translate(
                    GetPathOfAssembly(Assembly), ms,
                    TypeInfo == null
                );
                translatedJs = Encoding.ASCII.GetString(ms.GetBuffer(), 0, (int)ms.Length);

                // 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) {
                    Assert.AreEqual(1, assemblies.Length);
                    TypeInfo.Remove(assemblies);
                }
            }
            elapsedTranslation = DateTime.UtcNow.Ticks - translationStarted;

            var declaringType = JSIL.Internal.Util.EscapeIdentifier(TestMethod.DeclaringType.FullName, Internal.EscapingMode.TypeIdentifier);

            string argsJson;
            var jsonSerializer = new DataContractJsonSerializer(typeof(string[]));
            using (var ms2 = new MemoryStream()) {
                jsonSerializer.WriteObject(ms2, args);
                argsJson = Encoding.UTF8.GetString(ms2.GetBuffer(), 0, (int)ms2.Length);
            }

            var invocationJs = String.Format(
                @"timeout({0}); JSIL.Initialize(); JSIL.Host.warnedAboutRunLater = true; var started = elapsed(); {1}.Main({2}); var ended = elapsed(); print('// elapsed: ' + (ended - started));",
                JavascriptExecutionTimeout, declaringType, argsJson
            );

            generatedJavascript = translatedJs;

            File.WriteAllText(tempFilename, translatedJs + Environment.NewLine + invocationJs);

            try {
                // throw new Exception();

                var psi = new ProcessStartInfo(JSShellPath, String.Format("-w -j -m -f \"{0}\" -f \"{1}\" -f \"{2}\"", CoreJSPath, BootstrapJSPath, tempFilename)) {
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden
                };

                ManualResetEventSlim stdoutSignal, stderrSignal;
                stdoutSignal = new ManualResetEventSlim(false);
                stderrSignal = new ManualResetEventSlim(false);
                var output = new string[2];

                long startedJs = DateTime.UtcNow.Ticks;
                using (var process = Process.Start(psi)) {
                    ThreadPool.QueueUserWorkItem((_) => {
                        output[0] = process.StandardOutput.ReadToEnd();
                        stdoutSignal.Set();
                    });
                    ThreadPool.QueueUserWorkItem((_) => {
                        output[1] = process.StandardError.ReadToEnd();
                        stderrSignal.Set();
                    });

                    stdoutSignal.Wait();
                    stderrSignal.Wait();
                    process.WaitForExit();

                    if (process.ExitCode != 0)
                        throw new JavaScriptException(
                            process.ExitCode,
                            (output[0] ?? "").Trim(),
                            (output[1] ?? "").Trim()
                        );
                }

                long endedJs = DateTime.UtcNow.Ticks;
                elapsedJs = endedJs - startedJs;

                if (output[0] != null) {
                    var m = ElapsedRegex.Match(output[0]);
                    if (m.Success) {
                        elapsedJs = TimeSpan.FromMilliseconds(
                            double.Parse(m.Groups["elapsed"].Value)
                        ).Ticks;
                        output[0] = output[0].Replace(m.Value, "");
                    }
                }

                return output[0] ?? "";
            } finally {
                var jsFile = Filename.Replace(".cs", ".js");
                if (File.Exists(jsFile))
                    File.Delete(jsFile);
                File.Copy(tempFilename, jsFile);

                File.Delete(tempFilename);
            }
        }
Пример #3
0
        public TOutput Translate <TOutput> (
            Func <TranslationResult, TOutput> processResult,
            Func <Configuration> makeConfiguration  = null,
            Action <Exception> onTranslationFailure = 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, AssemblyCache)) {
                var assemblyPath = Util.GetPathOfAssembly(Assembly);
                TranslationResult translationResult = null;

                try {
                    translationResult = translator.Translate(
                        assemblyPath, TypeInfo == null
                        );

                    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(Assembly.FullName);
                    }
                }
            }

            return(result);
        }
Пример #4
0
        public string GenerateJavascript(
            string[] args, out string generatedJavascript, out long elapsedTranslation,
            Func <Configuration> makeConfiguration = null
            )
        {
            var           tempFilename = Path.GetTempFileName();
            Configuration configuration;

            if (makeConfiguration != null)
            {
                configuration = makeConfiguration();
            }
            else
            {
                configuration = MakeDefaultConfiguration();
            }

            if (StubbedAssemblies != null)
            {
                configuration.Assemblies.Stubbed.AddRange(StubbedAssemblies);
            }

            var translator = new JSIL.AssemblyTranslator(configuration, TypeInfo, null, AssemblyCache);

            string translatedJs;
            var    translationStarted = DateTime.UtcNow.Ticks;
            var    assemblyPath       = Util.GetPathOfAssembly(Assembly);

            translatedJs = null;
            try {
                var result = translator.Translate(
                    assemblyPath, TypeInfo == null
                    );

                AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result);
                translatedJs = result.WriteToString();

                // 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)
                {
                    Assert.AreEqual(1, result.Assemblies.Count);
                    TypeInfo.Remove(result.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(Assembly.FullName);
                }
            } finally {
                translator.Dispose();
            }

            elapsedTranslation = DateTime.UtcNow.Ticks - translationStarted;

            var testMethod    = GetTestMethod();
            var declaringType = JSIL.Internal.Util.EscapeIdentifier(
                testMethod.DeclaringType.FullName, Internal.EscapingMode.TypeIdentifier
                );

            string argsJson;

            if (MainAcceptsArguments.Value)
            {
                var jsonSerializer = new DataContractJsonSerializer(typeof(string[]));
                using (var ms2 = new MemoryStream()) {
                    jsonSerializer.WriteObject(ms2, args);
                    argsJson = Encoding.UTF8.GetString(ms2.GetBuffer(), 0, (int)ms2.Length);
                }
            }
            else
            {
                if ((args != null) && (args.Length > 0))
                {
                    throw new ArgumentException("Test case does not accept arguments");
                }

                argsJson = "";
            }

            var prefixJs =
                @"JSIL.SuppressInterfaceWarnings = true; ";

            var invocationJs = String.Format(
                @"if (typeof (timeout) !== 'function') timeout = function () {{}};" +
                @"if (typeof (elapsed) !== 'function') {{ if (typeof (Date) === 'object') elapsed = Date.now; else elapsed = function () {{ return 0; }} }}" +
                @"timeout({0});" +
                @"JSIL.Initialize(); var started = elapsed(); " +
                @"JSIL.GetAssembly({1}).{2}.{3}({4}); " +
                @"var ended = elapsed(); print('// elapsed: ' + (ended - started));",
                JavascriptExecutionTimeout,
                Util.EscapeString(testMethod.Module.Assembly.FullName),
                declaringType, Util.EscapeIdentifier(testMethod.Name),
                argsJson
                );

            generatedJavascript = translatedJs;

            File.WriteAllText(tempFilename, prefixJs + Environment.NewLine + translatedJs + Environment.NewLine + invocationJs);

            var jsFile = OutputPath;

            if (File.Exists(jsFile))
            {
                File.Delete(jsFile);
            }
            File.Copy(tempFilename, jsFile);

            File.Delete(tempFilename);

            return(OutputPath);
        }
Пример #5
0
        public string GenerateJavascript(
            string[] args, out string generatedJavascript, out long elapsedTranslation
        )
        {
            var tempFilename = Path.GetTempFileName();
            var configuration = MakeDefaultConfiguration();

            if (StubbedAssemblies != null)
                configuration.Assemblies.Stubbed.AddRange(StubbedAssemblies);

            var translator = new JSIL.AssemblyTranslator(configuration, TypeInfo, null, AssemblyCache);

            string translatedJs;
            var translationStarted = DateTime.UtcNow.Ticks;
            var assemblyPath = Util.GetPathOfAssembly(Assembly);
            translatedJs = null;
            try {
                var result = translator.Translate(
                    assemblyPath, TypeInfo == null
                );

                AssemblyTranslator.GenerateManifest(translator.Manifest, assemblyPath, result);
                translatedJs = result.WriteToString();

                // 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) {
                    Assert.AreEqual(1, result.Assemblies.Count);
                    TypeInfo.Remove(result.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(Assembly.FullName);
                }
            } finally {
                translator.Dispose();
            }

            elapsedTranslation = DateTime.UtcNow.Ticks - translationStarted;

            var testMethod = GetTestMethod();
            var declaringType = JSIL.Internal.Util.EscapeIdentifier(testMethod.DeclaringType.FullName, Internal.EscapingMode.TypeIdentifier);

            string argsJson;
            var jsonSerializer = new DataContractJsonSerializer(typeof(string[]));
            using (var ms2 = new MemoryStream()) {
                jsonSerializer.WriteObject(ms2, args);
                argsJson = Encoding.UTF8.GetString(ms2.GetBuffer(), 0, (int)ms2.Length);
            }

            var prefixJs =
                @"JSIL.SuppressInterfaceWarnings = true; ";

            var invocationJs = String.Format(
                @"timeout({0}); " +
                @"JSIL.Initialize(); var started = elapsed(); " +
                @"{1}.Main({2}); " +
                @"var ended = elapsed(); print('// elapsed: ' + (ended - started));",
                JavascriptExecutionTimeout, declaringType, argsJson
            );

            generatedJavascript = translatedJs;

            File.WriteAllText(tempFilename, prefixJs + Environment.NewLine + translatedJs + Environment.NewLine + invocationJs);

            var jsFile = OutputPath;
            if (File.Exists(jsFile))
                File.Delete(jsFile);
            File.Copy(tempFilename, jsFile);

            File.Delete(tempFilename);

            return OutputPath;
        }