Synopsys logo

Coverity® 2020.12 CodeXM

Java Library Reference

Introduction

Specifying the Target Language

Class Definitions

‘enum’ Kinds

‘globalset’ Sets

Code Patterns

Records

Functions

Hide/show Contents

Coverity® 2020.12 CodeXM

Java Library Reference

Introduction

CodeXM is a domain-specific language that allows you to create custom code checkers. CodeXM checkers analyze source code for specific coding patterns, and report these issues with messages that you provide. Like other Coverity checkers, the issues are displayed in Coverity Connect. They can be archived with the cov-commit-defect feature.

The CodeXM Java library provides access to Java coding constructs.

This document provides information about the patterns and functions provided by the Java library. To learn how to get started with CodeXM, please see Learning to Write CodeXM Checkers.

Typographic Conventions

Describing CodeXM is a bit different from describing other languages. Most programming books talk about one language only. To describe CodeXM, we have to talk about CodeXM code itself, and the code of the language it is inspecting—the target language.

This reference shows all code in monospace type.

Target code (whatever the language) appears in shades of orange.

Reminder: By default, many browsers do not print out background colors.

Nullable Types

The type of certain pattern properties is said to be nullable. This means that the property might return a value, or it might not. If it does not, its value matches the CodeXM keyword null. In the CodeXM documents, a nullable type is indicated by the name of the type the property might return, followed by a question mark; for example, int?.

In checker code, a nullable type requires some special handling in order to avoid the error of referencing the null. The Handling Null Values section of Learning to Write CodeXM Checkers describes how to do this.

Specifying the Target Language

In your CodeXM source, begin with an include declaration that names the library target language: include `Java`.

Specifying the target language makes the library’s special patterns and functions available within this CodeXM file. These patterns and functions are the subject of this reference.

The language specification also causes the checkers defined in your CodeXM file to be applied only to the target source code in your code base.

Class Definitions

Class definitions match class entities in the abstract representation of the target code, and provide properties that describe the classes that the library supports.

astnode (class)

Every target-code object that Coverity inspects is a node in an abstract syntax tree. For a brief overview of how Coverity uses these syntax trees, see How Does Coverity Analysis Work?.

Properties

Every astnode has the following properties:

Name Type Description
location sourceloc The location of this code construct in the source files
children list<astnode> A list of child nodes that are sub-parts of this code construct
parent astnode? This node’s parent node, if there is one; null if there is no parent
macrosExpandedFrom list<macroinfo> If the code is produced by macro expansion, this list contains the macros that generated that expansion. Otherwise, this list is empty.
implicit bool Indicates whether the node is the result of compiler intervention, as opposed to being explicitly stated in the source code. For example, if ( x ) in the source code is interpreted as if ( x != 0 ) by the compiler. The not-equals binary operator and the literal constant zero are implicit.

The astnode elements are further classified as statement, expression, initializer, and declaration elements (declaration elements declare symbols). Certain kinds of elements have their own set of properties in addition to the astnode properties shown here.

classDefinition (class)

Describes a Java class, interface, enum, or code annotation.

Properties

classDefinition produces a record that contains the following properties:

Name Type Description
annotations list<codeAnnotation> Any annotations specified for this class
declaredType classType The type of the class
fieldList list<fieldSymbol> A list of the symbols for each non-static field in the class
location sourceloc The location of this class in the source code
memberFunctionList list<functionSymbol> A list of the symbols for each non-static member function
parentList list<classParent> A list of parent classes
staticFieldList list<staticVariableSymbol> A list of the symbols for each static field in the class
staticMemberFunctionList list<functionSymbol> A list of the symbols for each static member function
findBaseClass function<testType> A function that invokes a callback function, which can be used as a predicate to find a particular base class—in other words, to test whether the class is a parent of the current class. See the section, “The Base Class Properties”, below.
findMatchingBaseClass function<testType> A function that invokes a pattern, which can be used as a predicate to find a particular base class—in other words, to test whether the class is a parent of the current class. See the section “The Base Class Properties”, below.

The Base Class Properties

The function provided by the findBaseClass property has this form:

CXM code follows
function <testType> ( callback: function( base: typeof( classType ).producedType ) -> testType? );

The function provided by the findMatchingBaseClass property has this form:

CXM code follows
function <testType> ( pattern( typeof( classType ).matchedType ) -> testType ) -> testType? ;

The findBaseClass call detects whether a base class is accepted by the callback function. If the callback returns a non-null value, then findBaseClass returns that value (which matches NonNull). If the callback does not return such a non-null value on any base class, findBaseClass returns null.

The findMatchingBaseClass call uses a pattern rather than a callback function, but it returns either a matching value or null, just as findBaseClass does.

Because both these function calls accomplish the same thing, for the most part which one you choose to use is up to you. The pattern form can be easier, and less lengthy, to code (see the examples that follow); on the other hand, a callback function can encode tests that a pattern cannot.

The following “Examples” section shows checkers that use these properties.

Examples of Using Base Class Properties

This first example uses findBaseClass. If findBaseClass can locate a class whose identifier (base.identifier) is "A", it returns the object for that class. Otherwise, the return value is null:

CXM code follows
checker { name = "DERIVES_FROM_A_findBaseClass"; reports = for c in globalset allClasses where c.findBaseClass( function ( base: typeof( classType ).producedType ) -> base.identifier == "A" ? base : null ) matches NonNull as baseA : { events = [ { tag = "base"; description = baseA + " is here"; location = baseA.location; }, { tag = "child"; description = "Class " + c.declaredType + " derives from A"; location = c.location; } ]; }; };

The second example uses findMatchingBaseClass:

CXM code follows
checker { name = "DERIVES_FROM_A_findMatchingBaseClass"; reports = for c in globalset allClasses where c.findMatchingBaseClass( classType { .identifier == "A"} ) matches NonNull as baseA : { events = [ { tag = "base"; description = baseA + " is here"; location = baseA.location; }, { tag = "child"; description = "Class " + c.declaredType + " derives from A"; location = c.location; } ]; }; };

classParent (class)

Describes a parent class in Java.

Properties

classParent produces a record that contains the following properties:

Name Type Description
classType classType The type of the parent class
isVirtual bool true if the class is virtual

functionDefinition (class)

Describes a function definition.

Properties

functionDefinition produces a record that contains the following properties:

Name Type Description
body statement A blockStatement of the function body
constructorInitializerList list<ctor>? A list of constructors called in the initialization of this function
formalParameterList list<symbol> A list of parameterSymbol elements for each argument to the function
functionSymbol symbol The functionSymbol that represents this function

Inherits properties from:

functionOrStaticVariableDefinition

functionOrStaticVariableDefinition (class)

Describes a function or statically declared variable.

Properties

functionOrStaticVariableDefinition produces a record that contains the following properties:

Name Type Description
allCode set<astnode> All nodes within a function. For a variable this is usually just the initialization.
location sourceloc The location in the code, used for defect reporting
paths executionPaths The execution paths used for path-sensitive analysis

staticVariableDefinition (class)

Describes a variable declared static within a class.

Properties

staticVariableDefinition produces a record that contains the following properties:

Name Type Description
initializer initializer? The initializer for this variable; null if one does not exist
variable symbol A staticVariableSymbol that represents this variable

Inherits properties from:

functionOrStaticVariableDefinition

Annotation Classes

Annotation classes match annotation constructs in the target code. annotations add metadata that can be used to help manage code, specify run-time behavior, and for a variety of other purposes.

When used with Coverity, in particular, an annotation can specify how Coverity Analysis should treat an object; for example, a call to a particular function.

annotationAnnotationElement (class)

An annotation element in a Java annotation

Inherits properties from:

annotationElement

annotationArrayElement (class)

An array element in a Java annotation

Inherits properties from:

annotationElement

annotationElement (class)

A Java annotation element

annotationExpressionElement (class)

An expression element in a Java annotation

Inherits properties from:

annotationElement

‘enum’ Kinds

These are enumerations that are used by the language library, and that are available to your own CodeXM code.

assignKind (enum)

Specifies whether an assignment is simple (assignment only) or compound (incorporating an additional operation such as plus, +, or minus, -).

Details

The following values are defined:

Name Description
`simple` A simple assignment; for example, a = b
`compound` A compound assignment; for example, a += b

See Also

assignmentOperator, assignmentOperatorCompound, assignmentOperatorSimple

castKind (enum)

Represents the various kinds of casts Java supports.

Details

The following values are defined:

