コード例 #1
0
        public List <int> RetrieveLanguageIdsFromRules()
        {
            List <int> list = new List <int>();

            foreach (KeyValuePair <int, ICategoryDefinition> categoryDefinition in Categories)
            {
                if (!categoryDefinition.Value.Enabled)
                {
                    continue;
                }

                foreach (KeyValuePair <int, IRuleDefinition> ruleDefinition in categoryDefinition.Value.Rules)
                {
                    if (!ruleDefinition.Value.Enabled)
                    {
                        continue;
                    }

                    IConfigurationProxy configProxy     = ProxyHome.Instance.RetrieveConfigurationProxy(ConfigKeyKeeper.Instance.AccessKey);
                    IRuleDeclaration    ruleDeclaration = configProxy.RuleDeclarationFromCategoryIdAndRuleId(categoryDefinition.Value.CategoryDeclarationReferenceId, ruleDefinition.Value.RuleDeclarationReferenceId);

                    foreach (KeyValuePair <int, ILanguageDeclaration> pair in ruleDeclaration.Languages)
                    {
                        ILanguageDeclaration languageReference = pair.Value;
                        if (!list.Contains(languageReference.Id))
                        {
                            list.Add(languageReference.Id);
                        }
                    }
                }
            }
            return(list);
        }
コード例 #2
0
        public PsiRuleSignature(IRuleDeclaration ruleDeclaration)
        {
            var parameters = ruleDeclaration.Parameters;

            if (parameters != null)
            {
                var child = parameters.FirstChild;
                while (child != null)
                {
                    var ruleName = child as IRuleName;
                    if (ruleName != null)
                    {
                        var declaredElement = ruleName.RuleNameReference.Resolve().DeclaredElement;
                        if (declaredElement != null)
                        {
                            myParameters.Add(declaredElement);
                        }
                        else
                        {
                            var candidates = ruleName.RuleNameReference.Resolve().Result.Candidates;
                            foreach (var candidate in candidates)
                            {
                                if (candidate is IRuleDeclaration)
                                {
                                    myParameters.Add(candidate);
                                    break;
                                }
                            }
                        }
                    }
                    child = child.NextSibling;
                }
            }
        }
コード例 #3
0
        public static IRuleDeclaration RuleDeclarationMapper(ICategoryDeclaration parentDeclaration, Model.RuleDeclaration ruleDeclaration)
        {
            IRuleDeclaration rule = null;

            try
            {
                rule = ConfigurationComponentFactory().ConfigurationFactory <IRuleDeclaration>(typeof(IRuleDeclaration));
            }
            catch (Exception e)
            {
                throw new DataAccessComponentException(null, -1, "Configuration proxy factory failure - unable to create an instance of " + typeof(IRuleDeclaration) + "?", e);
            }


            try
            {
                rule.Id                = ruleDeclaration.Id;
                rule.Name              = ruleDeclaration.Name;
                rule.Description       = ruleDeclaration.Description;
                rule.Expression        = ruleDeclaration.Expression;
                rule.Severity          = RuleSeverityMapper.Int2RuleSeverity(ruleDeclaration.Severity);
                rule.ParentDeclaration = parentDeclaration;

                foreach (var language in ruleDeclaration.LanguageDeclaration)
                {
                    rule.Languages.Add(language.Id, LanguageDeclarationMapper(language));
                }
            }
            catch (Exception e)
            {
                throw new DataAccessComponentException(null, -1, "Mapping process failure?", e);
            }
            return(rule);
        }
コード例 #4
0
 private void VisitRuleDeclaration(IRuleDeclaration ruleDeclaration)
 {
   string name = ruleDeclaration.DeclaredName;
   int offset = ruleDeclaration.GetNavigationRange().TextRange.StartOffset;
   IPsiSourceFile psiSourceFile = ruleDeclaration.GetSourceFile();
   mySymbols.Add(new PsiRuleSymbol(name, offset, psiSourceFile));
 }
コード例 #5
0
        private void VisitRuleDeclaration(IRuleDeclaration ruleDeclaration)
        {
            string         name          = ruleDeclaration.DeclaredName;
            int            offset        = ruleDeclaration.GetNavigationRange().TextRange.StartOffset;
            IPsiSourceFile psiSourceFile = ruleDeclaration.GetSourceFile();

            mySymbols.Add(new PsiRuleSymbol(name, offset, psiSourceFile));
        }
コード例 #6
0
 public override void VisitRuleDeclaration(IRuleDeclaration ruleDeclaration, IHighlightingConsumer consumer)
 {
   IRuleBody body = ruleDeclaration.Body;
   ITreeNode child = PsiTreeUtil.GetFirstChild<IRuleName>(body);
   var ruleName = child as IRuleName;
   if (ruleName != null)
   {
     if (ruleName.GetText().Equals(ruleDeclaration.DeclaredName))
     {
       consumer.AddHighlighting(new LeftRecursionWarning(ruleName), File);
     }
   }
   base.VisitRuleDeclaration(ruleDeclaration, consumer);
 }
コード例 #7
0
        public override void VisitRuleDeclaration(IRuleDeclaration ruleDeclaration, IHighlightingConsumer consumer)
        {
            IRuleBody body     = ruleDeclaration.Body;
            ITreeNode child    = PsiTreeUtil.GetFirstChild <IRuleName>(body);
            var       ruleName = child as IRuleName;

            if (ruleName != null)
            {
                if (ruleName.GetText().Equals(ruleDeclaration.DeclaredName))
                {
                    consumer.AddHighlighting(new LeftRecursionWarning(ruleName), File);
                }
            }
            base.VisitRuleDeclaration(ruleDeclaration, consumer);
        }
