Esempio n. 1
0
        public static MatchingResultDto[] GetMatchings(string code, string pattern, LanguageFlags analyzedLanguages,
                                                       LanguageFlags?patternLanguages = null)
        {
            var sourceCodeRep = new MemoryCodeRepository(code);
            var patternsRep   = new MemoryPatternsRepository();
            var workflow      = new Workflow(sourceCodeRep, analyzedLanguages, patternsRep)
            {
                Logger = new LoggerMessageCounter()
            };

            var processor   = new DslProcessor();
            var patternNode = (PatternNode)processor.Deserialize(pattern, patternLanguages ?? LanguageExt.AllPatternLanguages);
            var p           = new Pattern
            {
                Data      = patternNode,
                DebugInfo = pattern
            };
            var patternsConverter = new PatternConverter(
                new JsonUstNodeSerializer(typeof(UstNode), typeof(PatternVarDef)));

            patternsRep.Add(patternsConverter.ConvertBack(new List <Pattern>()
            {
                p
            }));
            WorkflowResult workflowResult = workflow.Process();

            MatchingResultDto[] matchingResults = workflowResult.MatchingResults.ToDto(workflow.SourceCodeRepository)
                                                  .OrderBy(r => r.PatternKey)
                                                  .ToArray();

            return(matchingResults);
        }
Esempio n. 2
0
        public static void Run()
        {
            LanguageFlags lang = LanguageFlags.CSharp | LanguageFlags.VBNET;

            // contains
            if ((lang & LanguageFlags.CSharp) == LanguageFlags.CSharp)
            {
                Console.WriteLine($"it contaions {LanguageFlags.CSharp}");
            }
            else
            {
                Console.WriteLine($"it does not contaions {LanguageFlags.CSharp}");
            }

            // exclusive
            if (lang == LanguageFlags.CSharp)
            {
                Console.WriteLine($"it == {LanguageFlags.CSharp}");
            }
            else
            {
                Console.WriteLine($"it != {LanguageFlags.CSharp}");
            }

            // contains exclusively
            if ((lang != 0) && (lang | (LanguageFlags.CSharp | LanguageFlags.VBNET)) == (LanguageFlags.CSharp | LanguageFlags.VBNET))
            {
                Console.WriteLine($"it only contains {LanguageFlags.CSharp}");
            }
            else
            {
                Console.WriteLine($"it does not only contains {LanguageFlags.CSharp}");
            }
        }
Esempio n. 3
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject       jObject             = JObject.Load(reader);
            var           languageFlagsString = (string)jObject[nameof(PatternDto.Languages)];
            LanguageFlags resultLanguages     = LanguageExt.ParseLanguages(languageFlagsString);

            var result = new PatternDto
            {
                Name             = (string)jObject[nameof(PatternDto.Name)] ?? "",
                Key              = (string)jObject[nameof(PatternDto.Key)] ?? "",
                Languages        = resultLanguages,
                FilenameWildcard = (string)jObject[nameof(PatternDto.FilenameWildcard)] ?? "",
                Value            = (string)jObject[nameof(PatternDto.Value)] ?? "",
                CweId            = (string)jObject[nameof(PatternDto.CweId)] ?? "",
                Description      = (string)jObject[nameof(PatternDto.Description)] ?? "",
            };
            var dataFormatString = (string)jObject[nameof(PatternDto.DataFormat)];
            UstNodeSerializationFormat format;

            if (dataFormatString != null && Enum.TryParse(dataFormatString, out format))
            {
                result.DataFormat = format;
            }

            return(result);
        }
