public static string Decompile(DomCecilMethod method, bool markup)
        {
            if (method.MethodDefinition.IsPInvokeImpl)
            {
                return(GettextCatalog.GetString("Method is P/Invoke"));
            }
            if (method.MethodDefinition.Body == null)
            {
                IType type = method.DeclaringType;
                return(type == null ||  type.ClassType == ClassType.Interface ? GettextCatalog.GetString("Interface method") : GettextCatalog.GetString("Abstract method"));
            }

            StringBuilder result = new StringBuilder();

            try {
                //ControlFlowGraph controlFlowGraph = ControlFlowGraph.Create (method.MethodDefinition);
                ILanguage lang = CSharp.GetLanguage(CSharpVersion.V3);
                ColoredCSharpFormatter formatter  = new ColoredCSharpFormatter();
                ILanguageWriter        langWriter = lang.GetWriter(formatter);
                langWriter.Write(method.MethodDefinition);
                result.Append(formatter.Text);
            } catch (Exception e) {
                result.Append("Decompilation failed: \n" + e);
            }
            return(result.ToString());
        }
 public XmlDocLanguageWriter(ILanguage language, IDocumentationLoader docLoader, bool injectXmlDoc)
 {
     _language = language;
     _docLoader = docLoader;
     _injectXmlDoc = injectXmlDoc;
     _configuration = new LanguageConfiguration();
     _formatter = new TextFormatter();
     _writer = language.GetWriter(_formatter, _configuration);
 }
Beispiel #3
0
 public XmlDocLanguageWriter(ILanguage language, IDocumentationLoader docLoader, bool injectXmlDoc)
 {
     _language      = language;
     _docLoader     = docLoader;
     _injectXmlDoc  = injectXmlDoc;
     _configuration = new LanguageConfiguration();
     _formatter     = new TextFormatter();
     _writer        = language.GetWriter(_formatter, _configuration);
 }
        private string GetNamespacePerLanguage(ILanguage language, string @namespace)
        {
            var formatter = new PlainTextFormatter(new StringWriter());

            ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, true);

            writer.WriteNamespaceNavigationName(@namespace, true);

            return(formatter.ToString());
        }
        private string GetMemberNamePerLanguage(ILanguage language, TypeDefinition type)
        {
            var formatter = new PlainTextFormatter(new StringWriter());

            ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, true);

            writer.WriteMemberNavigationName(type, true);

            return(formatter.ToString());
        }
        public static string GetMemberEscapedOnlyNameForLanguage(object memberReference, ILanguage language)
        {
            var formatter = new PlainTextFormatter(new StringWriter());

            ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, GetWriterSettings());

            writer.WriteMemberEscapedOnlyName(memberReference);

            return(formatter.ToString());
        }
        public static string GetMemberNavigationPathName(object memberReference, ILanguage language)
        {
            var formatter = new PlainTextFormatter(new StringWriter());

            ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, false);

            writer.WriteMemberNavigationPathFullName(memberReference);

            return(formatter.ToString());
        }
        public static string GetMemberDeclartionForLanguage(object memberReference, ILanguage language, bool renameInvalidMembers)
        {
            var formatter = new PlainTextFormatter(new StringWriter());

            ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, false);

            writer.WriteMemberNavigationName(memberReference, renameInvalidMembers);

            return(formatter.ToString());
        }
        public static string GetNamespaceForLanguage(string @namespace, ILanguage language, bool renameInvalidMembers)
        {
            var formatter = new PlainTextFormatter(new StringWriter());

            ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, false);

            writer.WriteNamespaceNavigationName(@namespace, renameInvalidMembers);

            return(formatter.ToString());
        }
