Semantic API (experimental)
This API may change between ZPA versions without notice. Its classes are marked with ZpaExperimentalApi: Java rules can
use them directly; Kotlin rules must opt in with @OptIn(ZpaExperimentalApi::class).
Beyond the syntax tree, a rule can ask ZPA what the code means: which declaration a name refers to, whether a variable is used, which column a name in SQL reads, what type a value has. ZPA answers these questions from its semantic analysis of the file, from the declarations of the whole project and, when configured, from the database metadata.
symbolTable and currentScope of the visitor context, Symbol, Scope, SymbolTable, PlSqlType, the *Datatype
classes and SemanticAstNode are deprecated since ZPA 4.3.0 and will be removed in ZPA 5.0. Move rules that use them to
the queries below; see Migrating from the legacy symbol model.
Certain and uncertain answers
PL/SQL code often depends on things ZPA can't see: a package in another schema, a table not covered by the database
metadata, text built at runtime. That's why every query answers with a type that says how certain the answer is. For
example, usageEvidence returns Used, Unused, Unknown (with the reasons) or Unavailable.
A rule should report an issue only when the answer proves the problem: for a rule about unused declarations, Unused.
Unknown means something ZPA can't see might use the declaration, and Unavailable means ZPA has no answer for that
node, so neither justifies an issue. A rule that reports on them raises false positives on code that depends on objects
outside the analysis.
Example
This rule reports exceptions that are declared but never raised or handled:
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar;
import org.sonar.plugins.plsqlopen.api.semantics.UsageEvidence;
@Override
public void init() {
subscribeTo(PlSqlGrammar.EXCEPTION_DECLARATION);
}
@Override
public void visitNode(AstNode node) {
if (getContext().usageEvidence(node) == UsageEvidence.Unused.INSTANCE) {
addIssue(node, "Remove this unused exception.");
}
}
A real rule also has to decide what is out of its reach. The built-in UnusedVariable rule, for example, skips the declarations of package specifications, because other units can use them.
Queries
The queries are methods of the visitor context (getContext() in Java, context in Kotlin). Each takes a node of the
syntax tree; the Javadoc lists which nodes each one accepts and every
answer it can give. The built-in rules are working examples.
Names: what a name refers to
| Query | Answers | Used by |
|---|---|---|
nameBinding | Which declaration of the file a name read in PL/SQL or SQL refers to. For calls and cursors, callBinding and cursorBinding give the full answer. | VariableInCount, ColumnHidesPlSqlName, ColumnsShouldHaveTableName |
callBinding | Which subprogram a call binds, in the file or in the project, including the overload chosen by the argument types. | FunctionWithoutReturn |
cursorBinding | Which cursor OPEN, FETCH, CLOSE or a cursor FOR loop uses, and how the arguments bind to its parameters. | |
fieldBinding | Which record field or object attribute a member name refers to, or that the type has no such field. | |
typeBinding | Which type declaration a datatype name refers to. | |
exceptionBinding | Which exception a RAISE or WHEN names. | UnhandledUserDefinedException |
Declarations: how a declaration is used
| Query | Answers | Used by |
|---|---|---|
usageEvidence | Whether a variable, exception, cursor or parameter is used. | UnusedVariable, UnusedParameter, UnusedCursor |
hidingEvidence | Which outer declaration a variable or exception hides. | VariableHiding |
regionUncertainty | What the analysis can't see in a block, subprogram or trigger, such as code under conditional compilation. | UnhandledUserDefinedException |
Types: what type a value or declaration has
| Query | Answers | Used by |
|---|---|---|
valueCategory | The category of the type of a value, following subtypes and %TYPE. | InsertWithoutColumns, ImplicitColumnConversion, SelectAllColumns |
declaredType | What a datatype, or the name of a record or collection type of the file, declares: a built-in type with its constraints, the fields of a record, the element of a collection, a %TYPE or %ROWTYPE anchor. Every answer also carries its category. | ColumnIntoSmallerVariable, FunctionShouldBeDeterministic |
SQL: what a statement reads
| Query | Answers | Used by |
|---|---|---|
columnBinding | Which column a name in static SQL reads. | NullTestOnNotNullColumn, ColumnIntoSmallerVariable, ImplicitColumnConversion |
mayBeOuterJoined | Whether an outer join may make the columns of a source null. Only false is a proof: no outer join does. | NullTestOnNotNullColumn |
isOuterJoined | Whether an outer join is proven to make the columns of a source null. Only true is a proof. | OuterJoinDiscardedByCondition, NotInWithNull |
dynamicSql | The SQL text that EXECUTE IMMEDIATE, OPEN … FOR or DBMS_SQL.PARSE builds, parsed as a statement. The other SQL queries also answer inside it. | ParameterInDynamicSql |
Project: other units
The declarations of the whole project are available through projectAnalysis(), for questions about other units. This
rule reports parameters declared NOCOPY in the package specification but not in the body:
import org.sonar.plugins.plsqlopen.api.project.PackageParameter;
import org.sonar.plugins.plsqlopen.api.project.PackageSpecificationResolution;
PackageSpecificationResolution resolution = projectAnalysis().resolvePackageSpecification(node);
if (resolution.getStatus() == PackageSpecificationResolution.Status.RESOLVED) {
var body = resolution.getBody().orElseThrow();
var specification = resolution.getSpecification().orElseThrow();
var specificationByOrdinal = new java.util.HashMap<Integer, PackageParameter>();
for (PackageParameter parameter : specification.getParameters()) {
specificationByOrdinal.put(parameter.getOrdinal(), parameter);
}
for (PackageParameter bodyParameter : body.getParameters()) {
PackageParameter specificationParameter = specificationByOrdinal.get(bodyParameter.getOrdinal());
if (specificationParameter == null) {
return;
}
if (specificationParameter.isNocopy() && !bodyParameter.isNocopy()) {
addIssue(node, "Add NOCOPY to this parameter to match its package specification.");
}
}
}
The same rule about certainty applies: act only on RESOLVED, which means ZPA found exactly one matching specification.
NOT_FOUND, AMBIGUOUS, INCOMPLETE, NOT_APPLICABLE and NOT_PREPARED mean ZPA can't answer with certainty.
Migrating from the legacy symbol model
| Legacy code | Replacement |
|---|---|
Looking up a symbol in symbolTable or currentScope to find what a name refers to | nameBinding, typeBinding, columnBinding, callBinding |
Checking the usages of a Symbol | usageEvidence |
| Comparing scopes to find hidden declarations | hidingEvidence |
Reading a PlSqlType or a datatype from SemanticAstNode | valueCategory, declaredType |
MethodMatcher.addParameter(PlSqlType) | MethodMatcher.addParameter(Predicate) on the argument node, for example MethodMatcher.nullLiteral() |
Testing
PlSqlCheckVerifier.verify runs the rule as a real analysis does, with a project prepared from the test file, so the
queries answer as they would in production:
verify(path, check, metadata, conditionalCompilation, errorRecovery, prepared): passprepared = falseto run the rule as in an analysis without a project.verifyWithExternalContext(path, check, externalContext): supplies database metadata and the compilation schema, for rules that depend on them.ProjectPlSqlCheckVerifier: takes oneProjectTestSourceper file, for rules that look at more than one file. All files are read as one project before the rule runs, and the expected issues are checked in each file.