Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 74 Next »

There are two ways to extend coding rules:

  1. Adding XPath rules directly through the SonarQube web interface.
  2. Extending an existing SonarQube plugin. For example Checkstyle and PMD plugins accept definition of custom checks.

Before starting implementing a new coding rule, you should wonder whether it is specific to your own context or might benefit others. If it might benefit others, you can propose them on the developer mailing-list. If the SonarQube team find them interesting, they may be directly implemented in the related language plugin. It means less maintenance on your side and benefits to others.

Adding New Rules Using XPath Expressions

SonarQube 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 VB.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 for example).


Let's take the following JavaScript source code sample:


While parsing the source code, SonarQube builds an Abstract Syntax Tree (AST).

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:

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

To create a new rule:

  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:
  5. Copy this template to create a new rule:
  6. Write your XPath rule (it should comply to XPath 1.0):

    Here are two examples of JavaScript XPath rules:

    Do not use document.write

    Always use curly braces for if/else statements:



  7. Once written, activate those rules and run an analysis.
  8. Issues on those XPath rules are now logged:

Extending SonarQube Plugins

The following languages can be extended with new rules:

  • No labels