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 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 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 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 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); ResourceConverter.ConvertResources(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); }
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); }
/// <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); } } }
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); }
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); }