示例#1
0
        private static bool TryGetLanguageParam(string[] args, out ILanguage result, ref bool isInvalidLanguage)
        {
            string languageAsString;

            if (TryGetParam(args, "/lang", out languageAsString))
            {
                if (languageAsString == CommandLineManager.CSharpLanguage)
                {
                    result = LanguageFactory.GetLanguage(CSharpVersion.V6);
                    return(true);
                }
                else if (languageAsString == CommandLineManager.VisualBasicLanguage)
                {
                    result = LanguageFactory.GetLanguage(VisualBasicVersion.V10);
                    return(true);
                }
                else
                {
                    isInvalidLanguage = true;
                }
            }

            result = null;
            return(false);
        }
        public IntermediateDecompilationCSharpLanguageWriter(IFormatter formatter)
            : base(LanguageFactory.GetLanguage(CSharpVersion.None), formatter, new WriterSettings(writeExceptionsAsComments: true))
        {
            SimpleWriterContextService swcs = new SimpleWriterContextService(new DefaultDecompilationCacheService(), renameInvalidMembers);

            this.writerContextService = swcs;
        }
示例#3
0
文件: Program.cs 项目: rmacfie/Words
        static LanguageInfo loadLanguage(string languageCode)
        {
            var languageFactory = new LanguageFactory(new LettersFileReader(), new LexiconFileReader());
            var language = languageFactory.GetLanguage(languageCode);

            Console.WriteLine("Loaded language: {0}", language.Code);
            Console.WriteLine("  Lexicon: {0} words loaded", language.Lexicon.Count);
            Console.WriteLine("  Letters: {0} letters loaded", language.Letters.Count);
            Console.WriteLine();

            return language;
        }
示例#4
0
        public ILanguage GetLanguage()
        {
            ILanguageSelector languageSelector = GetLanguageSelector();

            if (languageSelector == null)
            {
                return(LanguageFactory.GetLanguage(CSharpVersion.V7));
            }
            else
            {
                return(languageSelector.GetLanguage());
            }
        }
示例#5
0
        private GeneratorProjectInfo(string target, string @out, IProjectGenerationError error)
        {
            this.Target = target;
            this.Out    = @out;

            this.Language                  = LanguageFactory.GetLanguage(CSharpVersion.V6);
            this.VisualStudioVersion       = VisualStudioVersion.VS2015;
            this.frameworkVersion          = FrameworkVersion.v4_6_1;
            this.IsDefaultFrameworkVersion = true;

            this.AddDocumentation     = true;
            this.RenameInvalidMembers = true;

            this.Error = error;
        }
        private static ILanguage GetLanguage(SupportedLanguage language)
        {
            switch (language)
            {
            case SupportedLanguage.CSharp:
                return(LanguageFactory.GetLanguage(CSharpVersion.V6));

            case SupportedLanguage.VB:
                return(LanguageFactory.GetLanguage(VisualBasicVersion.V10));

            case SupportedLanguage.MSIL:
                return(new IntermediateLanguage());

            default:
                throw new NotSupportedException("Unexpected language");
            }
        }
        private GeneratorProjectInfo(string target, string @out, IProjectGenerationError error)
        {
            this.Target = target;
            this.Out    = @out;

            this.Language                  = LanguageFactory.GetLanguage(CSharpVersion.V7);
            this.VisualStudioVersion       = VisualStudioVersion.VS2017;
            this.frameworkVersion          = FrameworkVersion.v4_7;
            this.IsDefaultFrameworkVersion = true;

            this.AddDocumentation            = true;
            this.RenameInvalidMembers        = true;
            this.WriteLargeNumbersInHex      = true;
            this.DecompileDangerousResources = false;

            this.Error = error;
        }
        private MSBuildProjectBuilder CreateProjectBuilder(string target, string output)
        {
            DecompilationPreferences preferences = new DecompilationPreferences();

            preferences.WriteFullNames              = false;
            preferences.WriteDocumentation          = true;
            preferences.RenameInvalidMembers        = true;
            preferences.WriteLargeNumbersInHex      = true;
            preferences.DecompileDangerousResources = false;

            ILanguage language     = LanguageFactory.GetLanguage(CSharpVersion.None);
            string    projFilePath = Path.Combine(output, Path.GetFileNameWithoutExtension(target) + language.VSProjectFileExtension);

            TestMSBuildProjectBuilder result = new TestMSBuildProjectBuilder(target, projFilePath, language, preferences);

            return(result);
        }