コード例 #8
0
        public CreatePsiRuleTarget(PsiRuleReference reference)
        {
            myElement = reference.GetTreeNode();
            string name = reference.GetName();

            var node = myElement.NextSibling;

            while (node != null)
            {
                if (!node.IsWhitespaceToken())
                {
                    if (!(node is IRuleParameters))
                    {
                        break;
                    }
                    var child = node.FirstChild;
                    while (child != null)
                    {
                        if (!child.IsWhitespaceToken())
                        {
                            if (child is IRuleBraceParameters)
                            {
                                myHasBraceParameters = true;
                            }
                            if (child is IRuleBracketParameters)
                            {
                                CollectVariableParameters(child as IRuleBracketParameters);
                            }
                        }
                        child = child.NextSibling;
                    }
                    break;
                }
                node = node.NextSibling;
            }


            if (name != "")
            {
                myDeclaration = PsiElementFactory.GetInstance(myElement.GetPsiModule()).CreateRuleDeclaration(name, myHasBraceParameters, myVariableParameters);
            }
            else
            {
                myDeclaration = null;
            }

            Anchor = myElement.GetContainingNode <IRuleDeclaration>();
        }
コード例 #9
0
        public override string VisitRuleDeclaration(IRuleDeclaration ruleDeclarationParam, FormattingStageContext context)
        {
            string parentIndent = GetParentIndent(context.Parent);

            if (context.RightChild is IRuleBody)
            {
                return(parentIndent + StandartIndent + StandartIndent);
            }
            var token = context.RightChild as ITokenNode;

            if ((token != null) && ((token.GetTokenType() == PsiTokenType.COLON) || (token.GetTokenType() == PsiTokenType.SEMICOLON)))
            {
                return(parentIndent + StandartIndent);
            }
            return(myIndentCache.GetNodeIndent(ruleDeclarationParam));
        }
コード例 #10
0
        public override IEnumerable <string> VisitRuleDeclaration(IRuleDeclaration ruleDeclarationParam, PsiFmtStageContext context)
        {
            if (context.LeftChild is IModifier)
            {
                return(new[] { " " });
            }
            if (context.RightChild is IRoleGetterParameter)
            {
                return(new[] { " " });
            }
            if (context.RightChild is IRuleBracketTypedParameters)
            {
                return(new[] { " " });
            }

            return(new[] { "\r\n" });
        }
コード例 #11
0
 public static Model.RuleDeclaration RuleDeclarationMapper(IRuleDeclaration declaration, CodeAnalyzerContainer context)
 {
     Model.RuleDeclaration ruleDeclaration = context.RuleDeclaration.SingleOrDefault(r => r.Id == declaration.Id);
     if (ruleDeclaration == null)
     {
         return new Model.RuleDeclaration
                {
                    Name                = declaration.Name,
                    Description         = declaration.Description,
                    Severity            = (int)declaration.Severity,
                    Expression          = declaration.Expression,
                    CategoryDeclaration = CategoryDeclarationMapper(declaration.ParentDeclaration, context),
                }
     }
     ;
     return(ruleDeclaration);
 }
コード例 #12
0
ファイル: Scope.cs プロジェクト: ghord/SharpExpress
        public Scope CreateChildScope(IRuleDeclaration rule)
        {
            var builder = DeclaredIdentifiers.ToBuilder();

            //TODO: declarations
            //TODO: type labels (?)

            foreach (var population in rule.Populations)
            {
                builder[population.Name] = population;
            }

            foreach (var variable in rule.LocalVariables)
            {
                builder[variable.Name] = variable;
            }

            return(new Scope(builder.ToImmutable(), DeclaredDataTypes));
        }
コード例 #13
0
    public CreatePsiRuleTarget(PsiRuleReference reference)
    {
      myReference = reference;
      myElement = reference.GetTreeNode();
      string name = reference.GetName();

      var node = myElement.NextSibling;
      while (node != null)
      {
        if (!node.IsWhitespaceToken())
        {
          if (!(node is IRuleParameters))
          {
            break;
          }
          var child = node.FirstChild;
          while (child != null)
          {
            if (!child.IsWhitespaceToken())
            {
              if (child is IRuleBraceParameters)
              {
                myHasBraceParameters = true;
              }
              if (child is IRuleBracketParameters)
              {
                CollectVariableParameters(child as IRuleBracketParameters);
              }
            }
            child = child.NextSibling;
          }
          break;
        }
        node = node.NextSibling;
      }


      myDeclaration = PsiElementFactory.GetInstance(myElement.GetPsiModule()).CreateRuleDeclaration(name, myHasBraceParameters, myVariableParameters);

      Anchor = myElement.GetContainingNode<IRuleDeclaration>();
    }