Esempio n. 4
0
        private void SetSourceFields(LanguageFlags languageFlags, IEntryLanguage entrySourceLanguage)
        {
            pictureBoxSource.Load(languageFlags.GetImageStudioCodeByLanguageCode(entrySourceLanguage.Locale.Name));
            lblSourceLanguageText.Text = entrySourceLanguage.Name;
            var sourceTerms = entrySourceLanguage.Terms;

            if (sourceTerms.Count > 0)
            {
                lblSourceTermText.Text = Utils.UppercaseFirstLetter(sourceTerms[0].Value);

                txtSourceDefinitionText.Text = sourceTerms[0].Fields.Where(f => f.Name.Equals("Definition")).FirstOrDefault() != null
                                        ? Utils.UppercaseFirstLetter(sourceTerms[0].Fields.Where(f => f.Name.Equals("Definition")).FirstOrDefault().Value)
                                        : string.Empty;

                lblSourceDomainText.Text = sourceTerms[0].Fields.Where(f => f.Name.Equals("Domain")).FirstOrDefault() != null
                                        ? Utils.UppercaseFirstLetter(sourceTerms[0].Fields.Where(f => f.Name.Equals("Domain")).FirstOrDefault().Value.ToLower())
                                        : string.Empty;

                lblSourceSubdomainText.Text = sourceTerms[0].Fields.Where(f => f.Name.Equals("Subdomain")).FirstOrDefault() != null
                                        ? sourceTerms[0].Fields.Where(f => f.Name.Equals("Subdomain")).FirstOrDefault().Value
                                        : string.Empty;
                lblSourceSubdomainText.Text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(lblTargetSubdomainText.Text.ToLower());

                lblSourceTermTypeText.Text = sourceTerms[0].Fields.Where(f => f.Name.Equals("TermType")).FirstOrDefault() != null
                                        ? Utils.UppercaseFirstLetter(sourceTerms[0].Fields.Where(f => f.Name.Equals("TermType")).FirstOrDefault().Value)
                                        : string.Empty;
            }
        }
Esempio n. 5
0
 public PatternBase(string key, string debugInfo, LanguageFlags languages, string filenameWildcard)
 {
     Key              = key;
     DebugInfo        = debugInfo;
     Languages        = languages;
     FilenameWildcard = filenameWildcard;
 }
Esempio n. 6
0
        public UstNode Deserialize(string data, LanguageFlags sourceLanguage)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ParsingException("Pattern value can not be empty.")
                      {
                          IsPattern = true
                      };
            }

            Parser.Logger       = Logger;
            UstConverter.Logger = Logger;
            DslParser.PatternContext patternContext = Parser.Parse(data);
            UstConverter.SourceLanguage = sourceLanguage;
            UstConverter.Data           = data;
            DslNode dslNode = UstConverter.Convert(patternContext);
            UstNode result  = dslNode.Collection.First();

            ResultPatternVars = dslNode.PatternVarDefs;
            var preprocessor = new UstPreprocessor();

            preprocessor.Logger = Logger;
            result = new PatternNode(result, dslNode.PatternVarDefs);
            result = preprocessor.Preprocess(result);

            return(result);
        }
Esempio n. 7
0
 public LanguageInfo(Language language, string[] extensions, bool caseInsensitive, string title = null,
                     LanguageFlags dependentLanguages = LanguageFlags.None, bool haveAntlrParser = true)
 {
     Language           = language;
     Extensions         = extensions;
     CaseInsensitive    = caseInsensitive;
     Title              = string.IsNullOrEmpty(title) ? Language.ToString() : title;
     DependentLanguages = dependentLanguages;
     HaveAntlrParser    = haveAntlrParser;
 }
Esempio n. 8
0
        public override void BuildAst(LanguageData language, ParseTree parseTree)
        {
            if (!LanguageFlags.IsSet(LanguageFlags.CreateAst))
            {
                return;
            }
            var astContext = new AstContext(language);
            var astBuilder = new AstBuilder(astContext);

            astBuilder.BuildAst(parseTree);
        }
Esempio n. 9
0
        private void CheckPattern()
        {
            if (oldPattern != patternTextBox.Text || oldLanguages != Languages)
            {
                oldPattern   = patternTextBox.Text;
                oldLanguages = Languages;

                Dispatcher.UIThread.InvokeAsync(PatternErrors.Clear);
                patternLogger.Clear();

                UstNode patternNode = null;
                try
                {
                    if (!string.IsNullOrEmpty(patternTextBox.Text))
                    {
                        patternNode = dslProcessor.Deserialize(patternTextBox.Text, Languages);
                    }
                }
                catch
                {
                }

                if (patternLogger.ErrorCount == 0)
                {
                    PatternErrorsIsVisible = false;
                    PatternErrorsText      = "";
                    if (IsDeveloperMode && patternNode != null)
                    {
                        PatternJson = ustNodeJsonSerializer.Serialize(patternNode);
                        File.WriteAllText(Path.Combine(ServiceLocator.TempDirectory, "Pattern UST.json"), PatternJson);
                    }
                }
                else
                {
                    PatternErrorsIsVisible = true;
                    PatternErrorsText      = $"ERRORS ({patternLogger.ErrorCount})";
                    if (IsDeveloperMode)
                    {
                        PatternJson = "";
                    }
                }
                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    this.RaisePropertyChanged(nameof(PatternErrorsIsVisible));
                    this.RaisePropertyChanged(nameof(PatternErrorsText));
                    this.RaisePropertyChanged(nameof(PatternJson));
                });

                if (ServiceLocator.MainWindowViewModel != null)
                {
                    ServiceLocator.MainWindowViewModel.UpdateMatchings();
                }
            }
        }
