Domanda

I try to code a custom rule in stylecop for java style curvy brackets like this :

public void myfunction(int argument) {
body();
//.......
}

My actual code is :

    public override void AnalyzeDocument(CodeDocument document) {
                var csharpDocument = (CsDocument)document;

                for (var tokenNode = csharpDocument.Tokens.First; tokenNode != null; tokenNode = tokenNode.Next) {

               if (tokenNode.Value.CsTokenType == CsTokenType.OpenCurlyBracket) {
                        if (tokenNode.Value.LineNumber == tokenNode.Previous.Value.LineNumber
                            || tokenNode.Value.LineNumber == tokenNode.Next.Value.LineNumber) {
                            this.AddViolation(tokenNode.Value,
                                              tokenNode.Value.LineNumber,
                                                "OpenCurlyBracketBadLocation");
                        }
                    }

               if (tokenNode.Value.CsTokenType == CsTokenType.CloseCurlyBracket) {
                        if (tokenNode.Value.LineNumber != tokenNode.Previous.Value.LineNumber
                            || tokenNode.Value.LineNumber == tokenNode.Next.Value.LineNumber) {
                            this.AddViolation(tokenNode.Value,
                                              tokenNode.Value.LineNumber,
                                                "CloseCurlyBracketBadLocation");
                        }
                    }

                }

But this line :

this.AddViolation(tokenNode.Value,
                  tokenNode.Value.LineNumber,
                  "CloseCurlyBracketBadLocation");

Doesn't compile because function arguments type don't match. First argument need an ICodeElement and I have a CsToken... But in SDK this way it used... So anyone know a solution ? Or maybe a better way to do it ?

È stato utile?

Soluzione

The reason the first argument is an ICodeElement is that the target of a violation must be something against which a SuppressMessageAttribute may be applied. You could climb the token's Parent chain until you find an ICodeElement, but that wouldn't be particularly efficient. An approach that would be better aligned with the intended usage of the SDK would be to use the WalkDocument method to visit elements (as is done in the built-in StyleCop.CSharp.LayoutRules analyzer that implements StyleCop's own curly brace verification rules).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top