Beispiel #10
0
 protected virtual void WriteTypeInANewWriterIfNeeded(TypeDefinition type, bool writeDocumentation, bool showCompilerGeneratedMembers = false)
 {
     if (this.CurrentType != type)
     {
         ILanguageWriter    writer             = Language.GetWriter(this.formatter, this.exceptionFormatter, this.WriteExceptionsAsComments);
         List <WritingInfo> nestedWritingInfos = writer.Write(type, writerContextService, writeDocumentation, showCompilerGeneratedMembers);
         this.writingInfos.AddRange(nestedWritingInfos);
     }
     else
     {
         WriteType(type, writeDocumentation, showCompilerGeneratedMembers);
     }
 }
 protected override void WriteTypeInANewWriterIfNeeded(TypeDefinition type, bool writeDocumentation, bool showCompilerGeneratedMembers = false)
 {
     if (this.CurrentType != type)
     {
         ILanguageWriter    writer             = Language.GetWriter(this.formatter, this.exceptionFormatter, this.WriteExceptionsAsComments);
         List <WritingInfo> nestedWritingInfos = (writer as NamespaceImperativeLanguageWriter).WriteType(type, writerContextService, writeDocumentation, showCompilerGeneratedMembers, writeFullyQualifiedNames);
         this.writingInfos.AddRange(nestedWritingInfos);
     }
     else
     {
         WriteType(type, writeDocumentation, showCompilerGeneratedMembers);
     }
 }
        void setupDisplay(ILanguage language)
        {
            textEditorControl.SetHighlighting(language is CSharp ? "C#" : "VBNET");
            textEditorControl.ShowEOLMarkers = false;
            textEditorControl.ShowInvalidLines = false;

            swriter = new StringWriter();

            if (language != null)
            {
                writer = language.GetWriter(new PlainTextFormatter(swriter));
            }
        }
        void setupDisplay(ILanguage language)
        {
            textEditorControl.SetHighlighting(language is CSharp ? "C#" : "VBNET");
            textEditorControl.ShowEOLMarkers   = false;
            textEditorControl.ShowInvalidLines = false;

            swriter = new StringWriter();

            if (language != null)
            {
                writer = language.GetWriter(new PlainTextFormatter(swriter));
            }
        }
Beispiel #14
0
        private int WriteAssemblyInfo(IAssembly assembly, ILanguageWriterConfiguration configuration)
        {
            ILanguage   language   = LanguageManager.ActiveLanguage;
            ITranslator translator = TranslatorManager.CreateDisassembler("Xml", null);

            int exceptions = 0;

            using (StreamWriter streamWriter = CreateFile(string.Empty, "AssemblyInfo"))
            {
                TextFormatter formatter = new TextFormatter();
                try
                {
                    ILanguageWriter writer = language.GetWriter(formatter, configuration);
                    assembly = translator.TranslateAssembly(assembly, false);
                    writer.WriteAssembly(assembly);

                    foreach (IModule module in assembly.Modules)
                    {
                        IModule visitedModule = translator.TranslateModule(module, false);
                        writer.WriteModule(visitedModule);

                        foreach (IAssemblyReference assemblyReference in module.AssemblyReferences)
                        {
                            IAssemblyReference visitedAssemblyReference = translator.TranslateAssemblyReference(assemblyReference);
                            writer.WriteAssemblyReference(visitedAssemblyReference);
                        }

                        foreach (IModuleReference moduleReference in module.ModuleReferences)
                        {
                            IModuleReference visitedModuleReference = translator.TranslateModuleReference(moduleReference);
                            writer.WriteModuleReference(visitedModuleReference);
                        }
                    }

                    foreach (IResource resource in assembly.Resources)
                    {
                        writer.WriteResource(resource);
                    }
                }
                catch (Exception exception)
                {
                    streamWriter.WriteLine(exception.ToString());
                    WriteLine(exception.ToString());
                    exceptions++;
                }

                string output = formatter.ToString().Replace("\r\n", "\n").Replace("\n", "\r\n");
                streamWriter.WriteLine(output);
            }
            return(exceptions);
        }
        private string GetNamespacePerLanguage(ILanguage language, string @namespace)
        {
            var formatter = new PlainTextFormatter(new StringWriter());

            IWriterSettings settings = new WriterSettings(writeExceptionsAsComments: true,
                                                          renameInvalidMembers: true);
            ILanguageWriter writer = language.GetWriter(formatter, SimpleExceptionFormatter.Instance, settings);

            writer.ExceptionThrown += OnExceptionThrown;
            writer.WriteNamespaceNavigationName(@namespace);
            writer.ExceptionThrown -= OnExceptionThrown;

            return(formatter.ToString());
        }
 protected virtual void WriteTypeInANewWriterIfNeeded(TypeDefinition type)
 {
     if (this.CurrentType != type)
     {
         ILanguageWriter writer = Language.GetWriter(this.formatter, this.exceptionFormatter, this.Settings);
         writer.ExceptionThrown += OnExceptionThrown;
         List <WritingInfo> nestedWritingInfos = writer.Write(type, writerContextService);
         writer.ExceptionThrown -= OnExceptionThrown;
         this.writingInfos.AddRange(nestedWritingInfos);
     }
     else
     {
         WriteType(type);
     }
 }