Esempio n. 10
0
 public void SetLanguageFlags(LanguageFlags flag, bool value)
 {
     if (value)
     {
         _languageFlags |= flag;
     }
     else
     {
         _languageFlags &= ~flag;
     }
 }
Esempio n. 11
0
        public static Language[] GetLanguages(this LanguageFlags value)
        {
            var result = new List <Language>();

            foreach (Language language in Languages)
            {
                if (value.Is(language))
                {
                    result.Add(language);
                }
            }
            return(result.ToArray());
        }
Esempio n. 12
0
 private void ChangeLanguage(LanguageFlags languages, bool value)
 {
     if (SelectedPattern != null)
     {
         var flags = value ? (SelectedPattern.Languages | languages) : (SelectedPattern.Languages & ~languages);
         if (SelectedPattern.Languages != flags)
         {
             SelectedPattern.Languages = flags;
             CheckPattern();
             this.RaisePropertyChanged();
         }
     }
 }
Esempio n. 13
0
        public override void BuildAst(LanguageData language, ParseTree parseTree)
        {
            if (LanguageFlags.IsSet(LanguageFlags.CreateAst))
            {
                var astContext = new AstContext(language);
                astContext.DefaultNodeType           = typeof(DefaultAstNode);
                astContext.DefaultLiteralNodeType    = typeof(DefaultAstNode);
                astContext.DefaultIdentifierNodeType = typeof(DefaultAstNode);


                var astBuilder = new AstBuilder(astContext);
                astBuilder.BuildAst(parseTree);
            }
        }
Esempio n. 14
0
        /// <summary>Builds the AST for the specified language data and parse tree.</summary>
        /// <param name="language">The language data.</param>
        /// <param name="parseTree">The parse tree to build the AST against.</param>
        public override void BuildAst(LanguageData language, ParseTree parseTree)
        {
            if (!LanguageFlags.IsSet(LanguageFlags.CreateAst))
            {
                return;
            }

            var astContext = new InterpreterAstContext(language, _OperatorHandler);

            astContext.DefaultNodeType = typeof(NotSupportedNode);
            var astBuilder = new AstBuilder(astContext);

            astBuilder.BuildAst(parseTree);
        }
        public TranslationMemory(FileBasedTranslationMemory tm)
        {
            var languageFlags = new LanguageFlags();

            _sourceStatusToolTip = "Nothing processed yet";
            _targetStatusToolTip = "Nothing processed yet";
            _isSelected          = false;
            _sourceStatus        = "";
            _targetStatus        = "";
            Tm = tm;
            SourceLanguageFlagUri = languageFlags.GetImageStudioCodeByLanguageCode(tm.LanguageDirection.SourceLanguage.Name);
            TargetLanguageFlagUri = languageFlags.GetImageStudioCodeByLanguageCode(tm.LanguageDirection.TargetLanguage.Name);
            SourceLanguage        = tm.LanguageDirection.SourceLanguage.Name;
            TargetLanguage        = tm.LanguageDirection.TargetLanguage.Name;
        }
Esempio n. 16
0
        public Workflow(ISourceCodeRepository sourceCodeRepository, LanguageFlags languages,
                        IPatternsRepository patternsRepository = null, Stage stage = Stage.Match)
            : base(stage)
        {
            SourceCodeRepository = sourceCodeRepository;
            PatternsRepository   = patternsRepository ?? new DefaultPatternRepository();
            ParserConverterSets  = ParserConverterBuilder.GetParserConverterSets(languages);
            UstPatternMatcher    = new BruteForcePatternMatcher();
            IUstNodeSerializer jsonNodeSerializer = new JsonUstNodeSerializer(typeof(UstNode), typeof(PatternVarDef));
            IUstNodeSerializer dslNodeSerializer  = new DslProcessor();

            PatternConverter = new PatternConverter(new IUstNodeSerializer[] { jsonNodeSerializer, dslNodeSerializer });
            Stage            = stage;
            ThreadCount      = 1;
        }