Name Description
`checkedExplicit` An explicit checked cast
`checkedImplicit` An implicit checked cast
`explicit` An explicit cast. For example, (int) a.
`implicit` An implicit cast
`uncheckedFromGenerics` An unchecked cast from generics

See Also

castOperator, castOperatorChecked, castOperatorExplicit, castOperatorImplicit

floatKind (enum)

Represents the kinds of floating-point types known to Java.

Details

The following values are defined:

Name Description
`double` A double-precision floating-point number
`float` A single-precision floating-point number

See Also

floatType

ForLoopKind (enum)

Represents either simple or enhanced for loops.

Details

A simple for loop has the following form:

Java code follows
for (int i; i < 10; i++) {
// ...
};

An enhanced for loop has the following form:

Java code follows
for (int i : mySet) {
// ...
};

The following values are defined:

Name Description
`enhanced` An enhanced for loop
`simple` A simple for loop

See Also

forLoop, forLoopEnhanced, forLoopSimple

intKind (enum)

Represents the integer types known to Java.

Details

The following values are defined:

Name Description
`bool` A Boolean value
`byte A byte
`char` A character
`int` A regular integer
`long` A long integer
`short` A short integer

Specific bit lengths for integer values depend on the target implementation.

See Also

integerLiteral, integerType

variableDeclarationKind (enum)

Describes how a variable has been declared.

Details

The following values are defined:

Name Description
`local` The variable declaration is local to a function or a class.
`static` The variable declaration is static and the variable is available globally.

See Also

variableDeclaration

variableScopeEnum (enum)

Represents the scope of a variable symbol.

Details

The following values are defined:

Name Description
`local` The variable scope is local to a function or a class.
`static` The variable scope is static and the variable is available globally.
`tryResource` The variable is declared with a try-with-resources statement.

See Also

variableReference, variableSymbol

‘globalset’ Sets

The sets described in this section can help narrow the search of your checker. Typically they are used in for loop constructions such as the following:

CXM code follows
for code in globalset allFunctionCode where code matches // ... further criteria

allClasses (globalset)

Includes the definitions of all class, interface, and struct types in the current Java code.

allFunctionAndStaticVariableCode (globalset)

Includes the Abstract Syntax Tree (AST) nodes in all functions, and all statically declared variables. This set is the union of allFunctionCode and allStaticVariableCode.

allFunctionAndStaticVariableDefinitions (globalset)

Includes all function and staticaly declared variable definitions. This set is the union of allFunctionDefinitions and allStaticVariableDefinitions.

allFunctionCode (globalset)

Includes all the Abstract Syntax Tree (AST) nodes in all the functions of the current Java code.

See Also

allFunctionAndStaticVariableCode, allFunctionsAndGlobalVariableCode

allFunctionDefinitions (globalset)

Includes all function definitions in the current Java code.

See Also

allFunctionAndStaticVariableDefinitions

allFunctionsAndGlobalVariableCode (globalset)

Matches all the Abstract Syntax Tree (AST) nodes in all the functions and global variable initializers of the current Java code.

See Also

allFunctionCode

allStaticVariableCode (globalset)

Includes all statically declared variables in the current Java code.

See Also

allFunctionAndStaticVariableCode

allStaticVariableDefinitions (globalset)

Includes all definitions of statically declared variables in the current Java code.

See Also

allFunctionAndStaticVariableDefinitions

allTextFiles (globalset)

Includes all source files in the current project that are coded in the Java language.

Code Patterns

These patterns, organized by category, match the constructs that might be found in the target source code.

Statements

Patterns in this section belong to the statement class. They match executable statements in the target code.

allLoops (pattern)

Matches all loop kinds.

Details

The pattern matches if a statement is a for (simple or enhanced), while, or do ... while loop. For specific patterns, with more details about each loop, refer to forLoopSimple, forLoopEnhanced, whileLoop, doWhileLoop.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

Example

The following uses allLoops to determine if a simpleStatement contains a while loop expression:

CXM code follows
pattern simpleStatementLoop { simpleStatement { .expression == allLoops } };

See Also

forLoopSimple, forLoopEnhanced, forLoop, whileLoop, doWhileLoop

assertStatement (pattern)

Matches assert statements.

Details

This pattern only matches nodes of type statement.

Properties

assertStatement produces a record that contains the following properties:

Name Type Description
conditionExpression expression The condition of the assertion

Inherits properties from:

astnode

Example

The following pattern matches any assert that has a Boolean literal as its condition:

CXM code follows
pattern boolLiteralAssert { assertStatement { .conditionExpression == booleanLiteral } };

blockStatement (pattern)

Matches statements contained in curly braces.

Details

Block statements contain one or more statements, enclosed in curly braces.

This pattern only matches nodes of type statement.

Properties

blockStatement produces a record that contains the following properties:

Name Type Description
containedStatements list<statement> The statements the block contains

Inherits properties from:

astnode

Example

The following pattern finds blockStatements that contain only the empty statement:

CXM code follows
pattern emptyStatementBlock { blockStatement { .containedStatements == emptyStatement } };

See Also

emptyStatement

breakStatement (pattern)

Matches break statements.

Details

This does not match a break that has a label. See labeledBreakStatement.

This pattern only matches nodes of type statement.

Properties

breakStatement produces a record that contains the following properties:

Name Type Description
controlStatement statement The flow control statement within which the break occurs; for example, while or switch

Inherits properties from:

astnode

Example

The following example matches break statements from a switch:

CXM code follows
pattern breakFromSwitch { breakStatement { .controlStatement == switchStatement } };

See Also

switchStatement, whileLoop, doWhileLoop, forLoop, forLoopSimple, forLoopEnhanced

caseStatement (pattern)

Matches individual case statements.

Details

This pattern does not match the default case. See defaultStatement.

This pattern only matches nodes of type statement.

Properties

caseStatement produces a record that contains the following properties:

Name Type Description
valueExpression expression The value associated with the case

Inherits properties from:

astnode

Example

The following pattern matches all case statements that are for the integer value 1:

CXM code follows
pattern caseOne { caseStatement { .valueExpression == integerLiteral { .value == 1 } } };

See Also

defaultStatement, switchStatement

continueStatement (pattern)

Matches continue statements.

Details

This pattern only matches nodes of type statement.

Properties

continueStatement produces a record that contains the following properties:

Name Type Description
controlStatement statement The loop statement within which the continue occurs; for example, while or for

Inherits properties from:

astnode

Example

The following example matches continue statements from a while loop:

CXM code follows
pattern continueFromWhile { continueStatement { .controlStatement == whileStatement } };

See Also

labeledContinueStatement, whileLoop, doWhileLoop, forLoop, forLoopSimple, forLoopEnhanced

defaultStatement (pattern)

Matches the default case in switch statements.

Details

This pattern only matches nodes of type statement.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

Example

The following pattern matches switch statements that have a default clause:

CXM code follows
pattern switchWithDefault { switchStatement as sw where exists stmt in sw.caseList where stmt matches defaultStatement };

See Also

caseStatement, switchStatement

doWhileLoop (pattern)

Matches do ... while loops.

Details

This pattern only matches nodes of type statement.

Properties

doWhileLoop produces a record that contains the following properties:

Name Type Description
bodyStatement statement The body of the loop
conditionExpression expression The condition expression of the loop

Inherits properties from:

astnode

Example

The following pattern matches where a do ... while loop has a Boolean constant value as its condition:

CXM code follows
pattern doWhileLoopBoolConstantCondition { doWhileLoop { .conditionExpression == booleanLiteral } };

See Also

whileLoop, forLoop, forLoopSimple, forLoopEnhanced

emptyStatement (pattern)

Matches empty statements.

Details

An empty statement might be a non-statement (empty text) terminated by a semicolon, curly braces that do not enclose code, or it might be an implied branch of an ifStatement.

Properties

This pattern does not expose any new properties.

Examples

The following are examples of source code that emptyStatement would match:

Java code follows
; // No code here
{
// No code here
}
if (b) {
// ...
}
// No else branch

This pattern only matches nodes of type statement.

See Also

blockStatement, ifStatement

forLoop (pattern)

Matches either simple or enhanced for loops.

Details

To match specific kinds of for loops, and to get greater detail about them, refer to forLoopSimple and forLoopEnhanced.

This pattern only matches nodes of type statement.

Properties

forLoop produces a record that contains the following properties:

Name Type Description
body statement The body of the for loop
kind enum ForLoopKind The kind of for loop, either `simple` or `enhanced`; see ForLoopKind

Inherits properties from:

astnode

Example

The following pattern matches any simple for loop:

CXM code follows
pattern anySimpleForLoop { forLoop { .kind == `simple` } };

See Also

forLoopSimple, forLoopEnhanced

forLoopEnhanced (pattern)

Matches enhanced for loops; that is, loops of the form for (int i : numbers).

Details

This pattern only matches nodes of type statement.

Properties

forLoopEnhanced produces a record that contains the following properties:

Name Type Description
bodyStatement statement The body of the loop
containerExpression expression The container being iterated
kind enum ForLoopKind Always `enhanced`; see ForLoopKind
loopVariable localVariableSymbol The iterator for the loop

Inherits properties from:

astnode

Example

The following finds all enhanced for loops over an array of integers:

CXM code follows
pattern enhancedForIntegers { forLoopEnhanced { .containerExpression == expression { .type == arrayType { .elementType == integerType } } } };

See Also

forLoopSimple, forLoop

forLoopSimple (pattern)

Matches simple for loops; that is, loops of the form for (int i = 0; i < 10; i++).

Details

This pattern only matches nodes of type statement.

Properties

forLoopSimple produces a record that contains the following properties:

Name Type Description
bodyStatement statement The body of the loop
conditionDeclaration variableDeclaration? If a variable is declared in the second clause of the loop, it is represented (returned) here
conditionExpression statement Conditional clause for the loop
initializationStatement statement Initialization clause for the loop
kind enum ForLoopKind Always `simple`; see ForLoopKind
updateStatement statement The update clause of the loop

Inherits properties from:

astnode

Example

The following pattern matches a simple for loop that uses a postfix increment expression to update:

CXM code follows
pattern postFixUpdate { forLoopSimple { .updateStatement == simpleStatement { .expression == incrementOperator { .kind == `postfix` } } } };

See Also

forLoopEnhanced, forLoop

ifStatement (pattern)

Matches entire if statements, including their condition expressions and their true and false branches.

Details

This pattern only matches nodes of type statement.

Properties

ifStatement produces a record that contains the following properties:

Name Type Description
conditionDeclaration variableDeclaration? The variable declared in the condition, if one exists; null otherwise
conditionExpression expression The condition of the if statement
falseStatement statement? The false branch of the if statement; null if no false branch exists
trueStatement statement The true branch of the if statement

Inherits properties from:

astnode

Example

The following pattern matches if statements that have no else clause:

CXM code follows
pattern ifNoElse { ifStatement { .falseStatement == null } };

labeledBreakStatement (pattern)

Matches break statements that target a label.

Details

This pattern only matches nodes of type statement.

Properties

labeledBreakStatement produces a record that contains the following properties:

Name Type Description
controlStatement statement The flow-of-control statement within which the break occurs; for example, while or switch.
target statement The label to break to.

Inherits properties from:

astnode

Example

The following pattern matches a break statement that targets the label outer:

CXM code follows
pattern outerBreak { labeledBreakStatement { .target == labelStatement { .nameString == "outer" } } };

See Also

labelStatement, breakStatement, switchStatement, whileLoop, doWhileLoop, forLoop, forLoopSimple, forLoopEnhanced

labeledContinueStatement (pattern)

Matches continue statements that target a label.

Details

This pattern only matches nodes of type statement.

Properties

labeledContinueStatement produces a record that contains the following properties:

Name Type Description
controlStatement statement The flow-of-control statement within which the break occurs; for example, while or switch
target statement The label to target

Inherits properties from:

astnode

Example

The following pattern matches a continue statement that targets the label outer:

CXM code follows
pattern outerBreak { labeledContinueStatement { .target == labelStatement { .nameString == "outer" } } };

labelStatement (pattern)

Matches all labels.

Details

This pattern only matches nodes of type statement.

Properties

labelStatement produces a record that contains the following properties:

Name Type Description
nameString string The name of the label
targetStatement statement The statement to which this label is assigned

Inherits properties from:

astnode

Example

The following pattern finds all continue statements with a label to outer:

CXM code follows
pattern continueOuter { labeledContinueStatement { .target == labelStatement { .nameString == "outer" } } };

See Also

labeledContinueStatement, labeledBreakStatement

returnStatement (pattern)

Matches both simple, void return statements, and return <expression> returns.

Details

This pattern only matches nodes of type statement.

Properties

returnStatement produces a record that contains the following properties:

Name Type Description
isVoid bool true if the return does not have an associated expression
returnedExpression expression? The expression returned, if one is specified; null otherwise

Inherits properties from:

astnode

Example

The following pattern matches return statements that are void:

CXM code follows
pattern voidReturn { returnStatement { .isVoid == true } };

simpleStatement (pattern)

Matches individual execution statements.

Details

The term simple derives from the fact that the these statements do not involve control flow. Simple statements include assignments, function calls, and ordinary expressions. They do not include variableDeclaration code.

This pattern only matches nodes of type statement.

Properties

simpleStatement produces a record that contains the following properties:

Name Type Description
expression expression The expression, such as a function call or an assignment

Inherits properties from:

astnode

Example

The following pattern matches a simple statement that is a function call:

CXM code follows
pattern simpleStatementFunctionCall { simpleStatement { .expression == functionCall } };

switchStatement (pattern)

Matches switch statements, including all statements contained in the various case and default clauses.

Details

This pattern only matches nodes of type statement.

Properties

switchStatement produces a record that contains the following properties:

Name Type Description
bodyStatement statement The body of the switch statement
caseList list<statement> A list of targets for this switch statement
conditionDeclaration variableDeclaration? If a variable is declared in the .conditionExpression, it is identified here; if no variable is declared, this value is null
conditionExpression expression The condition for the switch statement

Inherits properties from:

astnode

Example

The following pattern matches switch statements that have a default clause:

CXM code follows
pattern switchWithDefault { switchStatement as sw where exists stmt in sw.caseList where stmt matches defaultStatement };

See Also

caseStatement, defaultStatement

synchronizedStatement (pattern)

Matches synchronized blocks.

Details

This pattern only matches nodes of type statement.

Properties

synchronizedStatement produces a record that contains the following properties:

Name Type Description
bodyStatement statement The statement block
lockExpression expression The monitor object of the statement

Inherits properties from:

astnode

Example

Matches all synchronized blocks that use an expression of type class MyLock as the monitor:

CXM code follows
pattern myLockSynchronize { synchronizedStatement { .lockExpression == expression { .type == classType { .simpleName == "MyLock" } } } };

throwStatement (pattern)

Matches throw statements.

Details

This pattern only matches nodes of type statement.

Properties

throwStatement produces a record that contains the following properties:

Name Type Description
conditionExpression expression The thing being thrown by the statement

Inherits properties from:

astnode

Example

The following pattern matches when an expression with type class MyException is thrown:

CXM code follows
pattern throwMyException { throwStatement { .expression == expression { .type == classType { .simpleName == "MyException" } } } };

tryStatement (pattern)

Matches try statements, including catch blocks and the finally block.

Details

This pattern only matches nodes of type statement.

Properties

tryStatement produces a record that contains the following properties:

Name Type Description
bodyStatement statement The body of the try block
catchBlockList list<handler> The Java handlers
finallyStatement statement? The body of the finally block, it if exists; null if it does not
resourcesList list<declaration> A list of resources declared in a try-with-resource try

Inherits properties from:

astnode

Example

The following pattern matches handlers for Exception. This pattern uses tryStatement, which has the field catchBlockList, a list of handlers:

CXM code follows
pattern exceptionHandle { tryStatement as t where exists h in t.catchBlockList where h.variable.type matches classType { .simpleName == "Exception" } };

See Also

handler, declaration

whileLoop (pattern)

Matches standard while loops.

Details

This matches standard while loops, as opposed to do ... while and for loops.

This pattern only matches nodes of type statement.

Properties

whileLoop produces a record that contains the following properties:

Name Type Description
bodyStatement statement The body of the loop
conditionDeclaration variableDeclaration? If a variable is declared in the condition expression, it is represented here; null if there is no declaration
conditionExpression expression The expression in the condition of the loop

Inherits properties from:

astnode

Example

The following pattern matches where a while loop has a Boolean constant value as its condition:

CXM code follows
pattern whileLoopBoolConstantCondition { whileLoop { .conditionExpression == booleanLiteral } };

See Also

doWhileLoop, forLoop, forLoopSimple, forLoopEnhanced

Declarations

Patterns in this section belong to the declaration class. They match object declarations in the target code.

variableDeclaration (pattern)

Matches all kinds of variable declarations.

Properties

variableDeclaration produces a record that contains the following properties:

Name Type Description
initializer initializer? The initialization of the variable, if it exists
kind enum variableDeclarationKind Either `local` or `static`; see variableDeclarationKind
variable symbol The symbol of the defined variable

Inherits properties from:

astnode

Example

The following pattern matches all variables declared with type char:

CXM code follows
pattern charVariableDeclaration { variableDeclaration { .variable == symbol { .type == charType } } };

Types

These patterns match various types of values in the target code.

anyType (pattern)

Matches all types.

Properties

This pattern does not expose any properties.

arrayType (pattern)

Matches all array types.

Details

This pattern only matches nodes of type type.

Properties

arrayType produces a record that contains the following properties:

Name Type Description
elementType type The type of the elements in the array

Example

The following match statement finds all arrays whose elements are integers:

CXM code follows
t matches arrayType { .elementType == integerType }

booleanType (pattern)

Matches the boolean type.

Details

This pattern only matches nodes of type type.

Properties

booleanType produces a record that contains the following properties:

Name Type Description
alignmentInBytes int The alignment of the type, in bytes
sizeInBits int The size of the Boolean, in bits
sizeInBytes int The size of the Boolean, in bytes

Example

The following example matches any expression with a boolean type:

CXM code follows
node matches expression as e where e.type matches booleanType;

See Also

integerType

charType (pattern)

Matches the char type.

Details

This pattern only matches nodes of type type.

Properties

charType produces a record that contains the following properties:

Name Type Description
alignmentInBytes int The alignment of the type, in bytes
sizeInBits int The total size of the char, in bits
sizeInBytes int The size of the char, in bytes

Example

The following example matches any expression with a char type:

CXM code follows
node matches expression { .type == charType };

See Also

integerType

classType (pattern)

Matches any kind of Java class type.

Details

Matches the following kinds of Java classes:

This pattern only matches nodes of type type.

Properties

classType produces a record that contains the following properties:

Name Type Description
extra string Extra information used for defect reporting
extraWithoutScope string Extra information used for defect reporting. This extra information omits the scope details.
isAnonymous bool true if the class is anonymous
isComplete bool true if the class is complete
kind enum The kind of class: one of `class`, `interface`, `array`, `annotation`, or `enum`
location location The location information of the class
qualifiedName string The name of the class, including its package
scopeList list<string> The scope of the class. This is the elements of the qualified name broken up into a list.
simpleName string The name of the class, without the package prefix

Example

The following pattern:

CXM code follows
c matches classType { .kind = `enum };