コード例 #14
0
            public void ConfigurationFactory_AllSupportedTypes_ReturnsValidObject()
            {
                ConfigurationComponentFactory factory = ConfigurationComponentFactory.Instance;

                factory.InitializeComponentAccessPermissions(AppManager);

                Debug.Assert(factory != null, "proxy != null");
                ILanguageDeclaration languageDeclaration = factory.ConfigurationFactory <ILanguageDeclaration>(typeof(ILanguageDeclaration));
                IRuleDeclaration     ruleDeclaration     = factory.ConfigurationFactory <IRuleDeclaration>(typeof(IRuleDeclaration));
                IProjectDefinition   projectDefinition   = factory.ConfigurationFactory <IProjectDefinition>(typeof(IProjectDefinition));
                ICategoryDefinition  categoryDefinition  = factory.ConfigurationFactory <ICategoryDefinition>(typeof(ICategoryDefinition));
                IRuleDefinition      ruleDefinition      = factory.ConfigurationFactory <IRuleDefinition>(typeof(IRuleDefinition));
                IDirectoryDefinition directoryDefinition = factory.ConfigurationFactory <IDirectoryDefinition>(typeof(IDirectoryDefinition));
                IFileDefinition      fileDefinition      = factory.ConfigurationFactory <IFileDefinition>(typeof(IFileDefinition));

                Assert.IsNotNull(languageDeclaration);
                Assert.IsNotNull(ruleDeclaration);
                Assert.IsNotNull(projectDefinition);
                Assert.IsNotNull(categoryDefinition);
                Assert.IsNotNull(ruleDefinition);
                Assert.IsNotNull(directoryDefinition);
                Assert.IsNotNull(fileDefinition);
            }
コード例 #15
0
ファイル: XmlFactory.cs プロジェクト: ClaesRyom/CodeAnalyzer
        public static XmlNode CreateRuleDefinitionXmlNode(XmlDocument doc, IRuleDeclaration declaration, IRuleDefinition definition)
        {
            // <RuleDefinition Enabled="true" RefName="No explicit exception identifier" RefId="{6C021885-99A7-48D7-97DB-C1FE3242182A}" >
            //   <Description><CDATA ELEMENT /></Description>
            // </RuleDefinition>
            XmlNode      ruleDefinitionXmlNode   = doc.CreateNode(XmlNodeType.Element, "RuleDefinition", null);
            XmlNode      descriptionXmlNode      = doc.CreateNode(XmlNodeType.Element, "Description", null);
            XmlNode      projectRelationXmlNode  = doc.CreateNode(XmlNodeType.Element, "ProjectDefinitionRelation", null);
            XmlNode      categoryRelationXmlNode = doc.CreateNode(XmlNodeType.Element, "CategoryDeclarationRelation", null);
            XmlAttribute idAttrib      = doc.CreateAttribute("Id");
            XmlAttribute enabledAttrib = doc.CreateAttribute("Enabled");
            XmlAttribute refNameAttrib = doc.CreateAttribute("RefName");
            XmlAttribute refIdAttrib   = doc.CreateAttribute("RefId");

            idAttrib.Value      = definition.Id.ToString();
            enabledAttrib.Value = definition.Enabled.ToString();
            refNameAttrib.Value = definition.RuleDeclarationReferenceName;
            refIdAttrib.Value   = definition.RuleDeclarationReferenceId + "";

            ruleDefinitionXmlNode.Attributes.Append(idAttrib);
            ruleDefinitionXmlNode.Attributes.Append(enabledAttrib);
            ruleDefinitionXmlNode.Attributes.Append(refNameAttrib);
            ruleDefinitionXmlNode.Attributes.Append(refIdAttrib);

            XmlCDataSection cdataNameNode = doc.CreateCDataSection(declaration.Description);

            descriptionXmlNode.AppendChild(cdataNameNode);

            projectRelationXmlNode.InnerText  = definition.ParentDefinition.ParentDefinition.Name;
            categoryRelationXmlNode.InnerText = declaration.ParentDeclaration.Name;

            ruleDefinitionXmlNode.AppendChild(descriptionXmlNode);
            ruleDefinitionXmlNode.AppendChild(projectRelationXmlNode);
            ruleDefinitionXmlNode.AppendChild(categoryRelationXmlNode);
            return(ruleDefinitionXmlNode);
        }
コード例 #16
0
        private bool IsCustomImpl(IRuleDeclaration ruleDeclaration)
        {
            var options = ruleDeclaration.Options;

            if (options == null)
            {
                return(false);
            }
            var child = options.FirstChild;

            while (child != null)
            {
                var optionDefinition = child as IOptionDefinition;
                if (optionDefinition != null)
                {
                    if (optionDefinition.OptionName.GetText() == "customParseFunction")
                    {
                        return(true);
                    }
                }
                child = child.NextSibling;
            }
            return(false);
        }
コード例 #17
0
        private void CreateRuleDefinitionsFile()
        {
            IConfigurationProxy proxy = ProxyHome.Instance.RetrieveConfigurationProxy(OutputKeyKeeper.Instance.AccessKey);

            XmlNode     node;
            XmlDocument doc = XmlFactory.CreateXmlFile(Ids.XSLT_DIR, Ids.ALL_RULE_DEFINITIONS_XSLT_FILE, "RuleDefinitions", out node);

            //<RuleDefinitions>
            //  <RuleDefinition />
            //</RuleDefinitions>
            foreach (KeyValuePair <int, IProjectDefinition> projectDefinition in proxy.Projects())
            {
                foreach (KeyValuePair <int, IRuleDefinition> pair in proxy.ProjectRules(projectDefinition.Value.Id))
                {
                    IRuleDefinition ruleDefinition = pair.Value;

                    IRuleDeclaration ruleDeclaration = proxy.RuleDeclarationFromRuleId(ruleDefinition.RuleDeclarationReferenceId);
                    node.AppendChild(XmlFactory.CreateRuleDefinitionXmlNode(doc, ruleDeclaration, ruleDefinition));
                    doc.AppendChild(node);
                }
            }

            XmlFactory.SaveXmlFile(Path.Combine(OutputRootDir, Ids.OUTPUT_DIR, Ids.ALL_RULE_DEFINITIONS_XML_FILE), doc);
        }