Esempio n. 17
0
        private void WriteLanguage(IEntryLanguage language, bool isSource, XmlWriter xmlTxtWriter)
        {
            var languageFlags = new LanguageFlags();
            var fullPath      = languageFlags.GetImageStudioCodeByLanguageCode(language.Locale.Name);

            xmlTxtWriter.WriteStartElement("Language");
            xmlTxtWriter.WriteAttributeString("Name", language.Name);
            xmlTxtWriter.WriteAttributeString("CultureInfo", language.Locale.Name);
            xmlTxtWriter.WriteAttributeString("TwoLetterISOLanguageName", language.Locale.TwoLetterISOLanguageName);
            xmlTxtWriter.WriteAttributeString("IsSource", isSource.ToString());
            xmlTxtWriter.WriteAttributeString("FlagFullPath", File.Exists(fullPath) ? fullPath : string.Empty);

            WriteFields(language.Fields, xmlTxtWriter);

            WriteTerms(language, xmlTxtWriter);

            xmlTxtWriter.WriteEndElement();             //Language
        }
Esempio n. 18
0
        public static Language[] GetImpactLanguages(this LanguageFlags value)
        {
            var languages = value.GetLanguages();
            var result    = new List <Language>();

            foreach (Language language in languages)
            {
                var impactLanguageInfo = LanguageInfos.FirstOrDefault(languageInfo => languageInfo.Value.DependentLanguages.Is(language));
                if (!impactLanguageInfo.Equals(default(KeyValuePair <Language, LanguageInfo>)))
                {
                    if (!result.Contains(impactLanguageInfo.Key))
                    {
                        result.Add(impactLanguageInfo.Key);
                    }
                }
            }

            return(result.ToArray());
        }
Esempio n. 19
0
        public void JumpToTerm(IEntry entry)
        {
            var languageFlags       = new LanguageFlags();
            var entrySourceLanguage = entry.Languages[0];
            var entryTargetLanguage = entry.Languages[1];

            //get the entry by Id from all the source terms result and map the following values from the target language
            if (entrySourceLanguage != null)
            {
                SetSourceFields(languageFlags, entrySourceLanguage);
            }

            //get the entry by Id from all the target terms result and map the following values from the target language
            if (entryTargetLanguage != null)
            {
                SetTargetFields(languageFlags, entryTargetLanguage);
            }
            ShowFields();
        }