... matches all enum classes.

floatType (pattern)

Matches the Java floating-point types.

Details

This pattern matches nodes of type type.

Properties

floatType produces a record that contains the following properties:

Name Type Description
kind enum floatKind Either `float` or `double`; see floatKind
alignmentInBytes int The alignment of the type, in bytes
sizeInBits int The total size of the float, in bits. The representation is implementation-defined, so bits for exponent and mantissa are not described.
sizeInBytes int The size of the float, in bytes

Example

The following pattern matches any expression that has the type double:

CXM code follows
node matches expression { .type == floatType { .kind == `double` } };

functionType (pattern)

Matches function types.

Details

This pattern only matches nodes of type type.

Properties

functionType produces a record that contains the following properties:

Name Type Description
declaredThrownTypeList list<type> The types the function is declared to throw
hasVariableArity bool true if the function uses variable arity; for example, method ( Type arg, ... ). (Arity is the number of arguments that a function accepts.)
isStatic bool Whether the function is declared as static
parameterTypeList list<type> Lists the types of parameters in the call
returnType type The return type of the function

Example

The following example pattern matches all function types that return an int:

CXM code follows
pattern returnsInt { functionType { .retunrnType == integerType { .kind == `int` } } };

integerType (pattern)

Matches all integer types that Java recognizes.

