In this lesson, we will demonstrate how to create a rule that checks the code for spaces between a variable and its operand (++
and --
). For example, var++
is acceptable, but not var ++
. The following code contains the violation this rule will find.
int x_plus_one(int x) { return x ++; // violation } int x_minus_one(int x) { return x--; // Ok }
In this section:
Designing the Rule Pattern
Designing the rule pattern consists of creating a parent rule node and then adding qualifications to that node so that it fully expresses the code pattern that you wish to search for and remove during static analysis.
Creating the Parent Node
- Choose New> Rule from the menu bar.
- Choose C++Text from the Dictionary drop-down menu and enable the By Node option.
- Choose Constants> Identifier Constant and click OK.
Adding Additional Qualifications
- Right-click the Identifier Constant node and choose Next[...] from the shortcut menu.
- Select the Whitespace folder and click OK.
- Next, you need to select the operands that you don't want separated with whitespace. Right-click the Identifier Constant node and choose NextIgnoringWhitespace from the shortcut menu.
- Choose Expressions> Assignment> ++ and -- and click OK. You can choose multiple items from the menu by pressing and holding the CTRL key as you click. The rule should resemble the following:
- You will need to change from indirect to direct checking because you only want to count the spaces up to the first occurrence of the
++
and--
expressions. Right-click the NextIgnoringWhitespace node (containing ++ and --) and choose Direct Check. Notice that the arrow is removed from the node.
Specifying an Error Message
We need to specify what to print when this rule is violated.
- Right-click the if parent rule node and choose Create Output> Display from the shortcut menu. The Customize Output dialog opens.
- Enter the message that you want the product to deliver when this rule is violated, e.g.,
There are no whitespaces between variables and operands
. - Click OK to save the output message.
The rule is now functionally complete, but the rule properties must be set before it can be saved and enabled.
Customizing Rule Properties
After you customize this rule's properties and save it, the product will be able to enforce it. See Customizing Rule Properties for details.
Saving and Enabling Your Rule
Before you can check your rule, you need to save and enable it as described in Saving and Enabling Rules.
Viewing Rule Documentation
Information about the rule will be included in RuleWizard’s Rules Documentation files. To view this documentation, click the View RuleDocs button in the toolbar. To refresh this documentation, click the Update RuleDocs button in the toolbar. These buttons are described in the Tool Bar chapter.