Beispiel #17
0
        /// <summary>
        /// Display the source node as a string in a given language
        /// </summary>
        /// <returns></returns>
        public string ToString(ILanguageWriter writer)
        {
            StringWriter sw = new StringWriter();

            sw.Write(this.StartString);
            if (this.Children != null)
            {
                foreach (SourceNode child in this.Children)
                {
                    LanguageWriter.WriteSourceNode(sw, child);
                }
            }
            sw.Write(this.EndString);
            return(sw.ToString());
        }
Beispiel #18
0
        private int WriteTypeDeclaration(ITypeDeclaration typeDeclaration, ILanguageWriterConfiguration configuration)
        {
            ILanguage   language   = LanguageManager.ActiveLanguage;
            ITranslator translator = TranslatorManager.CreateDisassembler("Xml", null);

            int exceptions = 0;

            using (StreamWriter streamWriter = CreateTypeDeclarationFile(typeDeclaration))
            {
                INamespace namespaceItem = new Namespace();
                namespaceItem.Name = typeDeclaration.Namespace;

                try
                {
                    if (language.Translate)
                    {
                        typeDeclaration = translator.TranslateTypeDeclaration(typeDeclaration, true, true);
                    }
                    namespaceItem.Types.Add(typeDeclaration);
                }
                catch (Exception ex)
                {
                    streamWriter.WriteLine(ex.ToString());
                    WriteLine(ex.ToString());
                    exceptions++;
                }

                TextFormatter   formatter = new TextFormatter();
                ILanguageWriter writer    = language.GetWriter(formatter, configuration);
                try
                {
                    writer.WriteNamespace(namespaceItem);
                }
                catch (Exception exception)
                {
                    streamWriter.WriteLine(exception.ToString());
                    WriteLine(exception.ToString());
                }

                string output = formatter.ToString().Replace("\r\n", "\n").Replace("\n", "\r\n");
                streamWriter.WriteLine(output);
            }

            return(exceptions);
        }
Beispiel #19
0
        private string GetSourceCode(object method)
        {
            TextFormatter formatter = new TextFormatter();
            ILanguage     language  = this.languageManager.ActiveLanguage;

            if ((language != null) && (formatter != null))
            {
                LanguageWriterConfiguration configuration = new LanguageWriterConfiguration();
                configuration.Visibility = this.visibilityConfiguration;
                ILanguageWriter writer = language.GetWriter(formatter, configuration);
                if (writer != null)
                {
                    try
                    {
                        IMethodDeclaration md = null;
                        if (language.Translate)
                        {
                            ITranslator translator = this.translatorManager.CreateDisassembler();
                            if (translator != null)
                            {
                                md = translator.TranslateMethodDeclaration((IMethodDeclaration)method);
                            }
                        }
                        else
                        {
                            md = (IMethodDeclaration)method;
                        }

                        writer.WriteMethodDeclaration(md);

                        return(formatter.ToString());
                    }
                    catch (Exception ex)
                    {
                        string sEx = ex.ToString();
                    }
                }
            }
            return(null);
        }