コード例 #18
0
 public PsiRuleInserter(IRuleDeclaration declarationToAdd, ICreationTarget target)
 {
   myDeclarationToAdd = declarationToAdd;
   myTarget = target;
 }
コード例 #19
0
 public RearrangeableRuleDeclaration([NotNull] IRuleDeclaration declaration)
 {
     myRuleDeclaration = declaration;
 }
コード例 #20
0
 public static Model.RuleDeclaration RuleDeclarationMapper(IRuleDeclaration declaration, CodeAnalyzerContainer context)
 {
     Model.RuleDeclaration ruleDeclaration = context.RuleDeclaration.SingleOrDefault(r => r.Id == declaration.Id);
     if (ruleDeclaration == null)
         return new Model.RuleDeclaration
         {
             Name                = declaration.Name,
             Description         = declaration.Description,
             Severity            = (int)declaration.Severity,
             Expression          = declaration.Expression,
             CategoryDeclaration = CategoryDeclarationMapper(declaration.ParentDeclaration, context),
         };
     return ruleDeclaration;
 }
コード例 #21
0
ファイル: XmlFactory.cs プロジェクト: ClaesRyom/CodeAnalyzer
        public static XmlNode CreateMatchXmlNode(XmlDocument doc, int id, IMatch match)
        {
            //throw new NotImplementedException();

            // <Match Id="" Name="" Open="">
            //   <File />
            //   <LineNumber />
            //   <RegExpName><CDATA ELEMENT></RegExpName>
            //   <RegExpDescription><CDATA ELEMENT></RegExpDescription>
            //   <RegExpExpression><CDATA ELEMENT></RegExpExpression>
            //   <RegExpSummary><CDATA ELEMENT></RegExpSummary>
            //   <Severity Value="">Fatal|Critical|Warning|Info</Severity>
            // </Match>

            XmlNode matchNode           = doc.CreateNode(XmlNodeType.Element, "Match", null);
            XmlNode projectNode         = doc.CreateNode(XmlNodeType.Element, "Project", null);
            XmlNode categoryNode        = doc.CreateNode(XmlNodeType.Element, "Category", null);
            XmlNode rootDirectoryNode   = doc.CreateNode(XmlNodeType.Element, "RootDirectory", null);
            XmlNode filenameNode        = doc.CreateNode(XmlNodeType.Element, "FileName", null);
            XmlNode lineNumberNode      = doc.CreateNode(XmlNodeType.Element, "LineNumber", null);
            XmlNode ruleNameNode        = doc.CreateNode(XmlNodeType.Element, "RuleName", null);
            XmlNode ruleDescriptionNode = doc.CreateNode(XmlNodeType.Element, "RuleDescription", null);
            XmlNode ruleExpressionNode  = doc.CreateNode(XmlNodeType.Element, "RuleExpression", null);
            XmlNode codeExtractNode     = doc.CreateNode(XmlNodeType.Element, "CodeExtract", null);
            XmlNode severityNode        = doc.CreateNode(XmlNodeType.Element, "Severity", null);

            IConfigurationProxy cfgProxy = ProxyHome.Instance.RetrieveConfigurationProxy(OutputKeyKeeper.Instance.AccessKey);

            // Match node...
            XmlAttribute idAttrib   = doc.CreateAttribute("Id");
            XmlAttribute nameAttrib = doc.CreateAttribute("Name");
            XmlAttribute openAttrib = doc.CreateAttribute("Open");

            idAttrib.Value   = id + "";
            nameAttrib.Value = match.Filename;
            openAttrib.Value = "false";

            matchNode.Attributes.Append(idAttrib);
            matchNode.Attributes.Append(nameAttrib);
            matchNode.Attributes.Append(openAttrib);


            IProjectDefinition   projectDefinition   = cfgProxy.Project(match.ProjectDefinitionRef.Id);
            ICategoryDeclaration categoryDeclaration = cfgProxy.CategoryDeclaration(match.RuleDeclarationRef.ParentDeclaration.Id);
            IRuleDeclaration     ruleDeclaration     = cfgProxy.RuleDeclarationFromRuleId(match.RuleDeclarationRef.Id);


            // File node and Line number node...
            projectNode.InnerText       = projectDefinition.Name;
            categoryNode.InnerText      = categoryDeclaration.Name;
            rootDirectoryNode.InnerText = match.RootDirectoryPath;
            filenameNode.InnerText      = match.Filename;
            lineNumberNode.InnerText    = match.LineNumber + "";


            // RegExpName node...
            XmlCDataSection cdataRegExpNameNode = doc.CreateCDataSection(ruleDeclaration.Name);

            ruleNameNode.AppendChild(cdataRegExpNameNode);

            // RegExpDescription node...
            XmlCDataSection cdataRegExpDescriptionNode = doc.CreateCDataSection(ruleDeclaration.Description);

            ruleDescriptionNode.AppendChild(cdataRegExpDescriptionNode);

            // RegExpExpression node...
            XmlCDataSection cdataRegExpExpression = doc.CreateCDataSection(ruleDeclaration.Expression);

            ruleExpressionNode.AppendChild(cdataRegExpExpression);

            // RegExpSummary node...
            XmlCDataSection cdataRegExpSummary = doc.CreateCDataSection(match.CodeExtract);

            codeExtractNode.AppendChild(cdataRegExpSummary);

            // Severity node...
            XmlAttribute severityValueAttrib = doc.CreateAttribute("Value");

            severityValueAttrib.Value = (int)match.Severity + "";
            severityNode.InnerText    = match.Severity.ToString();
            severityNode.Attributes.Append(severityValueAttrib);

            // Add all nodes to the 'node' given in the arguments.
            matchNode.AppendChild(projectNode);
            matchNode.AppendChild(categoryNode);
            matchNode.AppendChild(ruleNameNode);
            matchNode.AppendChild(ruleDescriptionNode);
            matchNode.AppendChild(ruleExpressionNode);
            matchNode.AppendChild(rootDirectoryNode);
            matchNode.AppendChild(filenameNode);
            matchNode.AppendChild(lineNumberNode);
            matchNode.AppendChild(codeExtractNode);
            matchNode.AppendChild(severityNode);
            return(matchNode);
        }
