Detect typedef of typedefs
This example shows how to use Polyspace Query Language (PQL) to check for violation of this rule: Do Not define typedef of typedefs.
This topic focuses on application of PQL. For more details about creating semantic defect checkers, see Detect Semantic Issues Using Polyspace Query Language Semantic Classes.
Analyze Rule
To implement the rule in PQL, analyze the components of the rule:
Type of a variable — Use the class
Typeto identify variable types.Checking for
typedefs oftypedefs — Findtypedeftypes, and then check if their underlying types aretypedefs themselves.
Implement Rule in PQL
The defect can be defined like this:
defect recursiveTypedef =
when
Cpp.TYpe.is(&type) and
type.isTypedef() and // Check if type is a type def
type.underlyingType(&base_type) and
base_type.isTypedef() // check if the underlying type of a typedef is also a typedef
raise "Recursive typedef is forbidden. {base_type} is already a typedef."
on varTest Defect
To test and verify the defect:
Initialize a test standard in a writable location:
polyspace-query-language init
In
main.pql, insert the defect in a test standard:package main // Main PQL file defines the catalog of your PQL project. // The catalog is a collection of sections. catalog PQL_Expression_example = { #[Description("MySection")] section mysection = { #[Description("myRule"), Id(Rule1)] rule myRule = { defect recursiveTypedef = when Cpp.Variable.is(&var) and var.type(&type) and type.isTypedef() and type.underlyingType(&base_type) and base_type.isTypedef() raise "Recursive typedef is not allowed. {base_type} is already a typedef." on var } } }Package the standard in a
pschkfile:polyspace-query-language packageCreate
example.cppin the same folder:This code explicitly states where a violation of the rule is expected using annotation/* Do Not define typedef of typedefs. */ typedef struct _SomeStruct { unsigned char fu1_someFlag; } SomeStruct; typedef SomeStruct someTypedefedType; someTypedefedType gst_command_type2; // expect-1-Rule1expect-1-Rule1. Absence of the violation is also annotated usingexpect-0-Rule1.Run a test for the defect on the example code:
The test verifies the expected violations as well as the expected absence of violations:polyspace-query-language test example.cpp
Number of actual defects: 1 Number of expected annotations: 1 (including 0 expected absence of defects). _______________________________________________ Checking expected defects with actuals... ----------------------------------------- _______________________________________________ Looking for unexpected defects... ------------------------------------------- _______________________________________________ Tests passed