示例#9
0
        static void Main(string[] args)
        {
            var formas = new List <FormaGeometrica> {
                new FormaGeometrica(EGeometricShapes.Square, 5, null, null, null, null),
                new FormaGeometrica(EGeometricShapes.Square, 5, null, null, null, null),
                new FormaGeometrica(EGeometricShapes.Rectangle, 8, 4, null, null, null),
                new FormaGeometrica(EGeometricShapes.EquilateralTriangle, 8, null, null, null, null),
                new FormaGeometrica(EGeometricShapes.Trapeze, 8, 4, 2, 1, 2),
                new FormaGeometrica(EGeometricShapes.Trapeze, 8, 4, 2, 1, 2),
                new FormaGeometrica(EGeometricShapes.Circle, 5, null, null, null, null)
            };

            var resumen = FormaGeometrica.Imprimir(formas, LanguageFactory.GetLanguage(ELanguages.Spanish));

            Console.WriteLine(resumen);
            Console.ReadKey();
        }
示例#10
0
        private Dictionary <string, TypeDefinition> GetAllTypeFilePathsForAssembly(AssemblyDefinition assembly, string assemblyFilePath)
        {
            Dictionary <ModuleDefinition, Collection <TypeDefinition> > userDefinedTypes = Utilities.GetUserDefinedTypes(assembly, true);
            Dictionary <ModuleDefinition, Collection <Resource> >       resources        = Utilities.GetResources(assembly);
            DefaultFilePathsService filePathsService = new DefaultFilePathsService(
                assembly,
                assemblyFilePath,
                null,
                userDefinedTypes,
                resources,
                assembly.BuildNamespaceHierarchyTree(),
                LanguageFactory.GetLanguage(CSharpVersion.V7),
                Utilities.GetMaxRelativePathLength(this.pathService.WorkingDirectory),
                true);

            return(filePathsService.GetTypesToFilePathsMap()
                   .ToDictionary(kvp => Path.Join(this.pathService.WorkingDirectory, assembly.FullName, assembly.MainModule.Name, kvp.Value), kvp => kvp.Key));
        }
示例#11
0
 /// <summary>
 /// 获取Json格式的语言对象字符串
 /// </summary>
 /// <returns></returns>
 public static List <Language> GetLanguage()
 {
     try
     {
         List <Language> retList = factory.GetLanguage();
         if (retList == null)
         {
             throw new Exception("DAL.Common.LanguageFactory.GetLanguage()==null");
         }
         return(retList);
     }
     catch (Exception ex)
     {
         LogHelper.WriteLog(new Log()
         {
             message = ex.Message
         }, "Langauge");
         return(null);
     }
 }
示例#12
0
        private static BlockStatement DecompileStateMachine(this MethodBody body, MethodSpecificContext enclosingMethodContext,
                                                            IStateMachineRemoverStep removeStateMachineStep,
                                                            Func <DecompilationContext, IStateMachineData> stateMachineDataSelector,
                                                            out DecompilationContext decompilationContext)
        {
            ILanguage language = LanguageFactory.GetLanguage(CSharpVersion.V6);

            removeStateMachineStep.Language = language;

            DecompilationPipeline thePipeline = GetStateMachineRemovalPipeline(removeStateMachineStep, stateMachineDataSelector);

            decompilationContext = thePipeline.Run(body, language);

            enclosingMethodContext.Variables.AddRange(decompilationContext.MethodContext.Variables);
            enclosingMethodContext.VariableDefinitionToNameMap.AddRange(decompilationContext.MethodContext.VariableDefinitionToNameMap);
            enclosingMethodContext.AddInnerMethodParametersToContext(decompilationContext.MethodContext);
            enclosingMethodContext.VariableAssignmentData.AddRange(decompilationContext.MethodContext.VariableAssignmentData);
            enclosingMethodContext.GotoLabels.AddRange(decompilationContext.MethodContext.GotoLabels);
            enclosingMethodContext.GotoStatements.AddRange(decompilationContext.MethodContext.GotoStatements);
            BlockStatement theBlockStatement = thePipeline.Body;

            return(theBlockStatement);
        }
