Custom suppression of exsisting rules or remove a violation

Apr 6, 2011 at 1:03 PM

We are currently using StyleCop 4.3.

Essentially we want to write some some code to parse the source code of a violation. If we think this does not violate it then we want to remove the violation.

We don’t want to remove a rule at a Project level as the rule/s still apply.

Its to get round some problems we are have merging some code from Japan. Bascically we want to ignore any code they put in, the other problem is its a shared code base so turning the rule off is not an option. i.e. They could start a comment like // [Japan] and we could ignore it.

The other way would be to pre-check a violation before it is added but I can’t see away of doing this.

We have already implemented some custom rules, we would like to extend our Dll to incorporate the rule suppression of existing rules that cause a violation. We don't really want to modify the StyleCop codebase.

Developer
Apr 6, 2011 at 6:34 PM

Hi Rick,

Are you talking about rule suppressions?
http://stylecop.codeplex.com/wikipage?title=Rule%20Suppressions

You could suppress a number of rules in an entire class.

Best regards,
Oleg Shuruev

Apr 6, 2011 at 7:45 PM
Edited Apr 6, 2011 at 7:45 PM

No, I am aware of this and we don't want to suppress for a whole class/function.

We are looking for away to do this:

private void CheckComments(CsDocument document)
        {
            // Loop through all of the tokens in the document.
            for (Node<CsToken> tokenNode = document.Tokens.First; tokenNode != null; tokenNode = tokenNode.Next)
            {
                if (tokenNode.Value.Text.Contains("[Japan"))
                {
                    var violation = document.DocumentContents.Violations.FirstOrDefault(v => v.Line == tokenNode.Value.LineNumber);
                    if (violation != null)
                    {
                        // Just ignore this one and some how remove it.
                    }
                }               
            }
        }

Developer
Apr 6, 2011 at 9:00 PM

Now I understand what you mean.

Without StyleCop modification, you could create your own fork and update it when needed (pulling changes from the main branch).
In this fork you could add some late processing of all violations encountered, removing some of them by your own criteria.

As a shortcoming, you will have to use "your own StyleCop", not the original one.

Another idea is to create "hooking" assembly (as a plug-in) which would inject own code in StyleCop assembly during run-time.
Of course, it is a real hack and require some efforts to do this.

Best regards,
Oleg Shuruev

Coordinator
Apr 6, 2011 at 9:21 PM

Hi,

If you can figure out from the StyleCop source what you would need changing to support this from an addin then I'd consider putting it in.

Maybe if we put a hook point before we throw the violations so you get a call back and therefore a chance to perhaps return false and stop the violation being thrown? Thoughts? Oleg, your thoughts too please.

Apr 6, 2011 at 9:33 PM

Thanks shuruev, I was beginning to suspect it is a code change.

Hi andyr

Some kind of call back hook/event would be useful or even an interface to inheit from i.e.

interface IViolationValidator
{
        bool IsValid(Violation);
}

Using simple reflection from our existing Dll which has custom rules in this could be called prior to adding the violation. If IsValid return true it does not add the violation.

I have downloaded the latest source if I get some time I will take a look.

Many thanks

Apr 6, 2011 at 9:38 PM
Edited Apr 6, 2011 at 9:42 PM

This is a snipet of the current code we are using in an addin assembly:

/// <summary>
    /// The OmronStyleCopRules class implements the Omron specific Rules for StyleCop.
    /// </summary>
    [SourceAnalyzer(typeof(CsParser))]
    public class OmronStyleCopRules : Microsoft.StyleCop.SourceAnalyzer 
    {
        #region Methods

        #region FxCop SourceAnalyzer Overrides

        /// <summary>
        /// StyleCop calls this method when analyzing a source code document.
        /// The custom rules defined in this class will be run against the
        /// specified document.
        /// </summary>
        /// <param name="document">Then document to be analyzed.</param>
        public override void AnalyzeDocument(CodeDocument document)
        {            
            CsDocument csharpDocument = document as CsDocument;

            // first check to ensure that the RootElement property is not null, indicating that the code file is empty. 
            // In most cases the code should also verify that the contents of the file have not been auto-generated 
            // by a tool, which is done by checking the value of the CsDocument.RootElement.Generated property. 
            // Generally, auto-generated code should not be checked for style errors, as it was generated by a tool
            // and not written manually. 
            if (csharpDocument.RootElement != null && !csharpDocument.RootElement.Generated)
            {
                // Run the custom rules against the code.
                csharpDocument.WalkDocument(
                                            new CodeWalkerElementVisitor<object>(this.VisitElement), 
                                            new CodeWalkerStatementVisitor<object>(this.VisitStatement),
                                            new CodeWalkerExpressionVisitor<object>(this.VisitExpression));

                // Walk though the entire document looking for multi-line comments
                this.CheckComments(csharpDocument);
            }
        }

        private bool VisitElement(CsElement element, CsElement parentElement, object context)
        {
            if (!element.Generated)
            {
                // Layout Rules
                this.CheckAttributeLayout(element);

                // Maintainability Rules
                this.CheckNumberOfPublicMethodsInClass(element);
                this.CheckMethodLength(element);
            }

            return true;
        }

        private bool VisitStatement(Statement statement, Expression parentExpression, Statement parentStatement, CsElement parentElement, object context)
        {
            // Usage Rules
            this.CheckLocking(statement, parentElement);

            return true;
        }

        private bool VisitExpression(Expression expression, Expression parentExpression, Statement parentStatement, CsElement parentElement, object context)
        {
            // Usage Rules
            this.CheckForMonitorEnter(expression, parentElement);

            return true;
        }

..... etc
Coordinator
Apr 6, 2011 at 10:08 PM

Hi,

Forgive me if I've missed something please, but how does that code help?

Apr 6, 2011 at 10:51 PM

I have added the code above just as reference, this is the current code we have in our addin.

The last thing  AnalyzeDocument calls is CheckComments, which is where I can then evaluate the Violations. However they have already been added.

So I am considering a mechanism that will allow me to remove them or an event that gets fired prior to adding violations.

Admitedly I am in the dark at the moment as I have not looked at the StyleCop source code.

I am only looking for a work around for comments at present but I am sure as the project progresses there will be other violations that we may want to parse and suppress.