Details

This pattern only matches nodes of type type.

Properties

integerType produces a record that contains the following properties:

Name Type Description
alignmentInBytes int The alignment of the type, in bytes
kind enum intKind The kind of integer type: `byte`, `int`, `long`, or `short`; see intKind
sizeInBits int The size of the type, in bits
sizeInBytes int The size of the type, in bytes

Example

The following snippet of CodeXM matches a long type, using the kind property:

CXM code follows
t matches integerType { .kind == `long` };

See Also

charType, booleanType

referenceType (pattern)

Matches Java reference types.

Details

Reference types are used to represent when something is passed as a reference; for example, in a function parameter.

This pattern only matches nodes of type type.

Properties

referenceType produces a record that contains the following properties:

Name Type Description
toType type The type the reference refers to

Example

The following match pattern:

CXM code follows
t matches referenceType { .toType == classType { .simpleName == "MyClass" } };

... matches all references to a class named MyClass.

voidType (pattern)

Matches the void type.

Details

This pattern only matches nodes of type type.

Properties

This pattern does not expose any properties.

Expressions

Patterns in this section belong to the expression class. They match expressions in the target code.

Many statements in Java code contain expressions. The patterns in this section match specific kinds of expressions.

Please be aware: The patterns shown in the “Literals” and “Operators” sections are expressions, too.

Example: Expressions used as if-statement conditions

For example, in the following snippet of target code:

C/C++ code follows
if ( my_boolean ) {
if ( getPropertyValue(a) == v) {
// ... Do something.
}
};

... we see a pair of if statements. As described in the previous section, the ifStatement pattern detects either instance.

But each statement has a condition: namely, the part enclosed by the parentheses that follow the keyword if. Both conditions in this example are expressions. The first is simply a variable reference. The second is more complicated: It is made up of a binary operator (specifically, the equality operator) with operands (which are themselves expressions) appearing on either side. The left-hand operand is a function call, and the right-hand operand is a variable reference.

You could match the first of these conditions by using the expression pattern variableReference (which also matches the right-hand side of the second condition), and you could match the second of these conditions by using the expression pattern binaryOperator.

To inspect a complete condition expression, look at the .conditionExpression property of the ifStatement pattern.

Common Properties of Expressions

In addition to the properties specific to each pattern, and the properties inherited from astnode, all expression patterns have the following properties:

Name Type Description
type type The Java type of the expression
isParenthesized bool Whether there are parenthesis around this expression

arrayLength (pattern)

Matches all expressions that retrieve the length of an array. That is, expressions such as array.length.

Details

This pattern only matches nodes of type expression.

Properties

arrayLength produces a record that contains the following property:

Name Type Description
array expression The array to get the length of

Inherits properties from:

astnode

Example

The following pattern finds all array length expressions for integer arrays:

CXM code follows
pattern integerArrayLength { arrayLength { .array == expression { .type == integerType } } };

boxExpression (pattern)

Matches box expressions, both boxing and unboxing.

Details

This pattern only matches nodes of type expression.

Properties

boxExpression produces a record that contains the following properties:

Name Type Description
boxMethod symbol? The function symbol of the boxing method, if the expression is being boxed; null otherwise
expression expression The expression being boxed or unboxed
unboxMethod symbol? The function symbol of the unboxing method, if the expression is being unboxed; null otherwise

Inherits properties from:

astnode

Example

The following pattern matches all unboxing expressions:

CXM code follows
pattern unboxingExpression { unboxExpression { .unboxMethod == NonNull } };

enumReference (pattern)

Matches expressions that refer to an enum.

Details

This pattern only matches nodes of type expression.

Properties

enumReference produces a record that contains the following property:

Name Type Description
enumVariableSymbol symbol The enum symbol that refers to this enum

Inherits properties from:

astnode

Example

The following pattern matches enum occurrences that have the identifier Example:

CXM code follows
pattern enumReferenceExample { enumReference { .enumVariableSymbol == enumVariableSymbol { .simpleName == "Example" } } };

fieldAccess (pattern)

Matches all accesses to fields.

Details

This pattern only matches nodes of type expression.

Properties

fieldAccess produces a record that contains the following properties:

Name Type Description
field symbol The symbol of the field being accessed
objectExpression expression The object that owns the field being accessed

Inherits properties from:

astnode

Example

For a class like this:

Java code follows
class Example {
public int myPublicInt;
};

... and an access like:

Java code follows
Example e;
int i = e.myPublicInt;

... the following pattern finds the accesses:

CXM code follows
pattern accessToExamplePublicInt { fieldAccess { .objectExpression == expression { .type == classType { .simpleName == "Example" } }; .field == symbol { .simpleName == "myPublicInt" } } };

fieldReference (pattern)

Matches where fields are referenced in expressions.

Details

This pattern only matches nodes of type expression.

Properties