Esempio n. 20
0
        public static bool IsCaseInsensitive(this LanguageFlags languageFlags)
        {
            int flags    = (int)languageFlags;
            int language = 0;

            while (flags != 0)
            {
                if ((flags & 1) == 1)
                {
                    var isCaseInsensitive = ((Language)language).IsCaseInsensitive();
                    if (!isCaseInsensitive)
                    {
                        return(false);
                    }
                }

                flags = flags >> 1;
                ++language;
            }
            return(true);
        }
        public static void TestEnumFlags()
        {
            LanguageFlags lang = LanguageFlags.CSharp | LanguageFlags.VBNET;

            if ((lang & LanguageFlags.CSharp) == LanguageFlags.CSharp)
            {
                Console.WriteLine("lang contains at least Language.CSharp");
            }

            if (lang == LanguageFlags.CSharp)
            {
                Console.WriteLine("lang contains only the Language.CSharp");
            }

            if ((lang > 0) && ((lang & (LanguageFlags.CSharp | LanguageFlags.VBNET)) ==
                               (LanguageFlags.CSharp | LanguageFlags.VBNET)))
            {
                Console.WriteLine("lang contains at least Language.CSharp and Language.VBNET");
            }

            if ((lang > 0) && ((lang | (LanguageFlags.CSharp | LanguageFlags.VBNET)) ==
                               (LanguageFlags.CSharp | LanguageFlags.VBNET)))
            {
                Console.WriteLine("lang contains only the Language.CSharp and Language.VBNET");
            }

            lang = LanguageFlags.CSharp;
            if ((lang & LanguageFlags.CSharp) == LanguageFlags.CSharp)
            {
                //Language_1_21.CSharp      0001
                //lang                 0001
                //ANDed bit values     0001

                Console.WriteLine("CSharp found in AND comparison (CSharp value)");
            }

            lang = LanguageFlags.CSharp;
            if ((lang > 0) && (LanguageFlags.CSharp == (lang | LanguageFlags.CSharp)))
            {
                // CSharp is found using OR logic
            }

            lang = LanguageFlags.CSharp | LanguageFlags.VB6 | LanguageFlags.Cpp;
            if ((lang > 0) && (LanguageFlags.CSharp == (lang | LanguageFlags.CSharp)))
            {
                // CSharp is found using OR logic
            }

            lang = LanguageFlags.VBNET | LanguageFlags.VB6 | LanguageFlags.Cpp;
            if ((lang > 0) && (LanguageFlags.CSharp == (lang | LanguageFlags.CSharp)))
            {
                // CSharp is found using OR logic
            }

            lang = LanguageFlags.VBNET;
            if ((lang & LanguageFlags.CSharp) == LanguageFlags.CSharp)
            {
                //Language_1_21.CSharp      0001
                //lang                 0010
                //ANDed bit values     0000
                Console.WriteLine("CSharp found in AND comparison (VBNET value)");
            }

            lang = LanguageFlags.CSharp;

            if (lang == LanguageFlags.CSharp)
            {
                //Language_1_21.CSharp      0001
                //lang                 0001
                //ORed bit values      0001
            }

            if ((lang > 0) && (LanguageFlags.CSharp == (lang | LanguageFlags.CSharp)))
            {
            }

            lang = LanguageFlags.CSharp | LanguageFlags.Cpp | LanguageFlags.VB6;

            if (lang == LanguageFlags.CSharp)
            {
                //Language_1_21.CSharp      0001
                //lang                 1101
                //ORed bit values      1101
            }

            lang = LanguageFlags.CSharp | LanguageFlags.VBNET;
            if ((lang > 0) && ((lang & (LanguageFlags.CSharp | LanguageFlags.VBNET)) ==
                               (LanguageFlags.CSharp | LanguageFlags.VBNET)))
            {
                //we can test multiple bits to determine whether they are both on and all other bits are off.
                Console.WriteLine("Found just CSharp and VBNET");
            }

            // now check with Cpp added
            lang = LanguageFlags.CSharp | LanguageFlags.VBNET | LanguageFlags.Cpp;
            if ((lang > 0) && ((lang & (LanguageFlags.CSharp | LanguageFlags.VBNET)) ==
                               (LanguageFlags.CSharp | LanguageFlags.VBNET)))
            {
                //we can test multiple bits to determine whether they are at least both on regardless of what else is in there.
                Console.WriteLine("Found at least CSharp and VBNET ");
            }

            lang = LanguageFlags.CSharp | LanguageFlags.VBNET;
            if ((lang > 0) && ((lang | (LanguageFlags.CSharp | LanguageFlags.VBNET)) ==
                               (LanguageFlags.CSharp | LanguageFlags.VBNET)))
            {
                //we can determine whether at least these bits are turned on.
                Console.WriteLine("Found CSharp or VBNET");
            }

            lang = LanguageFlags.CSharp | LanguageFlags.VBNET | LanguageFlags.Cpp;
            if ((lang > 0) && ((lang | (LanguageFlags.CSharp | LanguageFlags.VBNET)) ==
                               (LanguageFlags.CSharp | LanguageFlags.VBNET)))
            {
                //we can determine whether at least these bits are turned on.
                Console.WriteLine("Found CSharp or VBNET");
            }

            if ((lang > 0) && (lang | LanguageFlags.AllLanguagesExceptCSharp) ==
                LanguageFlags.AllLanguagesExceptCSharp)
            {
                Console.WriteLine("Only CSharp is not specified");
            }
        }
Esempio n. 22
0
 public MostDetailUst(FileNode fileNode, LanguageFlags sourceLanguages)
     : base(fileNode, sourceLanguages)
 {
 }
Esempio n. 23
0
 public bool FlagIsSet(LanguageFlags flag) {
   return (LanguageFlags & flag) != 0;
 }
 public static bool IsSet(this LanguageFlags flags, LanguageFlags flag) {
   return (flags & flag) != 0;
 }
Esempio n. 25
0
        public static Dictionary <Language, ParserConverterSet> GetParserConverterSets(LanguageFlags languageFlags)
        {
            var languages = new List <Language>();

            languages.AddRange(languageFlags.GetLanguages());
            languages.AddRange(languageFlags.GetImpactLanguages());
            Dictionary <Language, ParserConverterSet> result = new Dictionary <Language, ParserConverterSet>();

            foreach (var language in languages)
            {
                result[language] = GetParserConverterSet(language);
                result[language].Converter.ConvertedLanguages &= languageFlags;
            }
            return(result);
        }