Beispiel #20
0
        // get the original text from the LanguageWriter
        private string GetItemAsString(object item, int indent)
        {
            TextFormatter   formatter = new TextFormatter();
            ILanguageWriter writer    = _language.GetWriter(formatter, _configuration);

            for (int i = 0; i < indent; i++)
            {
                formatter.WriteIndent();
            }

            if (item is INamespace)
            {
                writer.WriteNamespace(item as INamespace);
            }
            if (item is ITypeDeclaration)
            {
                writer.WriteTypeDeclaration(item as ITypeDeclaration);
            }
            if (item is IEventDeclaration)
            {
                writer.WriteEventDeclaration(item as IEventDeclaration);
            }
            if (item is IFieldDeclaration)
            {
                writer.WriteFieldDeclaration(item as IFieldDeclaration);
            }
            if (item is IMethodDeclaration)
            {
                writer.WriteMethodDeclaration(item as IMethodDeclaration);
            }
            if (item is IPropertyDeclaration)
            {
                writer.WritePropertyDeclaration(item as IPropertyDeclaration);
            }

            return(formatter.ToString());
        }
        private void Translate()
        {
            if (this.Parent != null)
            {
                RichTextFormatter formatter = new RichTextFormatter();

                ILanguage language = this.languageManager.ActiveLanguage;

                LanguageWriterConfiguration configuration = new LanguageWriterConfiguration();
                configuration.Visibility = this.visibilityConfiguration;
                configuration["ShowCustomAttributes"]      = "true";
                configuration["ShowNamespaceImports"]      = "true";
                configuration["ShowNamespaceBody"]         = "true";
                configuration["ShowTypeDeclarationBody"]   = "true";
                configuration["ShowMethodDeclarationBody"] = "false";

                ILanguageWriter writer = language.GetWriter(formatter, configuration);

                object value = this.assemblyBrowser.ActiveItem;

                ITypeDeclaration typeDeclaration = value as ITypeDeclaration;
                if (typeDeclaration != null)
                {
                    configuration["ShowMethodDeclarationBody"] = "false";

                    if (language.Translate)
                    {
                        typeDeclaration = this.translatorManager.CreateDisassembler(null, null).TranslateTypeDeclaration(typeDeclaration, true, false);
                    }

                    writer.WriteTypeDeclaration(typeDeclaration);
                }

                IFieldDeclaration fieldDeclaration = value as IFieldDeclaration;
                if (fieldDeclaration != null)
                {
                    configuration["ShowMethodDeclarationBody"] = "true";

                    if (language.Translate)
                    {
                        fieldDeclaration = this.translatorManager.CreateDisassembler(null, null).TranslateFieldDeclaration(fieldDeclaration);
                    }

                    writer.WriteFieldDeclaration(fieldDeclaration);
                }

                IMethodDeclaration methodDeclaration = value as IMethodDeclaration;
                if (methodDeclaration != null)
                {
                    configuration["ShowMethodDeclarationBody"] = "true";

                    if (language.Translate)
                    {
                        methodDeclaration = this.translatorManager.CreateDisassembler(null, null).TranslateMethodDeclaration(methodDeclaration);
                    }

                    writer.WriteMethodDeclaration(methodDeclaration);
                }

                IPropertyDeclaration propertyDeclaration = value as IPropertyDeclaration;
                if (propertyDeclaration != null)
                {
                    configuration["ShowMethodDeclarationBody"] = "true";

                    if (language.Translate)
                    {
                        propertyDeclaration = this.translatorManager.CreateDisassembler(null, null).TranslatePropertyDeclaration(propertyDeclaration);
                    }

                    writer.WritePropertyDeclaration(propertyDeclaration);
                }

                IEventDeclaration eventDeclaration = value as IEventDeclaration;
                if (eventDeclaration != null)
                {
                    configuration["ShowMethodDeclarationBody"] = "true";

                    if (language.Translate)
                    {
                        eventDeclaration = this.translatorManager.CreateDisassembler(null, null).TranslateEventDeclaration(eventDeclaration);
                    }

                    writer.WriteEventDeclaration(eventDeclaration);
                }

                this.Rtf = formatter.ToString();
            }
        }