示例#13
0
        public override Task <GetProjectCreationMetadataResponse> GetProjectCreationMetadata(GetProjectCreationMetadataRequest request, ServerCallContext context)
        {
            VisualStudioVersion       visualStudioVersion = this.GetProjectCreationVSVersion(request.ProjectVisualStudioVersion);
            AssemblyDefinition        assemblyDefinition  = GlobalAssemblyResolver.Instance.GetAssemblyDefinition(request.AssemblyFilePath);
            ILanguage                 language            = LanguageFactory.GetLanguage(CSharpVersion.V7);
            ProjectGenerationSettings settings            = ProjectGenerationSettingsProvider.GetProjectGenerationSettings(request.AssemblyFilePath, NoCacheAssemblyInfoService.Instance,
                                                                                                                           EmptyResolver.Instance, visualStudioVersion, language, TargetPlatformResolver.Instance);
            bool   containsDangerousResources       = assemblyDefinition.Modules.SelectMany(m => m.Resources).Any(r => DangerousResourceIdentifier.IsDangerousResource(r));
            string normalizedVSProjectFileExtension = language.VSProjectFileExtension.TrimStart('.');
            string generatedProjectExtension        = normalizedVSProjectFileExtension + (settings.JustDecompileSupportedProjectType ? string.Empty : MSBuildProjectBuilder.ErrorFileExtension);

            return(Task.FromResult(new GetProjectCreationMetadataResponse()
            {
                ContainsDangerousResources = containsDangerousResources,
                ProjectFileMetadata = new ProjectFileMetadata()
                {
                    IsDecompilerSupportedProjectType = settings.JustDecompileSupportedProjectType,
                    IsVSSupportedProjectType = settings.VisualStudioSupportedProjectType,
                    ProjectTypeNotSupportedErrorMessage = settings.ErrorMessage ?? string.Empty,
                    ProjectFileName = assemblyDefinition.Name.Name,
                    ProjectFileExtension = generatedProjectExtension
                }
            }));
        }
示例#14
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
                }));
            }
        }
示例#15
0
        public IEnumerable <SearchResult> Search(string query, bool matchCasing = false, bool matchWholeWord = false)
        {
            this.cachedSearchResults = new Dictionary <int, SearchResult>();

            using (this.searchOperationCancellationTokenSource = new CancellationTokenSource())
            {
                CancellationToken token = this.searchOperationCancellationTokenSource.Token;

                IEnumerable <string> openedAssembliesFilePaths = this.decompilationContext.GetOpenedAssemliesPaths();

                foreach (string assemblyFilePath in openedAssembliesFilePaths)
                {
                    AssemblyDefinition assembly = GlobalAssemblyResolver.Instance.GetAssemblyDefinition(assemblyFilePath);

                    IEnumerable <TypeDefinition> types = assembly.Modules.SelectMany(m => m.GetTypes()).Where(t => !t.IsCompilerGenerated());

                    foreach (TypeDefinition type in types)
                    {
                        if (token.IsCancellationRequested)
                        {
                            this.searchOperationCancellationTokenSource = null;
                            yield break;
                        }

                        if (this.DoesMatchSearchCriteria(query, type, matchCasing, matchWholeWord))
                        {
                            yield return(this.AddSearchResultToCache(SearchResultType.DeclaringType, type, type.Name, type));
                        }

                        IEnumerable <IMemberDefinition> members = type.GetMembersSorted(false, LanguageFactory.GetLanguage(CSharpVersion.V7));

                        if (members.Count() == 0)
                        {
                            continue;
                        }

                        foreach (IMemberDefinition member in members)
                        {
                            if (token.IsCancellationRequested)
                            {
                                this.searchOperationCancellationTokenSource = null;
                                yield break;
                            }

                            if (this.DoesMatchSearchCriteria(query, member.Name, matchCasing, matchWholeWord))
                            {
                                SearchResultType memberSearchResultType = this.GetSearchResultTypeFromMemberDefinitionType(member);

                                // Skip adding nested types when traversing the type members as they are added when traversing the module types
                                if (memberSearchResultType != SearchResultType.DeclaringType)
                                {
                                    yield return(this.AddSearchResultToCache(memberSearchResultType, type, member.Name, member));
                                }
                            }

                            if (member is EventDefinition eventDefinition && this.DoesMatchSearchCriteria(query, eventDefinition.EventType, matchCasing, matchWholeWord))
                            {
                                yield return(this.AddSearchResultToCache(SearchResultType.EventType, type, this.GetFriendlyName(eventDefinition.EventType), eventDefinition));
                            }