コード例 #22
0
        private void StartSearch()
        {
            IConfigurationProxy cfgProxy = ProxyHome.Instance.RetrieveConfigurationProxy(EngineKeyKeeper.Instance.AccessKey);

            List <LinkFile2Language> bindedProj2LanguageFileType = null;

            // Retrieve project definitions from the Configuration component.
            Dictionary <int, IProjectDefinition> projects = cfgProxy.Projects();

            // Let's run through all the projects and do our thing.
            foreach (KeyValuePair <int, IProjectDefinition> pair in projects)
            {
                IProjectDefinition project = pair.Value;
                if (!project.Enabled)
                {
                    continue; // Project definition was disabled.
                }
                // Here we create the language file type containers for all the languages
                // that are in play for the current project.
                bindedProj2LanguageFileType = BindProjectLanguagesToFileTypes(project);


                // Find all files associated with the language file extension in
                // the current file container 'linkFile2Language'.
                foreach (LinkFile2Language linkFile2Language in bindedProj2LanguageFileType)
                {
                    foreach (IDirectoryDefinition dir in project.Directories)
                    {
                        if (!dir.Enabled)
                        {
                            continue;
                        }

                        if (!Directory.Exists(dir.Path))
                        {
                            string s = string.Format("No directory found ({0})", dir.Path);
                            throw new IOException(s);
                        }

                        IRootDirectoryStatistics rds = ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).CreateRootDirectory(project.Id);
                        rds.RootDirectory = dir.Path;

                        FileSearchEngine fileSearchEngine = new FileSearchEngine(dir, linkFile2Language.Language.Extension);
                        fileSearchEngine.ExcludeDirs            = project.ExcludedDirectories.Select(d => d).ToList();
                        fileSearchEngine.IncludeSubDirsInSearch = true;
                        fileSearchEngine.Search();

                        // Adding all the files found with the extention given by
                        // 'linkFile2Language.Language.Extension' to the file container 'linkFile2Language'.
                        linkFile2Language.Filenames.AddRange(fileSearchEngine.FileFoundDuringSearch);

                        // Adding all the files found to the StatisticsComponentProxy.
                        ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.Files, fileSearchEngine.FileCount);
                        rds.Filenames.AddRange(fileSearchEngine.FileFoundDuringSearch);
                    }
                }


                TimeTracker tt = new TimeTracker("Execution of regular expression on each file.");
                tt.Start();


                IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(EngineKeyKeeper.Instance.AccessKey);

                // Let's execute each regular expression from each rule that are enabled
                // and should be applied to the current language.
                foreach (LinkFile2Language linkFile2Language in bindedProj2LanguageFileType)
                {
                    foreach (KeyValuePair <int, ICategoryDefinition> categoryDefinition in project.Categories)
                    {
                        if (!categoryDefinition.Value.Enabled)
                        {
                            continue;
                        }


                        foreach (KeyValuePair <int, IRuleDefinition> ruleDefinition in categoryDefinition.Value.Rules)
                        {
                            if (!ruleDefinition.Value.Enabled)
                            {
                                continue;
                            }


                            // Let's check whether or not the current 'rule' is associated with the current 'language'?
                            IRuleDeclaration ruleDeclaration = cfgProxy.RuleDeclarationFromCategoryIdAndRuleId(categoryDefinition.Value.CategoryDeclarationReferenceId, ruleDefinition.Value.RuleDeclarationReferenceId);
                            foreach (KeyValuePair <int, ILanguageDeclaration> languageRef in ruleDeclaration.Languages)
                            {
                                if (languageRef.Key == linkFile2Language.Language.Id)
                                {
                                    // The language reference on the current rule is identical to the current 'linkFile2Language'
                                    // meaning that we should execute the regular expression from the current rule on all the
                                    // files placed in the 'linkFile2Language':
                                    IMatchInfoReferences references = matchProxy.MatchesFactory <IMatchInfoReferences>(typeof(IMatchInfoReferences));

                                    references.ProjectDefinitionReference   = project;
                                    references.CategoryDeclarationReference = cfgProxy.CategoryDeclaration(categoryDefinition.Value.CategoryDeclarationReferenceId);
                                    references.CategoryDefinitionReference  = categoryDefinition.Value;
                                    references.RuleDeclarationReference     = ruleDeclaration;
                                    references.RuleDefinitionReference      = ruleDefinition.Value;
                                    references.LanguageDeclarationReference = languageRef.Value;

                                    Parallel.ForEach(linkFile2Language.Filenames, file => ExecuteRegularExpressionsOnBuffer(file, references, ruleDeclaration));
                                }
                            }
                        }
                    }
                }

                tt.Stop("We are done.");
                tt.ToLog(Log);
            }
        }