fieldReference produces a record that contains the following property:

Name Type Description
fieldSymbol symbol The name of the field

Inherits properties from:

astnode

Example

The following pattern matches when the field example is referenced:

CXM code follows
pattern referringToExample { fieldReference { .fieldSymbol == symbol { .simpleName == "example"} } };

functionCall (pattern)

Matches function call sites.

Details

This pattern only matches nodes of type expression.

Properties

functionCall produces a record that contains the following properties:

Name Type Description
argumentList list<expression> A list of the arguments passed to the function
calledExpression expression The expression of the function being called
calledFunction functionSymbol The symbol of the function being called
isNonStaticMethod bool true if the function being called is a non-static method
resolvedCallees list<symbol> A list of the callees

Inherits properties from:

astnode

Example

The following pattern in CodeXM finds function calls that have anything but variable references as their arguments:

CXM code follows
pattern nonReferenceArgument { functionCall as fn where exists a in fn.argumentList where ! (a matches variableReference) };

functionReference (pattern)

Matches where expressions reference a function.

Details

This pattern only matches nodes of type expression.

Properties

functionReference produces a record that contains the following property:

Name Type Description
functionSymbol symbol The symbol representing the function

Inherits properties from:

astnode

Example

The following CodeXM matches calls to a function example():

CXM code follows
pattern callToExample { functionCall { .calledExpression == functionReference { .functionSymbol == functionSymbol { .simpleName == "example" } } } };

See Also

functionCall

instanceOf (pattern)

Matches instanceof expressions.

Properties

instanceOf produces a record that contains the following properties:

Name Type Description
expression expression The expression being examined by instanceof
referenceType type The type the expression is being compared with

Inherits properties from:

astnode

Example

The following pattern matches all calls to instanceof for the class type Example:

CXM code follows
pattern instanceOfExample { instanceOf { .referenceType == classType { .simpleName == "Example" } } };

referenceDereference (pattern)

Matches situations where expressions with type reference are being dereferenced.

Details

This pattern only matches nodes of type expression.

Properties

referenceDereference produces a record that contains the following property:

Name Type Description
referencedExpression expression The expression being dereferenced

Inherits properties from:

astnode

Example

For the following Java function:

Java code follows
int myFunction(MyObject o) {
return o.a + o.b; // o is dereferenced twice here
return o.a + o.b; // o is dereferenced twice here
};

... you could match the dereference of the parameter o by using the following pattern:

CXM code follows
pattern addingWithReference { binaryOperator as b where b.operation == `+` && ( ( b.lhsExpression matches fieldAccess { .objectExpresion == referenceDereference } ) || ( b.rhsExpression matches fieldAccess { .objectExpresion == referenceDereference } ) ) };

See Also

referenceType

subscriptReference (pattern)

Matches all uses of a subscript operator on an array.

Details

This pattern only matches nodes of type expression.

Properties

subscriptReference produces a record that contains the following properties:

Name Type Description
arrayExpression expression The array the subscript is being used on
indexExpression expression The value inside the brackets ( [ ] )

Inherits properties from:

astnode

Example

The following CodeXM matches where a variable reference is used as the index expression of the array lookup:

CXM code follows
pattern variableArrayLookup { subscriptReference { .indexExpression == variableReference } };

variableReference (pattern)

Matches locations where an expression references a variable.

Details

This pattern only matches nodes of type expression.

Properties

variableReference produces a record that contains the following properties:

Name Type Description
isFinal bool true if this variable is declared as final
qualifiedName string The name of the variable, with scope information
scope enum variableScopeEnum The scope of the variable: One of `static`, `local`, or `tryResource`; see variableScopeEnum
simpleName string The name of the variable, without scope information
variable symbol The symbol that represents this variable

Inherits properties from:

astnode

Example

The following CodeXM matches all variable references to final static variables:

CXM code follows
pattern variableReferenceStaticFinal { variableReference { .scope == `global`; .isFinal == true; } };

Literals

These patterns match literal values in the target code.

booleanLiteral (pattern)

Matches Boolean literals; that is, both true and false

Details

This pattern only matches nodes of type expression.

Properties

booleanLiteral produces a record that contains the following properties:

Name Type Description
value enum `true` or `false`

Inherits properties from:

astnode

Example

The following pattern matches all Boolean literals:

CXM code follows
pattern trueBooleanLiteral { booleanLiteral { .value == true } };

characterLiteral (pattern)

Matches character literals.

Details

This pattern only matches nodes of type expression.

Properties

characterLiteral produces a record that contains the following properties:

Name Type Description
value int The value of the character

Inherits properties from:

astnode

Example

The following pattern matches all character literals 'a':

CXM code follows
pattern lowercaseA { characterLiteral { .value == 'a' } };

classLiteral (pattern)

Matches class literals.

Details

This pattern only matches nodes of type expression.

Properties

classLiteral produces a record that contains the following properties:

Name Type Description
targetType type The type of the class

Inherits properties from:

astnode

Example

To match literals for the class Example, use the following pattern:

CXM code follows
pattern exampleClassLiteral { .targetType == classType { .simpleName == "Example"} };

floatLiteral (pattern)

Matches float literals.

Details

This pattern only matches nodes of type expression.

Properties

floatLiteral produces a record that contains the following properties:

Name Type Description
isHexFloat bool true if this float is represented using hexadecimal
suffix enum? The suffix of the literal: either `f` or null
valueString string The value of the float, represented as a string

Inherits properties from:

astnode

Example

The following expression:

Java code follows
float f = 2.5;

... could be matched using this pattern:

CXM code follows
f matches floatLiteral { .valueString == "2.5" };

integerLiteral (pattern)

Matches all integer literals. That is, all integer literals of kind `short`, `byte`, `int`, and `long`.

Details

This pattern only matches nodes of type expression.

Properties

integerLiteral produces a record that contains the following properties:

Name Type Description
base enum One of `binary`, `decimal`, `octal`, or `hexadecimal`
kind enum intKind One of `short`, `byte`, `int`, or `long`; see intKind
value int The value of the integer literal

Inherits properties from:

astnode

Example

The following pattern matches only long integer literals:

CXM code follows
pattern longIntegerLiteral { integerIteral { .kind == `long` } };

nullLiteral (pattern)

Matches all null literals.

Details

This pattern only matches nodes of type expression.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

Example

The following pattern finds all assignments to null (for example, a = null):

CXM code follows
pattern assignmentToNull { assignmentOperator { sourceExpression == nullLiteral } };

stringLiteral (pattern)

Matches all string literals.

Details

This pattern only matches nodes of type expression f.

Properties

stringLiteral produces a record that contains the following properties:

Name Type Description
valueString string The value of the string literal

Inherits properties from:

astnode

Example

The following pattern finds assignments from the string literal "Example":

CXM code follows
pattern assignmentsToStringLiterals { assignmentOperator { .sourceExpression == stringLiteral { .value == "Example" } } };

Operators

These patterns match operators in the target code.

assignmentOperator (pattern)

Matches all forms of the assignment-operator expression.

Details

Even though variable declarations look similar to assignment operators, this pattern does not match variable declarations where the variable is initialized with a value (see variableDeclaration).

This general pattern matches both simple (a = b) and compound (a += b) forms of assignments.

This pattern only matches nodes of type expression.

Properties

assignmentOperator produces a record that contains the following properties:

Name Type Description
kind enum assignKind The kind of assignment, either `simple` or `compound`; see assignKind
operator enum The operator used: one of `=`, `+=`, `-=`, `*=`, `/=`, `|=`, `&=`, `%=`, `^=`, `>>=`, or `<<=`
sourceExpression expression The right-hand side of the assignment
targetExpression expression The left-hand side of the assignment

Inherits properties from:

astnode

Example

The following pattern matches any assignment where the source of the assignment is a cast:

CXM code follows
pattern assignedFromCast { assignmentOperator { .sourceExpression == castOperator } };

See Also

assignmentOperatorCompound, assignmentOperatorSimple

assignmentOperatorCompound (pattern)

Matches only compound assignment operators: for example, a += b.

Details

This pattern only matches nodes of type expression.

Properties

assignmentOperatorCompound produces a record that contains the following properties:

Name Type Description
kind enum assignKind Always `compound`; see assignKind
operator enum The operator used: one of `+=`, `-=`, `*=`, `/=`, `|=`, `&=`, `%=`, `^=`, `>>=`, or `<<=`
sourceExpression expression The right-hand side of the assignment
targetExpression expression The left-hand side of the assignment

Inherits properties from:

astnode