Beispiel #22
0
        public override Task <DecompileTypeResponse> DecompileType(DecompileTypeRequest request, ServerCallContext context)
        {
            if (!this.decompilationContext.DecompilationContext.FilePathToType.ContainsKey(request.FilePath))
            {
                throw new RpcException(new Status(StatusCode.NotFound, "No type to corresponding file path"));
            }

            TypeDefinition      type = this.decompilationContext.DecompilationContext.FilePathToType[request.FilePath];
            IExceptionFormatter exceptionFormatter = SimpleExceptionFormatter.Instance;
            ILanguage           language           = LanguageFactory.GetLanguage(CSharpVersion.V7);
            StringWriter        theWriter          = new StringWriter();
            CodeFormatter       formatter          = new CodeFormatter(theWriter);
            IWriterSettings     settings           = new WriterSettings(writeExceptionsAsComments: true,
                                                                        writeFullyQualifiedNames: false,
                                                                        writeDocumentation: true,
                                                                        showCompilerGeneratedMembers: false,
                                                                        writeLargeNumbersInHex: false);
            ILanguageWriter writer = language.GetWriter(formatter, exceptionFormatter, settings);

            IWriterContextService writerContextService = new TypeCollisionWriterContextService(new ProjectGenerationDecompilationCacheService(), true);

            try
            {
                List <WritingInfo> infos = (writer as INamespaceLanguageWriter).WriteTypeAndNamespaces(type, writerContextService);

                DecompiledTypeMetadata decompiledTypeMetadata = new DecompiledTypeMetadata();

                decompiledTypeMetadata.CodeSpanToMemberReference.AddRange(formatter.CodeSpanToMemberReference);

                foreach (WritingInfo info in infos)
                {
                    decompiledTypeMetadata.MemberDeclarationToCodeSpan.AddRange(info.MemberDeclarationToCodeSpan);

                    decompiledTypeMetadata.CodeMappingInfo.NodeToCodeMap.AddRange(info.CodeMappingInfo.NodeToCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.InstructionToCodeMap.AddRange(info.CodeMappingInfo.InstructionToCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.FieldConstantValueToCodeMap.AddRange(info.CodeMappingInfo.FieldConstantValueToCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.VariableToCodeMap.AddRange(info.CodeMappingInfo.VariableToCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.ParameterToCodeMap.AddRange(info.CodeMappingInfo.ParameterToCodeMap);

                    decompiledTypeMetadata.CodeMappingInfo.MethodDefinitionToMethodReturnTypeCodeMap.AddRange(info.CodeMappingInfo.MethodDefinitionToMethodReturnTypeCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.FieldDefinitionToFieldTypeCodeMap.AddRange(info.CodeMappingInfo.FieldDefinitionToFieldTypeCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.PropertyDefinitionToPropertyTypeCodeMap.AddRange(info.CodeMappingInfo.PropertyDefinitionToPropertyTypeCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.EventDefinitionToEventTypeCodeMap.AddRange(info.CodeMappingInfo.EventDefinitionToEventTypeCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.ParameterDefinitionToParameterTypeCodeMap.AddRange(info.CodeMappingInfo.ParameterDefinitionToParameterTypeCodeMap);
                    decompiledTypeMetadata.CodeMappingInfo.VariableDefinitionToVariableTypeCodeMap.AddRange(info.CodeMappingInfo.VariableDefinitionToVariableTypeCodeMap);
                }

                this.decompilationContext.AddTypeMetadataToCache(type, decompiledTypeMetadata);

                return(Task.FromResult(new DecompileTypeResponse()
                {
                    SourceCode = theWriter.ToString()
                }));
            }
            catch (Exception e)
            {
                string[] exceptionMessageLines     = exceptionFormatter.Format(e, type.FullName, null);
                string   exceptionMessage          = string.Join(Environment.NewLine, exceptionMessageLines);
                string   commentedExceptionMessage = language.CommentLines(exceptionMessage);

                return(Task.FromResult(new DecompileTypeResponse()
                {
                    SourceCode = commentedExceptionMessage
                }));
            }
        }
        /// <summary>
        /// Called when a part's imports have been satisfied and it is safe to use.
        /// </summary>
        public void OnImportsSatisfied()
        {
            _stringWriter = new StringWriter();

            _chain = new FormatterChain(_hooks);

            LanguageWriter = _languageWriterCreator(_chain);
            if (LanguageWriter == null)
                throw new ArgumentOutOfRangeException("languageWriterCreator", Monoflector.Properties.Resources.LanguageWriterCreator_NullValue);
        }
        public bool WriteTypeToFile(TypeDefinition type, IProjectItemFileWriter itemWriter, Dictionary <string, ICollection <string> > membersToSkip, bool shouldBePartial,
                                    ILanguage language, out List <WritingInfo> writingInfos, out string theCodeString)
        {
            theCodeString = string.Empty;
            writingInfos  = null;
            StringWriter theWriter = new StringWriter();

            bool showCompilerGeneratedMembers = Utilities.IsVbInternalTypeWithoutRootNamespace(type) ||
                                                Utilities.IsVbInternalTypeWithRootNamespace(type);

            IFormatter      formatter = GetFormatter(theWriter);
            IWriterSettings settings  = new WriterSettings(writeExceptionsAsComments: true,
                                                           writeFullyQualifiedNames: decompilationPreferences.WriteFullNames,
                                                           writeDocumentation: decompilationPreferences.WriteDocumentation,
                                                           showCompilerGeneratedMembers: showCompilerGeneratedMembers,
                                                           writeLargeNumbersInHex: decompilationPreferences.WriteLargeNumbersInHex);
            ILanguageWriter writer = language.GetWriter(formatter, this.exceptionFormater, settings);

            IWriterContextService writerContextService = this.GetWriterContextService();

            writer.ExceptionThrown += OnExceptionThrown;
            writerContextService.ExceptionThrown += OnExceptionThrown;

            bool exceptionOccurred = false;

            try
            {
                if (!(writer is INamespaceLanguageWriter))
                {
                    writingInfos = writer.Write(type, writerContextService);
                }
                else
                {
                    if (shouldBePartial)
                    {
                        writingInfos = (writer as INamespaceLanguageWriter).WritePartialTypeAndNamespaces(type, writerContextService, membersToSkip);
                    }
                    else
                    {
                        writingInfos = (writer as INamespaceLanguageWriter).WriteTypeAndNamespaces(type, writerContextService);
                    }
                }

                this.RecordGeneratedFileData(type, itemWriter.FullSourceFilePath, theWriter, formatter, writerContextService, writingInfos);

                MemoryStream sourceFileStream = new MemoryStream(Encoding.UTF8.GetBytes(theWriter.ToString()));
                itemWriter.CreateProjectSourceFile(sourceFileStream);
                sourceFileStream.Close();
                theWriter.Close();
            }
            catch (Exception e)
            {
                exceptionOccurred = true;

                string[] exceptionMessageLines     = exceptionFormater.Format(e, type.FullName, itemWriter.FullSourceFilePath);
                string   exceptionMessage          = string.Join(Environment.NewLine, exceptionMessageLines);
                string   commentedExceptionMessage = language.CommentLines(exceptionMessage);
                itemWriter.CreateProjectSourceFile(new MemoryStream(Encoding.UTF8.GetBytes(commentedExceptionMessage)));

                OnExceptionThrown(this, e);
            }

            theCodeString = theWriter.ToString();

            writer.ExceptionThrown -= OnExceptionThrown;
            writerContextService.ExceptionThrown -= OnExceptionThrown;

            return(exceptionOccurred || writerContextService.ExceptionsWhileDecompiling.Any());
        }
        public string Decompile(int languageIndex, object o)
        {
            if (o == null)
            {
                return(String.Empty);
            }

            IFormatter      formatter  = CreateFormatter(this.LanguageManager.Languages[languageIndex].Name);
            ILanguageWriter writer     = this.LanguageManager.Languages[languageIndex].GetWriter(formatter, _langurageWriterConfiguration);
            ITranslator     translator = this.TranslatorManager.CreateDisassembler(null, null);

            if (o is IMethodDeclaration)
            {
                IMethodDeclaration m2;
                if (IsIL(languageIndex))
                {
                    m2 = (IMethodDeclaration)o;
                }
                else
                {
                    m2 = translator.TranslateMethodDeclaration((IMethodDeclaration)o);
                }
                writer.WriteMethodDeclaration(m2);
            }
            else if (o is IPropertyDeclaration)
            {
                IPropertyDeclaration p2 = translator.TranslatePropertyDeclaration((IPropertyDeclaration)o);
                writer.WritePropertyDeclaration(p2);
            }
            else if (o is IFieldDeclaration)
            {
                IFieldDeclaration f2 = translator.TranslateFieldDeclaration((IFieldDeclaration)o);
                writer.WriteFieldDeclaration(f2);
            }
            else if (o is ITypeDeclaration)
            {
                ITypeDeclaration t2 = translator.TranslateTypeDeclaration((ITypeDeclaration)o, true, false);
                writer.WriteTypeDeclaration(t2);
            }
            else if (o is IEventDeclaration)
            {
                IEventDeclaration e2 = translator.TranslateEventDeclaration((IEventDeclaration)o);
                writer.WriteEventDeclaration(e2);
            }
            else if (o is IModule)
            {
                IModule m2 = translator.TranslateModule((IModule)o, true);
                writer.WriteModule(m2);
            }
            else if (o is IModuleReference)
            {
                IModuleReference mr2 = translator.TranslateModuleReference((IModuleReference)o);
                writer.WriteModuleReference(mr2);
            }
            else if (o is IAssembly)
            {
                IAssembly a2 = translator.TranslateAssembly((IAssembly)o, true);
                writer.WriteAssembly(a2);
            }
            else if (o is IAssemblyReference)
            {
                IAssemblyReference ar2 = translator.TranslateAssemblyReference((IAssemblyReference)o);
                writer.WriteAssemblyReference(ar2);
            }
            else if (o is IResource)
            {
                writer.WriteResource((IResource)o);
            }
            else if (o is INamespace)
            {
                writer.WriteNamespace((INamespace)o);
            }

            return(formatter.ToString());
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            Assembly ass = Assembly.LoadFrom(@"D:\Nick Personal\Programming\GPU\Projects\Cudafy\Cudafy\bin\Debug\ESA.Dataflow.dll"); //(typeof(Program));
            //  ass.
            ////AssemblyDefinition.
            AssemblyDefinition         ad  = AssemblyFactory.GetAssembly(ass.Location);
            ModuleDefinitionCollection mdc = ad.Modules;
            StringBuilder sb           = new StringBuilder();
            StringWriter  streamWriter = new StringWriter(sb);

            foreach (ModuleDefinition mod in mdc)
            {
                Console.WriteLine(mod.Name);
                foreach (TypeDefinition type in mod.Types)
                {
                    Console.WriteLine(type.FullName);
                    if (type.Name == "ControlVector")
                    {
                        foreach (MethodDefinition md in type.Methods)
                        {
                            //foreach (CustomAttribute ca in md.CustomAttributes)
                            //{
                            //    if (ca.Constructor.DeclaringType.Name == "GPUFunctionAttribute")
                            //    {
                            if (md.Name == "Add")
                            {
                                Console.WriteLine(md.Name);
                                ILanguage       lan       = Cecil.Decompiler.Languages.CSharp.GetLanguage(Cecil.Decompiler.Languages.CSharpVersion.V3);
                                ILanguageWriter lanWriter = lan.GetWriter(new PlainTextFormatter(streamWriter));
                                lanWriter.Write(md);

                                Console.WriteLine(sb.ToString());
                            }
                            // }
                            //}
                        }
                    }
                }
            }

            int size = 4;

            int[]   myArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7 };
            int[][] inputA  = new int[size][];
            int[][] inputB  = new int[size][];
            int[][] outputC = new int[size][];
            for (int i = 0; i < size; i++)
            {
                inputB[i]  = new int[size];
                outputC[i] = new int[size];
                inputA[i]  = new int[size];
                int cnt = i;
                for (int x = 0; x < size; x++)
                {
                    inputA[i][x] = cnt;
                    inputB[i][x] = cnt++;
                }
            }

            HCudafy cuda = new HCudafy();

            cuda.Cudafy(typeof(Program));

            Stopwatch sw = new Stopwatch();

            sw.Start();
            int[]   devMyArray = cuda.CopyToDevice(myArray);
            int[][] devA       = cuda.CopyToDevice(inputA);
            int[][] devB       = cuda.CopyToDevice(inputB);
            int[][] devC       = cuda.Allocate(outputC);
            Dim3    grid       = new Dim3(1);
            Dim3    block      = new Dim3(size / 1);

            cuda.Launch(grid, block, "doVecAdd", devA, devB, devC, 42, devMyArray);

            cuda.CopyFromDevice(devC, outputC);
            sw.Stop();
            for (int i = 0; i < 4; i++)
            {
                for (int x = 0; x < 4; x++)
                {
                    Console.Write("{0}\t", outputC[i][x]);
                }
                Console.WriteLine();
            }

            int[] somestuff = new int[512];
            for (int y = 0; y < 512; y++)
            {
                somestuff[y] = y * 10;
            }
            int[] data = cuda.CopyToDevice(somestuff);
            int[] res  = new int[512];
            cuda.CopyFromDevice(data, res);
            for (int y = 0; y < 512; y++)
            {
                if (res[y] != somestuff[y])
                {
                    throw new Exception();
                }
            }


            int[][] deviceArray2D = cuda.Allocate <int>(4, 8);
            int[]   deviceArray   = cuda.Allocate <int>(7);

            Console.WriteLine(sw.ElapsedMilliseconds + "ms");
            Console.WriteLine("Done");
            Console.ReadKey();
            return;

            #region scrap
            //Action<object> action = (object obj) =>
            //{
            //    Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId);
            //};
            //Task t = new Task(action, "hello");
            //HThread ht = new HThread(action, "hello");

            //HGrid grid = new HGrid(
            //HCudafy.Launch(
            int     side          = 1024;
            int[][] myJaggedArray = new int[side][];
            for (int i = 0; i < side; i++)
            {
                myJaggedArray[i] = new int[side];
                int cnt = i;
                for (int x = 0; x < side; x++)
                {
                    myJaggedArray[i][x] = cnt++;
                }
            }

            int threads = Environment.ProcessorCount / 1;
            //  _barrier = new Barrier(threads);

            //Console.WriteLine("Before");
            //var po = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount };
            //Parallel.For(0, side, po, i => Process(myJaggedArray[i]));
            myJaggedArray.AsParallel().WithDegreeOfParallelism(threads).ForAll(x => Process(x));
            //myJaggedArray.ToList().ForEach(x => Process(x));
            //Console.WriteLine("Between");
            //myJaggedArray.AsParallel().WithDegreeOfParallelism(threads).ForAll(x => Process(x));
            sw.Stop();
            // _barrier.Dispose();
            Console.WriteLine(sw.ElapsedMilliseconds + "ms");
            Console.WriteLine("Done");
            Console.ReadKey();
            #endregion
        }
        /// <summary>
        /// Called when a part's imports have been satisfied and it is safe to use.
        /// </summary>
        public void OnImportsSatisfied()
        {
            _formatter = null;
            _stringWriter = new StringWriter();
            IFormatter formatter = new PlainTextFormatter(_stringWriter);

            // Get the hooks.
            if (_hooks != null)
            {
                var chain = new FormatterChain(_hooks);
                chain.Prepend(formatter);
                formatter = _formatter = chain;
            }

            LanguageWriter = _languageWriterCreator(formatter);
            if (LanguageWriter == null)
                throw new ArgumentOutOfRangeException("languageWriterCreator", Monoflector.Properties.Resources.LanguageWriterCreator_NullValue);
        }