コード例 #23
0
        public static IRuleDeclaration AddToTarget(IRuleDeclaration declarationToAdd, ICreationTarget target)
        {
            var inserter = new PsiRuleInserter(declarationToAdd, target);

            return(inserter.InsertRule());
        }
コード例 #24
0
        public static XmlNode CreateRuleDeclarationXmlNode(XmlDocument doc, IRuleDeclaration declaration)
        {
            // <RuleDeclaration Name="Static classes" Id="{A971681E-5E9A-4DD8-8870-35A4341752F4}">
              //   <Description><CDATA ELEMENT></Description>
              //   <Severity>Critical</Severity>
              //   <Expression><CDATA ELEMENT></Expression>
              //   <AppliesTo>
              //     <Language RefName="C#" RefId="{C224974D-E493-42C2-960F-DBE6BB64C946}" />
              //   </AppliesTo>
              // </RuleDeclaration>
              XmlNode      declarationNode = doc.CreateNode(XmlNodeType.Element, "RuleDeclaration", null);
              XmlNode      descriptionNode = doc.CreateNode(XmlNodeType.Element, "Description",     null);
              XmlNode      severityNode    = doc.CreateNode(XmlNodeType.Element, "Severity",        null);
              XmlNode      expressionNode  = doc.CreateNode(XmlNodeType.Element, "Expression",      null);
              XmlNode      appliesToNode   = doc.CreateNode(XmlNodeType.Element, "AppliesTo",       null);
              XmlAttribute severityAttrib  = doc.CreateAttribute("Value");
              XmlAttribute nameAttrib      = doc.CreateAttribute("Name");
              XmlAttribute idAttrib        = doc.CreateAttribute("Id");

              idAttrib.Value   = declaration.Id.ToString();
              nameAttrib.Value = declaration.Name;

              declarationNode.Attributes.Append(idAttrib);
              declarationNode.Attributes.Append(nameAttrib);

              XmlCDataSection descriptionCData = doc.CreateCDataSection(declaration.Description);
              descriptionNode.AppendChild(descriptionCData);

              severityAttrib.Value   = (int)declaration.Severity + "";
              severityNode.InnerText = declaration.Severity + "";
              severityNode.Attributes.Append(severityAttrib);

              XmlCDataSection expressionCData = doc.CreateCDataSection(declaration.Expression);
              expressionNode.AppendChild(expressionCData);

              foreach (KeyValuePair<int, ILanguageDeclaration> pair in declaration.Languages)
              {
            XmlNode      languageNode  = doc.CreateNode(XmlNodeType.Element, "Language", null);
            XmlAttribute refNameAttrib = doc.CreateAttribute("RefName");
            XmlAttribute refIdAttrib   = doc.CreateAttribute("RefId");

            refIdAttrib.Value   = pair.Value.Id + "";
            refNameAttrib.Value = pair.Value.Name;

            languageNode.Attributes.Append(refIdAttrib);
            languageNode.Attributes.Append(refNameAttrib);

            appliesToNode.AppendChild(languageNode);
              }

              declarationNode.AppendChild(descriptionNode);
              declarationNode.AppendChild(severityNode);
              declarationNode.AppendChild(expressionNode);
              declarationNode.AppendChild(appliesToNode);
              return declarationNode;
        }
コード例 #25
0
        private void ExecuteRegularExpressionsOnBuffer(string filename, IMatchInfoReferences references, IRuleDeclaration ruleDeclaration)
        {
            const string summary = "summary";

              string buffer = LoadFile(filename);

              if (string.IsNullOrEmpty(buffer))
            return;

            int lastLineNum;
            string[] lines = buffer.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            lastLineNum = (lines != null && lines.Length >= 1) ? lines.Length - 1 : 0;

            #region Statistics: update/increment the total number of lines and total number of whitespace lines in tested/scanned files.
            if (!ProxyHome.Instance.CheckCache(filename))
            {
            ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalNumberOfLinesInFiles, lastLineNum);
            ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalNumberOfWhitespaceLinesInFiles, lines.Count(string.IsNullOrWhiteSpace));
                ProxyHome.Instance.InsertInCache(filename);
            }
            #endregion

            string correctedRegExp = "(?<" + summary + ">" + ruleDeclaration.Expression + ")";

            IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(EngineKeyKeeper.Instance.AccessKey);
              IBatch      batch      = ProxyHome.Instance.RetrieveExecutionIdentification(EngineKeyKeeper.Instance.AccessKey);

              MatchCollection matches = Regex.Matches(buffer, correctedRegExp, RegexOptions.IgnoreCase);
              foreach (System.Text.RegularExpressions.Match match in matches)
              {

            int startIndx = match.Index;
            int endIndx   = startIndx + match.Groups[summary].Value.Length;

            int accumulation    = 0;
            int startLineNumber = 0;
            int endLineNumber   = 0;
            foreach (string line in lines)
            {
              if (accumulation < startIndx)
              {
              // This is for finding the line number where the match starts...
            accumulation += line.Length + Environment.NewLine.Length;
                        endLineNumber = startLineNumber++;
              }
              else
              {
            if (accumulation < endIndx)
            {
              // This is for finding the line number where the match ends...
              accumulation += line.Length + Environment.NewLine.Length;

                if ((endLineNumber + 1) < lastLineNum)
                {
                    endLineNumber++;
                }
                else
                {
                    endLineNumber = lastLineNum;

                                // Extract the code from the actual file...
                                string matchExtract = ExtractTheMatchAndSurroundings(lines, buffer.Length, ++startLineNumber, ++endLineNumber);

                                // Create the match and insert it into the MatchProxy...
                                GenerateMatch(matchProxy, references, batch, filename, startLineNumber, matchExtract);

                                // Let's update the statistics manager about the match we just found.
                                ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(RuleSeverityMapper.Severity2CounterId((RuleSeverity)ruleDeclaration.Severity));
                            }
            }
            else
            {
                            // Extract the code from the actual file...
                            string matchExtract = ExtractTheMatchAndSurroundings(lines, buffer.Length, ++startLineNumber, ++endLineNumber);

                            // Create the match and insert it into the MatchProxy...
                            GenerateMatch(matchProxy, references, batch, filename, startLineNumber, matchExtract);

                            // Let's update the statistics manager about the match we just found.
                            ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(RuleSeverityMapper.Severity2CounterId((RuleSeverity)ruleDeclaration.Severity));
              break;
            }
              }
            }
              }
        }