Example

The following pattern matches assignments that use the `+=` operator:

CXM code follows
pattern addCompoundAssignment { assignmentOperatorCompound { .operator == `+=` } };

See Also

assignmentOperatorSimple, assignmentOperator

assignmentOperatorSimple (pattern)

Matches only simple assignments, such as a = 1.

Details

Even though variable declarations look similar to assignment operators, this pattern does not match variable declarations. See variableDeclaration

This pattern only matches nodes of type expression.

Properties

assignmentOperatorSimple produces a record that contains the following properties:

Name Type Description
kind enum assignKind Always `simple`; see assignKind
operator enum Always `=`
sourceExpression expression The right-hand side of the assignment
targetExpression expression The left-hand side of the assignment

Inherits properties from:

astnode

Example

The following example matches all simple assignments to a null literal:

CXM code follows
pattern assignmentToNullLiteral { assignmentOperatorSimple { .sourceExpresion == nullLiteral } };

See Also

assignmentOperatorCompound, assignmentOperator

binaryOperator (pattern)

Matches all possible binary operations in Java.

Details

This pattern only matches nodes of type expression.

Complex binary operations are specifically represented with the correct order of operations, regardless of operator precedence (the compiler has already evaluated the precedence in order to build the expression’s tree structure). When pattern matching, be aware that either operand of a binary operator, or both, can also act as binary operators representing operations that are completed before the match operation is performed.

Properties

binaryOperator produces a record that contains the following properties:

Name Type Description
isImplicit bool true if the operator is implicit
lhsExpression expression The left-hand side of the expression
operator enum The operator this pattern represents. One of `=`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `*`, `/`, `%`, `+`, `-`, `<<`, `>>`, `&`, `^`, `|`, `&&`, `||`, `,`, `+=`, `-=`, `*=`, `/=`, `|=`, `&=`, `%=`, `^=`, `>>=`, or `<<=`
rhsExpression expression The right-hand side of the expression

Inherits properties from:

astnode

Nested Expressions

When pattern matching, be aware that either or both operands of a binary operator can themselves be binary operators that represent operations to be completed before the matched operation is performed.

For example, a + b * c is understood as a + (b * c) due to operator precedence. This is matched as a binary addition that has a right-hand operand of b * c. The value of the subexpression must be computed before the addition is performed.

On the other hand, (a + b) * c is matched as a binary multiplication. The left-hand operand, a + b, must be computed before it is multiplied by c.

The following illustration shows these two situations:

Parsing binary operations

In both these cases, a binaryOperator { .operand == `*` } pattern matches some part of the expression. In the left-hand case, it matches b * c. In the right-hand case, it matches the entire expression.

Example

The following pattern matches only multiplication:

CXM code follows
pattern multiplicationOperation { binaryOperator { .operator == `*` } };

See Also

unaryOperator

castOperator (pattern)

Matches all kinds of casts.

Details

This pattern only matches nodes of type expression.

Properties

castOperator produces a record that contains the following properties:

Name Type Description
kind enum castKind (see below) The kind of cast represented
operandExpression expression The expression being cast

These are the possible values of the kind property (see also castKind):

Name Description
`checkedExplicit` An explicit checked cast
`checkedImplicit` An implicit checked cast
`explicit` An explicit cast; for example, (int) a
`implicit` An implicit cast
`uncheckedFromGenerics` An unchecked cast from generics

Inherits properties from:

astnode

Example

The following pattern matches all casts (implicit, explicit, checked) to type int:

CXM code follows
pattern castToInt { castOperator { .type == integerType { .kind == `int` } } };

castOperatorChecked (pattern)

Matches all checked casts in Java.

Details

This pattern only matches nodes of type expression.

Properties

castOperatorChecked produces a record that contains the following properties:

Name Type Description
kind enum castKind Always `checkedExplicit`; see castKind
operandExpression expression The expression being cast

Inherits properties from:

astnode

Example

For the following Java example:

Java code follows
Object o = "String";
String s = (String) o; // Checked cast

The following pattern can be used to find checked casts from Object:

CXM code follows
pattern checkedCastFromObject { castOperatorChecked { .operandExpression == expression { .type == classType { simpleName == "Object" } } } };

See Also

castOperatorExplicit, castOperatorImplicit, castOperator

castOperatorExplicit (pattern)

Matches explicit casts.

Details

This pattern only matches nodes of type expression.

Properties

castOperatorExplicit produces a record that contains the following properties:

Name Type Description
kind enum castKind Always `explicit`; see castKind
operandExpression expression The expression being cast

Inherits properties from:

astnode

Example

The following snippet of Java casts i to short:

Java code follows
int i = 5;
short a = (short) i;

... you could use the following pattern to match it:

CXM code follows
pattern castToShort { castOperatorExplicit { .type == shortType } };

See Also

castOperatorImplicit, castOperatorChecked, castOperator

castOperatorImplicit (pattern)

Matches casts that are implicit to the code; that is, not explicitly stated.

Details

This pattern only matches nodes of type expression.

Properties

castOperatorImplicit produces a record that contains the following properties:

Name Type Description
kind enum castKind Always `implicit`; see castKind
operandExpression expression The expression being cast

Inherits properties from:

astnode

Example

For the following snippet of Java:

Java code follows
Object o = "Example";

... there is an implicit cast between the string literal and the class Object. To detect such a cast, you could use the following pattern:

CXM code follows
pattern implicitCastFromString { castOperatorImplicit { .operandExpression == expression { .type == classType { .simpleName == "String"} } } };

See Also

castOperator, castOperatorExplicit, castOperatorChecked

conditionalOperator (pattern)

Matches the conditional operator (sometimes called the “ternary” operator), ?:.

Details

This pattern only matches nodes of type expression.

Properties

conditionalOperator produces a record that contains the following properties:

Name Type Description
conditionExpression expression The expression that is the condition of the operator (first argument)
falseExpression expression The expression on the false side of the operator (third argument)
trueExpression expression The expression on the true side of the operator (second argument)

Inherits properties from:

astnode

Example

The following pattern matches all conditional operators that use the ?: operator:

CXM code follows
pattern binaryOperatorCondition { conditionalOperator { .condtionExpression == binaryOperator } };

decrementOperator (pattern)

Matches all decrement operators, both prefix and postfix.

Details

This pattern only matches nodes of type expression.

Properties

decrementOperator produces a record that contains the following properties:

Name Type Description
kind enum Either `prefix` or `postfix`
operandExpression expression The expression the decrement operator is being applied to

Inherits properties from:

astnode

Example

The following example CodeXM matches when a postfix decrement operator is used to update a for loop:

CXM code follows
pattern forLoopPostfixDecrement { forLoop { .updateStatement == simpleStatement { .expression == decrementOperator { .kind == `postfix` } } } };

incrementOperator (pattern)

Matches all increment operators, both prefix and postfix.

Details

This pattern only matches nodes of type expression.

Properties

incrementOperator produces a record that contains the following properties:

Name Type Description
kind enum Either `prefix` or `postfix`
operandExpression expression The expression the increment operator is being applied to

Inherits properties from:

astnode

Example

The following example CodeXM matches when a prefix increment operator is used to update a for loop:

CXM code follows
pattern forLoopPrefixIncrement { forLoop { .updateStatement == simpleStatement { .expression == incrementOperator { .kind == `prefix` } } } };

See Also

decrementOperator

newOperator (pattern)

Matches the Java new operator.

Details

This pattern only matches nodes of type expression.

Properties

newOperator produces a record that contains the following properties:

Name Type Description
initializer initializer The expression evaluated to determine the initial condition
isImplicit bool true if the new operator is implicitly placed
objectType type The type of the object being created

Inherits properties from:

astnode

Example

The following pattern matches all new operations that create an object of type class Example:

CXM code follows
pattern exampleNew { newOperator { .objectType == classType { .simpleName == "Example" } } };

throwOperator (pattern)

Matches instances of the throw operator.

Details

This pattern only matches nodes of type expression.

Properties

throwOperator produces a record that contains the following property:

Name Type Description
operandExpression expression The expression being thrown by the operator

Inherits properties from:

astnode

Example

The following pattern will find all throws of type Exception:

CXM code follows
pattern throwException { throwOperator { .operandExpression == expression { .type == classType { .simpleName == "Exception" } } } };

unaryOperator (pattern)

Matches all possible unary operators in Java.

Details

This pattern only matches nodes of type expression.

Properties

unaryOperator produces a record that contains the following properties:

Name Type Description
operandExpression expression The expression the operation is performed on
operator enum The unary operator this pattern represents: One of `+`, `-`, `!`, or `~`

Inherits properties from:

astnode

Example

The folowing CodeXM pattern matches any use of the unary plus operator:

CXM code follows
pattern unaryPlus { unaryOperator { .operator == `+` } };

See Also

binaryOperator

Initializers

Patterns in this section belong to the initializer class—or to the ctorinit class, in the case of the constructor initializers. They match initializers in the target code.

In many cases, an initializer can look the same as an assigment statement. However, many languages treat initialization as its own, special case. The CodeXM language libraries treat initialization in this way, as well.

arrayDimensionsInitializer (pattern)

Matches multidimensional array initialization.

Details

This pattern only matches nodes of type initializer.

Properties

arrayDimensionsInitializer produces a record that contains the following property:

Name Type Description
dimensions list<expression> List of dimensions

Inherits properties from:

astnode

Example

Matches array initialization that uses this format:

Java code follows
int a[][][] = new int[3][][];

arrayInitializer (pattern)

Matches array initialization that uses curly braces.

Details

This pattern only matches nodes of type initializer.

Properties

arrayInitializer produces a record that contains the following property:

Name Type Description
variableInitializerList list<initializer> A list of the elements within the curly braces

Inherits properties from:

astnode

Example

Matches array initialization that uses this format:

Java code follows
int[] a = {0, 1};

baseClassInitializer (pattern)

Matches initialization calls to super().

Details

This pattern only matches nodes of type type.

Properties

baseClassInitializer produces a record that contains the following property:

Name Type Description
baseClass type The classType of the base type being called

Inherits properties from:

astnode

Example

For the following snippet of Java:

Java code follows
class Example extends BaseExample {
public Example() {
super();
}
};

... the following pattern matches all calls to super() for the class `BaseExample`:

CXM code follows
pattern baseExampleSuper { baseClassInitializer { .baseClass == classType { .simpleName == "BaseExample" } } };

constructorInitializer (pattern)

Matches cases where a constructor is used to initialize an object.

Details

This pattern only matches nodes of type initializer.

Properties

constructorInitializer produces a record that contains the following properties:

Name Type Description
arguments list<expression> A list of arguments passed to the constructor
constructorFunction symbol A symbol that represents the constructor function used
enclosingClassReference expression? Non-null when there is an inner class used. For example, in the initializer y.new X() this value would represent y. null if there is no inner class.

Inherits properties from:

astnode

Example

Given the following Java initialization:

Java code follows
ExampleObj o = new ExampleObject(5);

... you can use the following CodeXM patrtern to match it. The example pattern below matches a constructor that uses an integer literal for its argument:

CXM code follows
pattern ExampleObjectInitlizeLiteral { constructorInitializer as c where exists e in c.arguments where e matches integerLiteral };

expressionInitializer (pattern)

Matches simple expression initializers used to initialize scalar objects.

Details

This pattern only matches nodes of type initializer.

Properties

expressionInitializer produces a record that contains the following property:

Name Type Description
expression expression The expression that evaluates to a value used to initialize the object

Inherits properties from:

astnode

Example

Matches the following Java initialization:

Java code follows
int a = x + y;

For example, the following pattern matches all initializations done using binary operation:

CXM code follows
pattern binaryOperationInitializer { expressionInitializer { .expression == binaryOperator; } };

memberInitializer (pattern)

Matches locations where a member is being initialized as part of a call to a constructor.

Details

This pattern only matches nodes of type type.

Properties

memberInitializer produces a record that contains the following property:

Name Type Description
field symbol The fieldSymbol of the member being initialized

Inherits properties from:

astnode

peerConstructorInitializer (pattern)

Matches situations where a constructor uses another constructor within the same class.

Details

This pattern only matches nodes of type type.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

zeroInitializer (pattern)

Matches initializations where no value is given.

Details

This pattern only matches nodes of type initializer.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

Example

For a given class:

Java code follows
class Example {
private int a;
};

... the initialization of the field a will be a zeroInitializer

Symbols

These patterns match symbols in the target code.

A symbol is an entity that can have an identifier; for example, a symbol might be a variable, a function, or a field in a record.

In Coverity Analysis, each symbol in a program is its own node in the abstract syntax tree, and is distinct from the identifier that represents it in the source.

Common Properties of Symbols

In addition to the properties that are specific to each pattern, all symbol patterns have the following properties in common:

Name Type Description
identifier string? The string used as an unqualified name for the symbol; null if there is none
mangledName string? The internal “mangled” name used for the symbol (the mangled name includes type and scope information, to disambiguate this instance of the identifier); null if the mangled name is not available
location sourceloc The location where this symbol was declared
type type The Java type declared for this symbol
access enum AccessKeyword The scoping keywords associated with the symbol, such as `public` or `private`
is_file_or_readonly bool true if the symbol has a final specifier
scopeList list<string> A list of the class names and namespaces that enclose the symbol

enumVariableSymbol (pattern)

Matches symbols used in an enum declarations.

Details

This pattern only matches nodes of type symbol.

Properties

enumVariableSymbol produces a record that contains the following properties:

Name Type Description
parentEnum classType The parent enum class of this enum value
qualifiedName string The name of the enum value, including any scope information
simpleName string The name of the enum value, without scope information

Inherits properties from:

symbol

Example

The following example finds all uses of enum variables:

CXM code follows
pattern enumVariableUse { variableReference { .variable == enumVariableSymbol } };

fieldSymbol (pattern)

Matches a field symbol in a class declaration.

Details

This pattern only matches nodes of type symbol.

Properties

fieldSymbol produces a record that contains the following properties:

Name Type Description
access enum The type of access to the field: `public`, `private`, or `protected`
annotations list<codeAnnotation> A list of the code annotations applied to this field
isFinal bool true if the field is declared final
isTransient bool true if the field is declared transient
isVolatile bool true if the field is declared volatile
ownerClass classType The class that this field belongs to
qualifiedName string The name of the field, including any scope information
simpleName string The name of the field, excluding scope information

Inherits properties from:

symbol

Example

The following pattern finds all field accesses to private fields:

CXM code follows
pattern privateFieldAccess { fieldAccess { .field == fieldSymbol { .access == `private`} } };

functionSymbol (pattern)

Matches symbols used to declare functions.

Details

This pattern only matches nodes of type symbol.

Properties

functionSymbol produces a record that contains the following properties:

Name Type Description
annotations list<codeAnnotation> A list of the code annotations applied to this function
explicitParameterCount int The number of explicit parameters this function has
functionType functionType The type of the function
hasThis bool true if the function has the implicit this argument
isAbstract bool true if the function is declared abstract
isClassInitializer bool true if this function is a class initializer
isCompilerGenerated bool true if the function is compiler-generated
isConstructor bool true if the function is a constructor
isFinal bool true if the function is declared final
isStaticMethod bool true if the function is a static method
isStrictfp bool true if the function is declared with strictfp
isSynchronized bool true if the function is declared with synchronized
isVirtual bool true if the function is declared virtual
qualifiedName string The name of the function, including any scope information
simpleName string The name of the function, without scope information

Inherits properties from:

symbol

Example

The following pattern finds all function calls to synchronized functions:

CXM code follows
pattern callToSynchronized { functionCall { .calledFunction == functionSymbol { .isSynchronized == true } } };

localVariableSymbol (pattern)

Matches variable symbols used in variable declarations.

Details

This pattern only matches nodes of type symbol.

Properties

localVariableSymbol produces a record that contains the following properties:

Name Type Description
isFinal bool true if the variable is declared as final
qualifiedName string The name of the variable, including any scope information
simpleName string The name of the variable, without scope information

Inherits properties from:

symbol

Example

The following example finds all uses of local variables:

CXM code follows
pattern localVariableUse { variableReference { .variable == localVariableSymbol } };

parameterSymbol (pattern)

Matches parameter symbols used in function definitions.

Details

This pattern only matches nodes of type symbol.

Properties

parameterSymbol produces a record that contains the following properties:

Name Type Description
access enum The type of access: `public`, `private`, or `protected`
extra string Extra information used for defect reporting
isFinal bool true if the parameter is declared as final
isThis bool true if the parameter is the implicit this parameter
ownerClass classType The owner class for the symbol
position string The position of the parameter in the function
qualifiedName string The name of the class, including scope information
scopeList list<string> The scope of the parameter. This is the elements of the qualified name, broken up into a list.
simpleName string The name of the parameter, without scope information
type type The type of the parameter

Inherits properties from:

symbol

Example

