Ejemplo n.º 1
0
        /// <summary>
        /// Main program entry.
        /// </summary>
        public static void Main(string[] args)
        {
            StyleCopConsole console = new StyleCopConsole(
                null,
                false,
                null,
                new List<string>(new[] { basePath }),
                true);

            Configuration configuration = new Configuration(null);
            CodeProject project = new CodeProject(0, basePath, configuration);

            console.Core.Environment.AddSourceCode(project, sourceFile, null);

            List<CodeProject> projects = new List<CodeProject>();
            projects.Add(project);

            console.OutputGenerated += OnOutputGenerated;
            console.ViolationEncountered += OnViolationEncountered;
            console.Start(projects, true);
            console.OutputGenerated -= OnOutputGenerated;
            console.ViolationEncountered -= OnViolationEncountered;
            console.Dispose();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
        /// <summary>
        /// Give list of files and projects to be treated by Stylecop
        /// </summary>
        /// <param name="console">
        /// A <see cref="StyleCopConsole"/> which define the console which will treat the files
        /// </param>
        /// <returns>
        /// A <see cref="List<CodeProject>"/> which contains all the project to be treated by stylecop
        /// </returns>
        protected override List<CodeProject> GetCodeProjectList(StyleCopConsole console)
        {
            Configuration configuration = new Configuration(new string[] { "DEBUG" });
            List<CodeProject> projects = new List<CodeProject>();
            CodeProject project = new CodeProject(IdeApp.ProjectOperations.CurrentSelectedProject.BaseDirectory.GetHashCode(), IdeApp.ProjectOperations.CurrentSelectedProject.BaseDirectory, configuration);

            // Add each source file to this project.
            console.Core.Environment.AddSourceCode(project, IdeApp.Workbench.ActiveDocument.FileName, null);
            projects.Add(project);

            return projects;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the CodeProject class.
        /// </summary>
        /// <param name="key">The unique key for the project.</param>
        /// <param name="location">The location where the project is contained.</param>
        /// <param name="configuration">The active configuration.</param>
        public CodeProject(int key, string location, Configuration configuration)
        {
            Param.Ignore(key);
            Param.Ignore(location);
            Param.RequireNotNull(configuration, "configuration");

            this.key = key;
            this.configuration = configuration;

            if (location != null)
            {
                // Trim the path and convert it to lowercase characters
                // so that we can do string matches and find other files and
                // projects under the same location.
                this.location = StyleCopCore.CleanPath(location);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Executes this MSBuild task, based on the input values passed in by the MSBuild engine.
        /// </summary>
        /// <returns>Returns true if there were no errors, false otherwise.</returns>
        public override bool Execute()
        {
            // Clear the violation count and set the violation limit for the project.
            this.violationCount = 0;
            this.violationLimit = 0;

            if (this.maxViolationCount != null)
            {
                if (!int.TryParse(this.maxViolationCount.ItemSpec, out this.violationLimit))
                {
                    this.violationLimit = 0;
                }
            }

            if (this.violationLimit == 0)
            {
                this.violationLimit = DefaultViolationLimit;
            }

            // Get settings files (if null or empty use null filename so it uses right default).
            string overrideSettingsFileName = null;
            if (this.inputOverrideSettingsFile != null && this.inputOverrideSettingsFile.ItemSpec.Length > 0)
            {
                overrideSettingsFileName = this.inputOverrideSettingsFile.ItemSpec;
            }

            // Get addin paths.
            List<string> addinPaths = new List<string>();
            foreach (ITaskItem addinPath in this.inputAdditionalAddinPaths)
            {
                addinPaths.Add(addinPath.GetMetadata("FullPath"));
            }

            // Create the StyleCop console.
            using (StyleCopConsole console = new StyleCopConsole(
                overrideSettingsFileName,
                this.inputCacheResults,
                this.outputFile == null ? null : this.outputFile.ItemSpec,
                addinPaths,
                true))
            {
                // Create the configuration.
                Configuration configuration = new Configuration(this.inputDefineConstants);

                string projectFullPath = null;
                if (this.inputProjectFullPath != null)
                {
                    projectFullPath = this.inputProjectFullPath.GetMetadata("FullPath");
                }

                if (!string.IsNullOrEmpty(projectFullPath))
                {
                    // Create a CodeProject object for these files.
                    CodeProject project = new CodeProject(
                        projectFullPath.GetHashCode(),
                        projectFullPath,
                        configuration);

                    // Add each source file to this project.
                    foreach (ITaskItem inputSourceFile in this.inputSourceFiles)
                    {
                        console.Core.Environment.AddSourceCode(project, inputSourceFile.ItemSpec, null);
                    }

                    try
                    {
                        // Subscribe to events
                        console.OutputGenerated += this.OnOutputGenerated;
                        console.ViolationEncountered += this.OnViolationEncountered;

                        // Analyze the source files
                        CodeProject[] projects = new CodeProject[] { project };
                        console.Start(projects, this.inputForceFullAnalysis);
                    }
                    finally
                    {
                        // Unsubscribe from events
                        console.OutputGenerated -= this.OnOutputGenerated;
                        console.ViolationEncountered -= this.OnViolationEncountered;
                    }
                }
            }

            return this.succeeded;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a StyleCop report.
        /// </summary>
        /// <param name="outputXmlFile">
        /// The fully-qualified path to write the output of the report to.
        /// </param>
        public void Create(string outputXmlFile)
        {
            // Create a StyleCop configuration specifying the configuration
            // symbols to use for this report.
            var cfg = new Configuration(
                this.ProcessorSymbols != null
                    ?
                        this.ProcessorSymbols.ToArray()
                    :
                        null);

            // Create a new StyleCop console used to do the check.
            var scc = new StyleCopConsole(
                this.StyleCopSettingsFile,
                true,
                GetViolationsFile(outputXmlFile),
                this.AddInDirectories,
                true);

            // Process solution files
            if (this.SolutionFiles != null)
            {
                foreach (var i in this.SolutionFiles)
                {
                    this.AddSolutionFile(i);
                }
            }

            // Process project files
            if (this.ProjectFiles != null)
            {
                foreach (var i in this.ProjectFiles)
                {
                    this.AddProjectFile(
                        i,
                        null);
                }
            }

            // Process directories
            if (this.Directories != null)
            {
                foreach (var i in this.Directories)
                {
                    this.AddDirectory(i);
                }
            }

            // Process files
            if (this.Files != null)
            {
                foreach (var i in this.Files)
                {
                    this.AddFile(
                        i,
                        null,
                        null);
                }
            }

            // Create a list of code projects from the data set.
            var cps = this.Report.Projects.Select(
                r => new CodeProject(
                         r.ID,
                         r.Location,
                         cfg)).ToList();

            // Add the source code files to the style cop checker
            foreach (var f in this.Report.SourceCodeFiles)
            {
                // ReSharper disable AccessToModifiedClosure
                var cp = cps.SingleOrDefault(i => i.Key == f.CodeProjectID);
                scc.Core.Environment.AddSourceCode(
                    cp,
                    f.Path,
                    null);

                // ReSharper restore AccessToModifiedClosure
            }

            if (this.OutputGenerated != null)
            {
                scc.OutputGenerated += this.OutputGenerated;
            }

            scc.ViolationEncountered += this.ViolationEncountered;

            scc.Start(
                cps,
                true);

            if (this.OutputGenerated != null)
            {
                scc.OutputGenerated -= this.OutputGenerated;
            }

            scc.ViolationEncountered -= this.ViolationEncountered;
            scc.Dispose();

            // Write the report to the output XML file.
            this.Report.WriteXml(outputXmlFile);

            if (!string.IsNullOrEmpty(this.TransformFile))
            {
                this.Transform(outputXmlFile);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Compares the given configuration with the given list of flags.
        /// </summary>
        /// <param name="configuration">The configuration object.</param>
        /// <param name="flagList">The list of flags.</param>
        /// <returns>Returns true if the configuration is identical to the flag list, or
        /// false otherwise.</returns>
        private static bool CompareCachedConfiguration(Configuration configuration, string flagList)
        {
            Param.AssertNotNull(configuration, "configuration");
            Param.AssertNotNull(flagList, "flagList");

            // Split the flags.
            string[] flags = new string[0];
            string trimmedList = flagList.Trim();
            if (trimmedList.Length > 0)
            {
                flags = flagList.Split(';');
            }

            // If the counts are different, the configurations are different.
            if (flags.Length != configuration.Flags.Count)
            {
                return false;
            }

            // Make sure each of the flags exists in the configuration.
            foreach (string flag in flags)
            {
                if (!configuration.Contains(flag))
                {
                    return false;
                }
            }

            return true;
        }
Ejemplo n.º 7
0
 private bool GetIfElsePreprocessorDirectives(Microsoft.StyleCop.SourceCode sourceCode, Symbol preprocessorSymbol, Configuration configuration, int startIndex, string type, out bool skip)
 {
     bool flag = false;
     skip = false;
     if (type == "if")
     {
         this.conditionalDirectives.Push(false);
         Expression expression = CodeParser.GetConditionalPreprocessorBodyExpression(this.parser, sourceCode, preprocessorSymbol, startIndex);
         if (expression == null)
         {
             throw new SyntaxException(sourceCode, preprocessorSymbol.LineNumber);
         }
         skip = !this.EvaluateConditionalDirectiveExpression(sourceCode, expression, configuration);
         return flag;
     }
     if (type == "elif")
     {
         if (this.conditionalDirectives.Count == 0)
         {
             throw new SyntaxException(sourceCode, preprocessorSymbol.LineNumber);
         }
         if (this.conditionalDirectives.Peek())
         {
             skip = true;
             return flag;
         }
         Expression expression2 = CodeParser.GetConditionalPreprocessorBodyExpression(this.parser, sourceCode, preprocessorSymbol, startIndex);
         if (expression2 != null)
         {
             skip = !this.EvaluateConditionalDirectiveExpression(sourceCode, expression2, configuration);
         }
         return flag;
     }
     if (type == "else")
     {
         if (this.conditionalDirectives.Count == 0)
         {
             throw new SyntaxException(sourceCode, preprocessorSymbol.LineNumber);
         }
         if (this.conditionalDirectives.Peek())
         {
             skip = true;
         }
         return flag;
     }
     return true;
 }
Ejemplo n.º 8
0
        internal Symbol GetSymbol(Microsoft.StyleCop.SourceCode sourceCode, Configuration configuration, bool evaluatePreprocessors)
        {
            Symbol number = null;
            char character = this.codeReader.Peek();
            switch (character)
            {
                case '\t':
                case ' ':
                    return this.GetWhitespace();

                case '\n':
                case '\r':
                    return this.GetNewLine();

                case '!':
                case '%':
                case '&':
                case '*':
                case '+':
                case '-':
                case ':':
                case '<':
                case '=':
                case '>':
                case '?':
                case '^':
                case '|':
                case '~':
                    return this.GetOperatorSymbol(character);

                case '"':
                case '\'':
                    return this.GetString();

                case '#':
                    return this.GetPreprocessorDirectiveSymbol(sourceCode, configuration, evaluatePreprocessors);

                case '(':
                    return this.CreateAndMovePastSymbol("(", SymbolType.OpenParenthesis);

                case ')':
                    return this.CreateAndMovePastSymbol(")", SymbolType.CloseParenthesis);

                case ',':
                    return this.CreateAndMovePastSymbol(",", SymbolType.Comma);

                case '.':
                    number = this.GetNumber();
                    if (number == null)
                    {
                        number = this.GetOperatorSymbol('.');
                    }
                    return number;

                case '/':
                    number = this.GetComment();
                    if (number == null)
                    {
                        number = this.GetOperatorSymbol('/');
                    }
                    return number;

                case ';':
                    return this.CreateAndMovePastSymbol(";", SymbolType.Semicolon);

                case '@':
                    return this.GetLiteral();

                case '[':
                    return this.CreateAndMovePastSymbol("[", SymbolType.OpenSquareBracket);

                case ']':
                    return this.CreateAndMovePastSymbol("]", SymbolType.CloseSquareBracket);

                case '{':
                    return this.CreateAndMovePastSymbol("{", SymbolType.OpenCurlyBracket);

                case '}':
                    return this.CreateAndMovePastSymbol("}", SymbolType.CloseCurlyBracket);

                case '\0':
                    return number;
            }
            UnicodeCategory unicodeCategory = char.GetUnicodeCategory(character);
            if ((unicodeCategory != UnicodeCategory.Format) && (unicodeCategory != UnicodeCategory.OtherNotAssigned))
            {
                number = this.GetNumber();
                if (number == null)
                {
                    number = this.GetOtherSymbol(this.source);
                }
            }
            return number;
        }
Ejemplo n.º 9
0
 private bool EvaluateConditionalDirectiveExpression(Microsoft.StyleCop.SourceCode sourceCode, Expression expression, Configuration configuration)
 {
     bool flag2;
     bool flag3;
     switch (expression.ExpressionType)
     {
         case ExpressionType.Parenthesized:
         {
             ParenthesizedExpression expression6 = expression as ParenthesizedExpression;
             return this.EvaluateConditionalDirectiveExpression(sourceCode, expression6.InnerExpression, configuration);
         }
         case ExpressionType.Relational:
         {
             RelationalExpression expression4 = expression as RelationalExpression;
             flag2 = this.EvaluateConditionalDirectiveExpression(sourceCode, expression4.LeftHandSide, configuration);
             flag3 = this.EvaluateConditionalDirectiveExpression(sourceCode, expression4.RightHandSide, configuration);
             if (expression4.OperatorType != RelationalExpression.Operator.EqualTo)
             {
                 if (expression4.OperatorType != RelationalExpression.Operator.NotEqualTo)
                 {
                     throw new SyntaxException(sourceCode, expression.Tokens.First.Value.LineNumber);
                 }
                 return (flag2 != flag3);
             }
             return (flag2 == flag3);
         }
         case ExpressionType.Unary:
         {
             UnaryExpression expression5 = expression as UnaryExpression;
             if (expression5.OperatorType != UnaryExpression.Operator.Not)
             {
                 throw new SyntaxException(sourceCode, expression.Tokens.First.Value.LineNumber);
             }
             return !this.EvaluateConditionalDirectiveExpression(sourceCode, expression5.Value, configuration);
         }
         case ExpressionType.ConditionalLogical:
         {
             ConditionalLogicalExpression expression3 = expression as ConditionalLogicalExpression;
             flag2 = this.EvaluateConditionalDirectiveExpression(sourceCode, expression3.LeftHandSide, configuration);
             flag3 = this.EvaluateConditionalDirectiveExpression(sourceCode, expression3.RightHandSide, configuration);
             if (expression3.OperatorType == ConditionalLogicalExpression.Operator.And)
             {
                 return (flag2 && flag3);
             }
             return (flag2 || flag3);
         }
         case ExpressionType.Literal:
         {
             LiteralExpression expression2 = expression as LiteralExpression;
             if (expression2.Text == "false")
             {
                 return false;
             }
             if (expression2.Text == "true")
             {
                 return true;
             }
             if ((this.undefines != null) && this.undefines.ContainsKey(expression2.Text))
             {
                 return false;
             }
             return (((this.defines != null) && this.defines.ContainsKey(expression2.Text)) || ((configuration != null) && configuration.Contains(expression2.Text)));
         }
     }
     throw new SyntaxException(sourceCode, expression.Tokens.First.Value.LineNumber);
 }
Ejemplo n.º 10
0
        private void CheckForConditionalCompilationDirective(Microsoft.StyleCop.SourceCode sourceCode, Symbol preprocessorSymbol, Configuration configuration)
        {
            int num;
            int num2;
            Symbol symbol;
            string preprocessorDirectiveType = CsParser.GetPreprocessorDirectiveType(preprocessorSymbol, out num);
            switch (preprocessorDirectiveType)
            {
                case "define":
                    this.GetDefinePreprocessorDirective(sourceCode, preprocessorSymbol, num);
                    return;

                case "undef":
                    this.GetUndefinePreprocessorDirective(sourceCode, preprocessorSymbol, num);
                    return;

                case "endif":
                    if (this.conditionalDirectives.Count == 0)
                    {
                        throw new SyntaxException(sourceCode, preprocessorSymbol.LineNumber);
                    }
                    this.conditionalDirectives.Pop();
                    return;

                default:
                    bool flag;
                    if (this.GetIfElsePreprocessorDirectives(sourceCode, preprocessorSymbol, configuration, num, preprocessorDirectiveType, out flag))
                    {
                        return;
                    }
                    if (!flag)
                    {
                        if (this.conditionalDirectives.Count == 0)
                        {
                            throw new SyntaxException(sourceCode, preprocessorSymbol.LineNumber);
                        }
                        this.conditionalDirectives.Pop();
                        this.conditionalDirectives.Push(true);
                        return;
                    }
                    num2 = 0;
                    goto Label_0085;
            }
            Label_0085:
            do
            {
                symbol = this.GetSymbol(sourceCode, configuration, false);
                if (symbol == null)
                {
                    throw new SyntaxException(sourceCode, preprocessorSymbol.LineNumber);
                }
            }
            while (symbol.SymbolType != SymbolType.PreprocessorDirective);
            preprocessorDirectiveType = CsParser.GetPreprocessorDirectiveType(symbol, out num);
            if (preprocessorDirectiveType == "if")
            {
                num2++;
                goto Label_0085;
            }
            if ((num2 > 0) && (preprocessorDirectiveType == "endif"))
            {
                num2--;
                goto Label_0085;
            }
            if ((num2 != 0) || ((!(preprocessorDirectiveType == "elif") && !(preprocessorDirectiveType == "else")) && !(preprocessorDirectiveType == "endif")))
            {
                goto Label_0085;
            }
            this.marker.Index = symbol.Location.StartPoint.Index;
            this.marker.IndexOnLine = symbol.Location.StartPoint.IndexOnLine;
            this.marker.LineNumber = symbol.Location.StartPoint.LineNumber;
        }
Ejemplo n.º 11
0
 internal List<Symbol> GetSymbols(Microsoft.StyleCop.SourceCode sourceCode, Configuration configuration)
 {
     List<Symbol> list = new List<Symbol>();
     while (true)
     {
         Symbol item = this.GetSymbol(sourceCode, configuration, true);
         if (item == null)
         {
             return list;
         }
         list.Add(item);
     }
 }
Ejemplo n.º 12
0
 private Symbol GetPreprocessorDirectiveSymbol(Microsoft.StyleCop.SourceCode sourceCode, Configuration configuration, bool evaluate)
 {
     StringBuilder text = new StringBuilder();
     this.AdvanceToEndOfLine(text);
     if (text.Length == 1)
     {
         throw new SyntaxException(Microsoft.StyleCop.CSharp.Strings.UnexpectedEndOfFile);
     }
     CodeLocation location = new CodeLocation(this.marker.Index, (this.marker.Index + text.Length) - 1, this.marker.IndexOnLine, (this.marker.IndexOnLine + text.Length) - 1, this.marker.LineNumber, this.marker.LineNumber);
     Symbol preprocessorSymbol = new Symbol(text.ToString(), SymbolType.PreprocessorDirective, location);
     this.marker.Index += text.Length;
     this.marker.IndexOnLine += text.Length;
     if (evaluate && (configuration != null))
     {
         this.CheckForConditionalCompilationDirective(sourceCode, preprocessorSymbol, configuration);
     }
     return preprocessorSymbol;
 }
Ejemplo n.º 13
0
 private static bool CompareCachedConfiguration(Configuration configuration, string flagList)
 {
     string[] strArray = new string[0];
     if (flagList.Trim().Length > 0)
     {
         strArray = flagList.Split(new char[] { ';' });
     }
     if (strArray.Length != configuration.Flags.Count)
     {
         return false;
     }
     foreach (string str2 in strArray)
     {
         if (!configuration.Contains(str2))
         {
             return false;
         }
     }
     return true;
 }