コード例 #26
0
        public static XmlNode CreateRuleDefinitionXmlNode(XmlDocument doc, IRuleDeclaration declaration, IRuleDefinition definition)
        {
            // <RuleDefinition Enabled="true" RefName="No explicit exception identifier" RefId="{6C021885-99A7-48D7-97DB-C1FE3242182A}" >
              //   <Description><CDATA ELEMENT /></Description>
              // </RuleDefinition>
              XmlNode ruleDefinitionXmlNode   = doc.CreateNode(XmlNodeType.Element, "RuleDefinition", null);
              XmlNode descriptionXmlNode      = doc.CreateNode(XmlNodeType.Element, "Description", null);
              XmlNode projectRelationXmlNode  = doc.CreateNode(XmlNodeType.Element, "ProjectDefinitionRelation", null);
              XmlNode categoryRelationXmlNode = doc.CreateNode(XmlNodeType.Element, "CategoryDeclarationRelation", null);
              XmlAttribute idAttrib           = doc.CreateAttribute("Id");
              XmlAttribute enabledAttrib      = doc.CreateAttribute("Enabled");
              XmlAttribute refNameAttrib      = doc.CreateAttribute("RefName");
              XmlAttribute refIdAttrib        = doc.CreateAttribute("RefId");

              idAttrib.Value      = definition.Id.ToString();
              enabledAttrib.Value = definition.Enabled.ToString();
              refNameAttrib.Value = definition.RuleDeclarationReferenceName;
              refIdAttrib.Value   = definition.RuleDeclarationReferenceId + "";

              ruleDefinitionXmlNode.Attributes.Append(idAttrib);
              ruleDefinitionXmlNode.Attributes.Append(enabledAttrib);
              ruleDefinitionXmlNode.Attributes.Append(refNameAttrib);
              ruleDefinitionXmlNode.Attributes.Append(refIdAttrib);

              XmlCDataSection cdataNameNode = doc.CreateCDataSection(declaration.Description);
              descriptionXmlNode.AppendChild(cdataNameNode);

              projectRelationXmlNode.InnerText  = definition.ParentDefinition.ParentDefinition.Name;
              categoryRelationXmlNode.InnerText = declaration.ParentDeclaration.Name;

              ruleDefinitionXmlNode.AppendChild(descriptionXmlNode);
              ruleDefinitionXmlNode.AppendChild(projectRelationXmlNode);
              ruleDefinitionXmlNode.AppendChild(categoryRelationXmlNode);
              return ruleDefinitionXmlNode;
        }
コード例 #27
0
    public static IRuleDeclaration AddToTarget(IRuleDeclaration declarationToAdd, ICreationTarget target)
    {

      var inserter = new PsiRuleInserter(declarationToAdd, target);
      return inserter.InsertRule();
    }
