Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Sonar provides a quick and easy way to add new coding rules directly via the web interface for certain languages (C, C#, C++, Cobol, Flex, JavaScript, PL/I, PL/SQL, Python and PythonVB.NET).

The rules have to be written in XPath to navigate the Abstract Syntax Tree (AST). For each language, an SSLR Toolkit is provided to navigate the AST. This SSLR Toolkit is a standalone application that displays the AST for a provided piece of code source. So that you quickly get the nodes names and attributes to write your XPath expression from your code sample. The proper SSLR Toolkit can be downloaded from the language plugin page. So, finally, knowing the XPath language is the only prerequisite. A lot of tutorials on XPath can be found online (see http://www.w3schools.com/xpath/ for example).

...

An SSLR Toolkit is provided by each language supporting XPath to get a representation of this AST. Here's the AST for our JavaScript sample:

Image RemovedImage Added

The XPath language provides a way to write coding rules by navigating this AST.

...

  1. Login as an administrator
  2. Go to Configuration > Quality Profile
  3. Select one of the quality profiles whose language you want to add a new rule
  4. Look for the XPath rule template:
    Image RemovedImage Added
  5. Copy this template to create a new rule:
    Image RemovedImage Added
  6. Write your XPath rule (it should comply to XPath 1.0):
    Image RemovedImage Added

    Here are two examples of JavaScript XPath rules:

    Do not use document.write

    Code Block
    languagenone
    //callExpression/memberExpression[count(*) = 3 and primaryExpression[@tokenValue = "document"] and identifierName[@tokenValue = "write"]]


    Always use curly braces for if/else statements:

    Code Block
    languagenone
    //ifStatement/statement[not(block)] 

     

     

  7. Once written, activate those rules and run a Sonar analysis.
     
  8. Violations on those XPath rules are now logged:
    Image RemovedImage Added

Extending Sonar Plugins

...

This step relates to the extension point org.sonar.api.profiles.ProfileDefinition. Profiles provided by plugins are registered at server startup  and can't be edited by users:Image RemovedImage Added

3. Analyzing source code

...