Detect Use of std Namespace in using
Declaration
This example shows how to use Polyspace Query Language (PQL) to check for violation of
this rule: Do not use using namespace std.
This topic focuses on application of PQL. For more details about creating syntax defect checkers, see Detect Syntactic Issues Using Polyspace Query Language Syntactic Classes.
Analyze Rule
To implement the rule in PQL, analyze the components of the rule.
usingdeclaration — Use the classUsingDeclarationto identifyusingdeclarations.Namespace identifier in
usingdeclaration — Use the predicates of the classUsingDeclarationto find the namespace identifier and check if it matchesstd.
Implement Rule in PQL
The rule can be implemented using the predicates of the class UsingDeclaration:
defect use_of_namespace_std =
when
Cpp.UsingDeclaration.is(&ns)
and ns.identifier(&ns_id)
and ns_id.nodeText(&ns_id_name)
and ns_id_name=="std"
raise "Explicitly prefix all identifiers from the standard namespace with an 'std::' prefix, rather than rely on 'using namespace std;'"
on ns,Test 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_Using_example = { #[Description("MySection")] section mysection = { #[Description("myRule"), Id(Rule1)] rule myRule = { defect use_of_namespace_std = when Cpp.UsingDeclaration.is(&ns) and ns.identifier(&ns_id) and ns_id.nodeText(&ns_id_name) and ns_id_name=="std" raise "Explicitly prefix all identifiers from the standard namespace with an 'std::' prefix, rather than rely on 'using namespace std;'" on ns, } } }Package the standard in a
pschkfile:polyspace-query-language package
Create
example.cppin the same folder:This code explicitly states where a violation of the rule is expected using annotation/* Do Not Use 'using namespace std'. */ #include <iostream> namespace mathutils { int add(int a, int b) { return a + b; } } using namespace std; // expect-1-Rule1 using namespace mathutils; // expect-0-Rule1 int main() { cout << "3 + 4 = " << add(3, 4) << endl; return 0; }expect-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: 2 (including 1 expected absence of defects). _______________________________________________ Checking expected defects with actuals... ----------------------------------------- _______________________________________________ Looking for unexpected defects... ------------------------------------------- _______________________________________________ Tests passed