Esempio n. 26
0
 protected Ust(FileNode root, LanguageFlags sourceLanguages)
 {
     Root            = root;
     SourceLanguages = sourceLanguages;
 }
Esempio n. 27
0
 public void SetLanguageFlags(LanguageFlags flag, bool value) {
   if (value)
     _languageFlags |= flag;
   else
     _languageFlags &= ~flag;
 }
Esempio n. 28
0
 public void ResetFlags() {
   _languageFlags = LanguageFlags.None;
 }
Esempio n. 29
0
 public DslPatternRepository(string patternData, LanguageFlags languageFlags)
 {
     this.patternData   = patternData;
     this.languageFlags = languageFlags;
 }
 public bool FlagIsSet(LanguageFlags flag)
 {
     return((LanguageFlags & flag) != 0);
 }
Esempio n. 31
0
 public LanguageInfo(Language language, string extension, bool caseInsensitive, string title = null,
                     LanguageFlags dependentLanguages = LanguageFlags.None, bool haveAntlrParser = true)
     : this(language, new string[] { extension }, caseInsensitive, title, dependentLanguages, haveAntlrParser)
 {
 }
 public LanguageAttribute(LanguageFlags flags)
 {
     this.Flags = flags;
 }
Esempio n. 33
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
            var parser = new FluentCommandLineParser();

            string fileName                = "";
            string escapedPatterns         = "";
            int    threadCount             = 1;
            string languagesString         = "";
            Stage  stage                   = Stage.Match;
            int    maxStackSize            = 0;
            int    maxTimespan             = 0;
            int    memoryConsumptionMb     = 300;
            string logsDir                 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PT.PM", "Logs");
            bool   logErrors               = false;
            bool   logDebugs               = false;
            bool   showVersion             = true;
            bool   isDumpUst               = false;
            bool   isIndentedUst           = false;
            bool   isIncludeTextSpansInUst = true;
            bool   isPreprocess            = true;

            parser.Setup <string>('f', "files").Callback(f => fileName            = f.NormDirSeparator());
            parser.Setup <string>('l', "languages").Callback(l => languagesString = l);
            parser.Setup <string>('p', "patterns").Callback(p =>
                                                            escapedPatterns = p.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
                    ? p.NormDirSeparator()
                    : p.Replace('\\', '/')
                                                            );
            parser.Setup <int>('t', "threads").Callback(t => threadCount                    = t);
            parser.Setup <Stage>('s', "stage").Callback(s => stage                          = s);
            parser.Setup <int>("max-stack-size").Callback(mss => maxStackSize               = mss);
            parser.Setup <int>("max-timespan").Callback(mt => maxTimespan                   = mt);
            parser.Setup <int>('m', "memory").Callback(m => memoryConsumptionMb             = m);
            parser.Setup <string>("logs-dir").Callback(lp => logsDir                        = lp.NormDirSeparator());
            parser.Setup <bool>("log-errors").Callback(le => logErrors                      = le);
            parser.Setup <bool>("log-debugs").Callback(ld => logDebugs                      = ld);
            parser.Setup <bool>('v', "version").Callback(v => showVersion                   = v);
            parser.Setup <bool>("dump-ust").Callback(param => isDumpUst                     = param);
            parser.Setup <bool>("indented-ust").Callback(param => isIndentedUst             = param);
            parser.Setup <bool>("text-spans-ust").Callback(param => isIncludeTextSpansInUst = param);
            parser.Setup <bool>("preprocess-ust").Callback(param => isPreprocess            = param);

            ILogger logger = new ConsoleLogger();
            string  commandLineArguments = "Command line arguments" + (args.Length > 0
                ? ": " + string.Join(" ", args)
                : " are not defined.");

            var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            var argsWithUsualSlashes = args.Select(arg => arg.Replace('/', '\\')).ToArray(); // TODO: bug in FluentCommandLineParser.
            var parsingResult        = parser.Parse(argsWithUsualSlashes);

            if (!parsingResult.HasErrors)
            {
                if (isDumpUst)
                {
                    stage  = Stage.Convert;
                    logger = new DummyLogger();
                }

                try
                {
                    if (showVersion)
                    {
                        logger.LogInfo($"PT.PM version: {version}");
                    }

                    var abstractLogger = logger as AbstractLogger;
                    if (abstractLogger != null)
                    {
                        abstractLogger.LogsDir     = logsDir;
                        abstractLogger.IsLogErrors = logErrors;
                        abstractLogger.IsLogDebugs = logDebugs;
                        abstractLogger.LogInfo(commandLineArguments);
                    }

                    if (string.IsNullOrEmpty(fileName) && string.IsNullOrEmpty(escapedPatterns))
                    {
                        throw new ArgumentException("at least --files or --patterns parameter required");
                    }

                    if (string.IsNullOrEmpty(fileName))
                    {
                        stage = Stage.Patterns;
                    }

                    LanguageFlags         languages = LanguageExt.ParseLanguages(languagesString);
                    ISourceCodeRepository sourceCodeRepository;
                    if (Directory.Exists(fileName))
                    {
                        sourceCodeRepository = new FilesAggregatorCodeRepository(fileName, LanguageExt.GetExtensions(languages));
                    }
                    else
                    {
                        sourceCodeRepository = new FileCodeRepository(fileName);
                    }
                    logger.SourceCodeRepository = sourceCodeRepository;

                    IPatternsRepository patternsRepository;
                    if (string.IsNullOrEmpty(escapedPatterns))
                    {
                        patternsRepository = new DefaultPatternRepository();
                    }
                    else if (escapedPatterns.EndsWith(".json"))
                    {
                        patternsRepository = new FilePatternsRepository(escapedPatterns);
                    }
                    else
                    {
                        var patterns = StringCompressorEscaper.UnescapeDecompress(escapedPatterns);
                        patternsRepository = new JsonPatternsRepository(patterns);
                    }

                    var workflow = new Workflow(sourceCodeRepository, languages, patternsRepository, stage)
                    {
                        Logger                 = logger,
                        ThreadCount            = threadCount,
                        MaxStackSize           = maxStackSize,
                        MaxTimespan            = maxTimespan,
                        MemoryConsumptionMb    = memoryConsumptionMb,
                        IsIncludePreprocessing = isPreprocess
                    };
                    var            stopwatch      = Stopwatch.StartNew();
                    WorkflowResult workflowResult = workflow.Process();
                    stopwatch.Stop();

                    if (isDumpUst)
                    {
                        DumpUst(isIndentedUst, isIncludeTextSpansInUst, workflowResult);
                    }

                    if (stage != Stage.Patterns)
                    {
                        logger.LogInfo("Scan completed.");
                        if (stage == Stage.Match)
                        {
                            logger.LogInfo($"{"Matches count: ",-22} {workflowResult.MatchingResults.Count()}");
                        }
                    }
                    else
                    {
                        logger.LogInfo("Patterns checked.");
                    }
                    logger.LogInfo($"{"Errors count: ",-22} {workflowResult.ErrorCount}");
                    var workflowLoggerHelper = new WorkflowLoggerHelper(logger, workflowResult);
                    workflowLoggerHelper.LogStatistics();
                    logger.LogInfo($"{"Time elapsed:",-22} {stopwatch.Elapsed}");
                }
                catch (Exception ex)
                {
                    if (logger != null)
                    {
                        var abstractLogger = logger as AbstractLogger;
                        if (abstractLogger != null)
                        {
                            abstractLogger.IsLogErrors = true;
                        }
                        logger.LogError(ex);
                    }
                }
                finally
                {
                    var disposableLogger = logger as IDisposable;
                    if (disposableLogger != null)
                    {
                        disposableLogger.Dispose();
                    }
                }
            }
            else
            {
                Console.WriteLine($"PT.PM version: {version}");
                Console.WriteLine(commandLineArguments);
                Console.WriteLine("Command line arguments processing error: " + parsingResult.ErrorText);
            }
        }
Esempio n. 34
0
 public static bool IsSet(this LanguageFlags flags, LanguageFlags flag)
 {
     return((flags & flag) != 0);
 }
Esempio n. 35
0
 public static bool IsSet(this LanguageFlags enumValue, LanguageFlags flag)
 {
     return (enumValue & flag) != 0;
 }
Esempio n. 36
0
 public UstNode Deserialize(string data, LanguageFlags sourceLanguage)
 {
     return(JsonConvert.DeserializeObject <UstNode>(data, astJsonConverter, stringEnumConverter));
 }
Esempio n. 37
0
 public void SetLanguageFlags(LanguageFlags flag) {
   SetLanguageFlags(flag, true); 
 }