The following example CodeXM pattern finds all uses of parameters with a referenceType type:

CXM code follows
pattern useOfReferenceType { variableReference { .variable == parameterSymbol { .type == referenceType } } };

staticVariableSymbol (pattern)

Matches symbols for variables defined as static within a class.

Details

This pattern only matches nodes of type symbol.

Properties

staticVariableSymbol produces a record that contains the following properties:

Name Type Description
annotation list<codeAnnotation> Any code annotations on this variable
isFinal bool true if the variable is declared final
ownerClass classType The class that contains this variable
qualifiedName string The name of the variable, including any scope information
simpleName string The name of the variable, without scope information

Inherits properties from:

symbol

Example

The following example finds all uses of statically defined variables:

CXM code follows
pattern staticVariableUse { variableReference { .variable == staticVariableSymbol } };

variableSymbol (pattern)

Matches the symbols of all declared variables.

Details

This pattern only matches nodes of type symbol.

Properties

variableSymbol produces a record that contains the following properties:

Name Type Description
isFinal bool true if the variable is declared final
qualifiedName string The name of the variable, including any scope information
scope enum variableScopeEnum `local` for local variables, `static` for statically defined variables, or `tryResource` for a try-with-resource variable; see variableScopeEnum
simpleName string The name of the variable, without scope information

Inherits properties from:

symbol

See Also

staticVariableSymbol, localVariableSymbol, enumVariableSymbol, parameterSymbol

Records

These are records that can be used within CodeXM patterns to match declarations, code attributes, or handlers for try/catch blocks.

annotationElementValuePair (record)

In a list of code annotations, represents an element-value pair.

Properties

annotationElementValuePair produces a record that contains the following properties:

Name Type Description
key string The name of the element
value annotationElement The value of the element

codeAnnotation (record)

Represents a code annotation. Annotations can be placed on classes, class variables, or methods.

Properties

codeAnnotation produces a record that contains the following properties:

Name Type Description
annotationType classType The annotation type
elements list<annotationElementValuePair> The element-value pairs

Example

This type can be used to inspect things like the @Deprecated annotation in the following sample code:

Java code follows
class Example {
@Deprecated
void myFunction() {
// ...
}
};

See Also

classDefinition, staticVariableSymbol, functionSymbol, fieldSymbol

declaration (record)

Represents a declaration.

Properties

declaration produces a record that contains the following properties:

Name Type Description
initializer initializer? An initializer; null if there is none
kind variableDeclarationKind The kind of declaration
variable symbol The symbol variable

Example

The following pattern matches a try-with-resource statement, using a resource with the name myResource:

CXM code follows
let myResourceDeclaration = pattern { declaration { .variable == localVariableSymbol { .simpleName == "myResource" } } } in patternResourceTry { tryStatement as t where exists r in t.resourcesList where r matches myResourceDeclaration };

See Also

tryStatement

handler (record)

Represents exception handlers in try/catch blocks.

Properties

handler produces a record that contains the following properties:

Name Type Description
body blockStatement The body of the exception handler
variable localVariableSymbol The variable representing the exception caught

Example

The following CodeXM pattern matches handlers that declare a variable named Exception in catch statements; for example, catch ( Exception ex ):

CXM code follows
let exceptionHandleWithVar = pattern { handler { .variable == NonNull } } in pattern tryCatchWithVar { tryStatement as t where exists r in t.catchBlockList where r matches exceptionHandleWithVar };

See Also

tryStatement

Functions

The Java library provides a number of functions to help you handle, and analyze, the target source code.

See the Common Library Reference for descriptions of some general-purpose functions that are available to all language libraries.

Definition Functions

Definition functions retrieve class definitions.

getClassDefinition( classTypeResult )

Gets the class definition of a given class type, if that is available to the analysis.

Parameters and Return Value

Name Type Description
classTypeResult classType The classType to fetch the definition of
return value classDefinition Returns the class definition if one is available; otherwise returns null.

Type Functions

Type functions handle elaborated types.

hasBaseType( t )

Returns the type that a referenceType points to, or the type of the elements in an array.

Parameters and Return Value

Name Type Description
t type The type to return the base type of
return value type The base type of the argument

Example

Using the function hasBaseType on the array int[] a gives you the result integerType.

stripReferenceTypes( t )

Removes referenceTypes around a “base type”.

Details

Sometimes it is useful to strip away one or more reference types in order to inspect what the reference is pointing to. If a type other than a referenceType is passed, that same type is returned.

Parameters and Return Value

Name Type Description
t type The type to strip referenceTypes from. This does not itself necessarily need to be a referenceType.
return value type The type, stripped of any referenceTypes

Example

For the following Java code:

Java code follows
void myExampleFunction(ExampleClass c) {
// ...
};

... the parameter c can be passed as a referenceType. To inspect the type being referenced, we can specify:

CXM code follows
pattern isReferenceToExampleClass { referenceType as t where stripReferenceType(t) matches classType { .simpleName == "ExampleClass" } };

See Also

arrayType, referenceType

Decomposing Functions

Decomposing functions deal explicitly with managing casts and qualifiers.

arrayOf( typePattern )

Generates a pattern to match arrays of a particular type.

Parameters and Return Value

Name Type Description
typePattern pattern A pattern matching a type
return value pattern A pattern matching an array type

Example

The following CodeXM snippet returns a pattern, intArray, that matches arrays of type int:

CXM code follows
let intArray = arrayOf(pattern integralType { .kind == `int` }) in for code in globalset allFunctionCode where code matches intArray // ...

See Also

arrayType

stripBoxes( e )

Strips an outermost box expression, if one is present, and returns the underlying expression.

If the expression consists of sub-expressions which themselves are box expressions, those expressions are also stripped.

Parameters and Return Value

Name Type Description
e expression The expression to strip boxes from
return value expression The expression with the boxes removed

Example

In the following Java snippet:

Java code follows
int[] lst = {0, 1, 2};
Integer sum = new Integer(0);
for (int i : lst) {
sum += i; // Box expression here
};

... to examine the variable on the right-hand side of the assignmentOperatorCompound, the function stripBoxes could be called on the sourceExpression of that assignment expression.

See Also

stripCasts, stripCastsAndBoxes

stripCasts( e )

Strips an outermost cast, if one is present, and returns the underlying expression.

If the expression consists of sub-expressions which themselves are being cast, those casts are also stripped.

Parameters and Return Value

Name Type Description
e expression The expression to strip casts from
return value expression The expression with casts removed

Example

To examine the variable i in the assignment below:

Java code follows
void example(int i, short s) {
class="targetline" s = (short) i;
};

... the function stripCasts could be used on the sourceExpression of the assignmentOperator.

See Also

stripBoxes, stripCastsAndBoxes

stripCastsAndBoxes( e )

Strips an outermost cast or box expression, if one of those is present, and returns the underlying expression.

If the expression consists of sub-expressions which themselves are a cast or a box expression, those expressions are also stripped.

Parameters and Return Value

Name Type Description
e expression The expression to strip boxes and casts from
return value expression The expression, with boxes and casts removed

Example

See the examples of stripCasts and stripBoxes

See Also

stripCasts, stripBoxes

stripImplicitCasts( e )

Decomposes expressions with implicit casts; that is, casts that are not explicitly placed in the source code, but are implicitly created by Java.

Parameters and Return Value

Name Type Description
e expression The expression to strip casts from.
return value expression The expression, free of casts. If the expression passed to this function is not a cast, stripImplicitCasts simply returns the expression itself.

Example

When assigning between integer kinds, implicit casts can occur. For example:

Java code follows
short s = 5;
long l;
l = s; // Implicit cast here

To match all assignments from short integers, you might need to use stripImplicitCasts as follows:

CXM code follows
pattern allAssignmentsFromShorts { assignmentOperator as assignment where stripImplicitCasts(assignment.sourceExpression) matches variableReference as v && v.type matches integerType { .kind == `short` } };

Overridee Functions

An overridee function returns the symbols that have been used to override a specified function symbol.

getFunctionOverridees( f )

Returns all the overridees of a given functionSymbol.

Parameters and Return Value

Name Type Description
f functionSymbol The functionSymbol to get the overridees of
return value set<functionSymbol> The overridees of the argument, as a set

Example

The following CodeXM function determines if a function overrides a function, example():

CXM code follows
function overridesExample( f : typeof(functionSymbol).producedType ) : bool -> let overridees = getFunctionOverridees(f) in for a in overridees accumulate b : bool = false : a matches functionSymbol { .simpleName == "example" } || b;