コード例 #28
0
ファイル: XmlFactory.cs プロジェクト: ClaesRyom/CodeAnalyzer
        public static XmlNode CreateRuleDeclarationXmlNode(XmlDocument doc, IRuleDeclaration declaration)
        {
            // <RuleDeclaration Name="Static classes" Id="{A971681E-5E9A-4DD8-8870-35A4341752F4}">
            //   <Description><CDATA ELEMENT></Description>
            //   <Severity>Critical</Severity>
            //   <Expression><CDATA ELEMENT></Expression>
            //   <AppliesTo>
            //     <Language RefName="C#" RefId="{C224974D-E493-42C2-960F-DBE6BB64C946}" />
            //   </AppliesTo>
            // </RuleDeclaration>
            XmlNode      declarationNode = doc.CreateNode(XmlNodeType.Element, "RuleDeclaration", null);
            XmlNode      descriptionNode = doc.CreateNode(XmlNodeType.Element, "Description", null);
            XmlNode      severityNode    = doc.CreateNode(XmlNodeType.Element, "Severity", null);
            XmlNode      expressionNode  = doc.CreateNode(XmlNodeType.Element, "Expression", null);
            XmlNode      appliesToNode   = doc.CreateNode(XmlNodeType.Element, "AppliesTo", null);
            XmlAttribute severityAttrib  = doc.CreateAttribute("Value");
            XmlAttribute nameAttrib      = doc.CreateAttribute("Name");
            XmlAttribute idAttrib        = doc.CreateAttribute("Id");

            idAttrib.Value   = declaration.Id.ToString();
            nameAttrib.Value = declaration.Name;

            declarationNode.Attributes.Append(idAttrib);
            declarationNode.Attributes.Append(nameAttrib);

            XmlCDataSection descriptionCData = doc.CreateCDataSection(declaration.Description);

            descriptionNode.AppendChild(descriptionCData);


            severityAttrib.Value   = (int)declaration.Severity + "";
            severityNode.InnerText = declaration.Severity + "";
            severityNode.Attributes.Append(severityAttrib);


            XmlCDataSection expressionCData = doc.CreateCDataSection(declaration.Expression);

            expressionNode.AppendChild(expressionCData);

            foreach (KeyValuePair <int, ILanguageDeclaration> pair in declaration.Languages)
            {
                XmlNode      languageNode  = doc.CreateNode(XmlNodeType.Element, "Language", null);
                XmlAttribute refNameAttrib = doc.CreateAttribute("RefName");
                XmlAttribute refIdAttrib   = doc.CreateAttribute("RefId");

                refIdAttrib.Value   = pair.Value.Id + "";
                refNameAttrib.Value = pair.Value.Name;

                languageNode.Attributes.Append(refIdAttrib);
                languageNode.Attributes.Append(refNameAttrib);

                appliesToNode.AppendChild(languageNode);
            }


            declarationNode.AppendChild(descriptionNode);
            declarationNode.AppendChild(severityNode);
            declarationNode.AppendChild(expressionNode);
            declarationNode.AppendChild(appliesToNode);
            return(declarationNode);
        }
コード例 #29
0
 public PsiRuleInserter(IRuleDeclaration declarationToAdd, ICreationTarget target)
 {
     myDeclarationToAdd = declarationToAdd;
     myTarget           = target;
 }
コード例 #30
0
        private void ExecuteRegularExpressionsOnBuffer(string filename, IMatchInfoReferences references, IRuleDeclaration ruleDeclaration)
        {
            const string summary = "summary";

            string buffer = LoadFile(filename);

            if (string.IsNullOrEmpty(buffer))
            {
                return;
            }

            int lastLineNum;

            string[] lines = buffer.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            lastLineNum = (lines != null && lines.Length >= 1) ? lines.Length - 1 : 0;


            #region Statistics: update/increment the total number of lines and total number of whitespace lines in tested/scanned files.
            if (!ProxyHome.Instance.CheckCache(filename))
            {
                ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalNumberOfLinesInFiles, lastLineNum);
                ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(CounterIds.TotalNumberOfWhitespaceLinesInFiles, lines.Count(string.IsNullOrWhiteSpace));
                ProxyHome.Instance.InsertInCache(filename);
            }
            #endregion


            string correctedRegExp = "(?<" + summary + ">" + ruleDeclaration.Expression + ")";


            IMatchProxy matchProxy = ProxyHome.Instance.RetrieveMatchProxy(EngineKeyKeeper.Instance.AccessKey);
            IBatch      batch      = ProxyHome.Instance.RetrieveExecutionIdentification(EngineKeyKeeper.Instance.AccessKey);

            MatchCollection matches = Regex.Matches(buffer, correctedRegExp, RegexOptions.IgnoreCase);
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                int startIndx = match.Index;
                int endIndx   = startIndx + match.Groups[summary].Value.Length;

                int accumulation    = 0;
                int startLineNumber = 0;
                int endLineNumber   = 0;
                foreach (string line in lines)
                {
                    if (accumulation < startIndx)
                    {
                        // This is for finding the line number where the match starts...
                        accumulation += line.Length + Environment.NewLine.Length;
                        endLineNumber = startLineNumber++;
                    }
                    else
                    {
                        if (accumulation < endIndx)
                        {
                            // This is for finding the line number where the match ends...
                            accumulation += line.Length + Environment.NewLine.Length;

                            if ((endLineNumber + 1) < lastLineNum)
                            {
                                endLineNumber++;
                            }
                            else
                            {
                                endLineNumber = lastLineNum;

                                // Extract the code from the actual file...
                                string matchExtract = ExtractTheMatchAndSurroundings(lines, buffer.Length, ++startLineNumber, ++endLineNumber);

                                // Create the match and insert it into the MatchProxy...
                                GenerateMatch(matchProxy, references, batch, filename, startLineNumber, matchExtract);

                                // Let's update the statistics manager about the match we just found.
                                ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(RuleSeverityMapper.Severity2CounterId((RuleSeverity)ruleDeclaration.Severity));
                            }
                        }
                        else
                        {
                            // Extract the code from the actual file...
                            string matchExtract = ExtractTheMatchAndSurroundings(lines, buffer.Length, ++startLineNumber, ++endLineNumber);

                            // Create the match and insert it into the MatchProxy...
                            GenerateMatch(matchProxy, references, batch, filename, startLineNumber, matchExtract);

                            // Let's update the statistics manager about the match we just found.
                            ProxyHome.Instance.RetrieveStatisticsProxy(EngineKeyKeeper.Instance.AccessKey).IncrementCounter(RuleSeverityMapper.Severity2CounterId((RuleSeverity)ruleDeclaration.Severity));
                            break;
                        }
                    }
                }
            }
        }