Synopsys logo

Coverity® 2020.12 CodeXM

Python Library Reference

Introduction

Specifying the Target Language

Class Definitions

‘enum’ Kinds

Code Patterns

Functions

Python 2 Patterns

Python 3 Patterns

Hide/show Contents

Hide/show Contents

Coverity® 2020.12 CodeXM

Python 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 defects with messages that you provide. Like other Coverity checkers, the defects are displayed in Coverity Connect. They can be archived with the cov-commit-defect feature.

The CodeXM Python library provides access to Python coding constructs.

This document provides information about the patterns and functions provided by the Python 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.

CodeXM code appears in shades of green.

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 `Python`.

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? in the CodeXM Syntax Reference.

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.

functionDefinition (class)

Describes a function definition.

Properties

functionDefinition produces a record that contains the following properties:

Name Type Description
allCode set<astnode> All nodes within the function. If the object is a variable, this list contains only the variable’s initializer.
body statement The function body. This is a blockStatement.
formalParameterList list<symbol> A list that contains one parameterSymbol for each function parameter
functionSymbol symbol The symbol that represents this function
isScriptFunction bool true if this function definition defines the body of the Python script
location sourceloc The location in the code: can be used for defect reporting
paths executionPaths The executable paths that can be used for path-sensitive analysis
qualifiedName string? The name of the function, including scope information; null if the name is not available
simpleName string? The name of the function, excluding scope information; null if the name is not available

‘enum’ Kinds

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

assignmentKind (enum)

The type of an assignment statement.

Details

assignmentKind defines the following values:

Name Description
`augmented` Augmented assignment using one of the following operators: +=, -=, *=, /=, |=, &=, %=, ^=, >>=, or <<=
`simple` Simple assignment using the = operator

See Also

assignmentStatement

numberKind (enum)

The type of a numeric value.

Details

numberKind defines the following values:

Name Description
`boolean` A Boolean value (true or false)
`complex` A complex value. Complex numbers are represented by a pair of machine-level double-precision floating-point values.
`int` A 32-bit integer value
`long` An integer value of arbitrary length. The possible length is limited by the available virtual memory.
`real` A machine-level double-precision floating-point value

Note: The discrete types int and long are indistinguishable to the Python library. The same is true of the continuous types real and complex, although you can search for the imaginary component of a complex value: see imaginaryLiteral.

variableScopeKind (enum)

The scope of a variable.

Details

variableScopeKind defines the following values:

Name Description
`global` The variable is available globally.
`local` The variable is available only locally; that is, within the scope of a particular function or class.

See Also

variableReference

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.

assertStatement (pattern)

Matches assert statements.

Details

The following CodeXM pattern matches assertions on Boolean literals—that is, assert(True)

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

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

assignmentStatement (pattern)

Matches assignment statements.

Details

This pattern only matches nodes of type statement.

Properties

assignmentStatement produces a record that contains the following properties:

Name Type Description
kind enum assignmentKind Either `simple` or `augmented`; see assignmentKind
assignmentOperator expression The expression that describes this assignment statement

Inherits properties from:

astnode

Example

The following CodeXM pattern matches simple assignment statements (that is, assignments that use the = operator):

CXM code follows
pattern simpleAssignment { assignmentStatement { .assignmentKind == `simple` } };

See Also

assignmentKind

blockStatement (pattern)

Matches block statements; that is, statements that contain a sequence of other statements.

Details

In Python, a block is also referred to as a suite.

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 that the block contains

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a blockStatement that contains a single passStatement:

CXM code follows
pattern passStatementBlock { blockStatement as blk where blk.containedStatements.length == 1 && blk.containedStatements[0] matches passStatement };

breakStatement (pattern)

Matches break statements.

Details

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-of-control statement, such as while, within which the break occurs

Inherits properties from:

astnode

Example

The following CodeXM pattern matches break statements within while loops:

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

See Also

whileLoop, forEachLoop, continueStatement

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 flow-of-control statement, such as while, within which the continue occurs

Inherits properties from:

astnode

Example

The following CodeXM pattern matches continue statements within while loops:

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

See Also

whileLoop, forEachLoop, breakStatement

delStatement (pattern)

Matches del statements.

Details

This pattern only matches nodes of type statement.

Properties

delStatement produces a record that contains the following properties:

Name Type Description
expression expression The expression to be deleted

Inherits properties from:

astnode

Example

The following CodeXM pattern matches del statements applied to global variables:

CXM code follows
pattern delGlobalVariable { delStatement { .expression == variableReference { .scope == `global` } } };

expressionStatement (pattern)

Matches individual executable expressions.

Details

This pattern only matches nodes of type statement.

Properties

expressionStatement produces a record that contains the following properties:

Name Type Description
expression expression The expression itself

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a function call:

CXM code follows
pattern expressionStatementFunctionCall { expressionStatement { .expression == functionCall } };

forEachLoop (pattern)

Matches for loop statements.

Details

This pattern only matches nodes of type statement.

Properties

forEachLoop produces a record that contains the following properties:

Name Type Description
bodyStatement statement The statement that the loop repeatedly executes. Frequently this is a block statement.
elseStatement statement The statement executed when the loop terminates.
isAsync bool true if the loop is declared as async (Python 3)
iterableExpression expression The iterable object

Inherits properties from:

astnode

Example

The following CodeXM pattern finds all for loops over empty literal lists:

CXM code follows
pattern forOverListLiteral { forEachLoop { .iterableExpression == listLiteral } as f where f.iterableExpression.expressions.empty };

See Also

whileLoop

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
conditionExpression expression The condition of the if
falseStatement statement? The statement to execute if the condition is false; null if there is none
trueStatement statement The statement to execute if the condition is true

Inherits properties from:

astnode

Example

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

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

importStatement (pattern)

Matches import statements.

Details

This pattern only matches nodes of type statement.

Properties

importStatement produces a record that contains the following properties:

Name Type Description
moduleSpecification string? The name of the imported module; null if there is no name
target expression? The name of the target variable in a named import—for example, Sys in import sys as Sys; null if there is none

Inherits properties from:

astnode

Example

The following CodeXM pattern matches statements that import from a module named sys:

CXM code follows
pattern sysImport { importStatement { .moduleSpecification == "sys" } };

passStatement (pattern)

Matches pass statements.

Details

This pattern only matches nodes of type statement.

Properties

passStatement produces a record that contains the following properties:

Name Type Description
isImplicit bool true if the statement is compiler-generated

Inherits properties from:

astnode

Example

The following CodeXM pattern matches pass statements in the body of conditionals:

CXM code follows
pattern passInIf { passStatement { .parent == ifStatement } };

raiseStatement (pattern)

Matches raise statements.

Details

This pattern only matches nodes of type statement.

Properties

raiseStatement produces a record that contains the following properties:

Name Type Description
expression expression The exception that the statement raises

Inherits properties from:

astnode

Example

The following CodeXM pattern matches raise statements that throw Exception("Error!"):

CXM code follows
pattern raiseErrorException { raiseStatement { .expression == stringLiteral { .valueString == "Error!" } } };

returnStatement (pattern)

Matches either simple return statements or return <expression>.

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 function does not return an expression
returnedExpression expression? The expression that the function returns; null if there is none

Inherits properties from:

astnode

Example

The following CodeXM pattern matches return statements that do not return a value:

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

tryStatement (pattern)

Matches try statements, including any except, finally, or else blocks.

Details

This pattern only matches nodes of type statement.

Properties

tryStatement produces a record that contains the following properties:

Name Type Description
elseBlock list<statement>? The statements in the else block; null if there is no else
exceptHandlers list<statement> The statements in the except block
finallyBlock statement? The statement in the finally block; null if there is no finally
tryBlock statement The statement in the try block

Inherits properties from:

astnode

Example

The following CodeXM pattern matches try statements that contain both finally and else blocks:

CXM code follows
pattern hasElseAndFinally { tryStatement { .elseBlock == NonNull; .finallyBlock == NonNull } };

whileLoop (pattern)

Matches while loop statements.

Details

This pattern only matches nodes of type statement.

Properties

whileLoop produces a record that contains the following properties:

Name Type Description
bodyStatement statement The statement in the loop. Often this is a block statement.
conditionExpression expression The loop condition
elseStatement list<statement>? The statements executed when the loop terminates; null if there are none

Inherits properties from:

astnode

Example

The following CodeXM pattern finds all while loops whose condition is the Boolean value True:

CXM code follows
pattern whileTrueLoop { whileLoop { .conditionExpression == booleanLiteral { .value == true } } };

See Also

forEachLoop

yieldBreakStatement (pattern)

Matches the end of yield-generators.

Details

Note: Python does not actually have a statement to mark the end of a yield, but the Python library places a node in the abstract syntax tree to enable you to match this situation.

This pattern only matches nodes of type statement.

Properties

yieldBreakStatement does not expose any new properties.

Inherits properties from:

astnode

yieldStatement (pattern)

Matches yield statements.

Details

This pattern only matches nodes of type statement.

Properties

yieldStatement produces a record that contains the following properties:

Name Type Description
expression expression The expression being yielded

Inherits properties from:

astnode

Example

The following CodeXM pattern matches statements that yield an integer:

CXM code follows
pattern yieldInteger { yieldStatement { .expression == integerLiteral } };

Declarations

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

classDeclaration (pattern)

Matches class declarations.

Details

This pattern only matches nodes of type statement.

Properties

classDeclaration produces a record that contains the following properties:

Name Type Description
baseClasses list<variableReference> The base classes of this class
constructor symbol The constructor function for this class
instanceMembers list<statement>? This class’s instance members and properties; null if there are none
name expression The name of the class
staticMembers list<statement>? This class’s static methods; null if there are none

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a class declaration that inherits from a class named Foo:

CXM code follows
pattern inheritsFromFoo { classDeclaration as decl where ( exists c in decl.baseClasses where c matches variableReference { .simpleName == "Foo" } ) };

functionDeclaration (pattern)

Matches function declarations.

Details

This pattern only matches nodes of type statement.

Properties

functionDeclaration produces a record that contains the following properties:

Name Type Description
argumentInfo mapLiteral The initialization map for this function
functionSymbol symbol The symbol for this function
isAsync bool true if the function is declared async (Python 3)

Inherits properties from:

astnode

Example

The following CodeXM pattern matches the declaration of a function named foo:

CXM code follows
pattern declarationFoo { functionDeclaration { functionSymbol == functionSymbol { .simpleName == "foo" } } };

localVariableDeclaration (pattern)

Matches declarations of local variables.

Details

This pattern only matches nodes of type statement.

Properties

localVariableDeclaration produces a record that contains the following properties:

Name Type Description
isCompilerGenerated bool true if the variable is generated by the compiler
qualifiedName string? The function name, including scope information; null if the name is not available
simpleName string? The function name, without scope information; null if the name is not available
variableType type The type of the variable

Inherits properties from:

astnode

Types

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

booleanType (pattern)

Matches the boolean type.

Details

This pattern only matches nodes of type type.

Properties

booleanType does not expose any properties.

Example

The following CodeXM code matches any expression of the type boolean:

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

compositeType (pattern)

Matches composite objects such as sequences, sets, and dictionaries.

Details

This pattern only matches nodes of type type.

Properties

compositeType does not expose any properties.

Example

The following CodeXM code matches any expression that has a composite type:

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

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
isMethod bool true if the function is a method
parameterTypeList list<type> The types of the function parameters
returnType type? The type that the function returns; null if there is no return expression

Example

The following CodeXM code matches any expression that has a function type:

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

integralType (pattern)

Matches integers of either the int or long type.

Details

This pattern only matches nodes of type type.

Properties

integralType does not expose any properties.

Example

The following CodeXM code matches any expression whose type is int or long:

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

realType (pattern)

Matches real numbers of the real, complex, or float type.

Details

This pattern only matches nodes of type type.

Properties

realType does not expose any properties.

Example

The following CodeXM code matches any expression whose type is real, complex, or float:

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

stringType (pattern)

Matches the string type.

Details

This pattern only matches nodes of type type.

Properties

stringType does not expose any properties.

Example

The following CodeXM code matches any expression whose type is string:

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

Expressions

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

Many statements in Python 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 Python type of the expression
isParenthesized bool Whether there are parenthesis around this expression

attributeReference (pattern)

Matches references to attributes; that is, expressions with dot notation such as test.type.

Details

This pattern only matches nodes of type expression.

Properties

attributeReference produces a record that contains the following properties:

Name Type Description
primaryExpression expression The base (the left-hand side) of the attribute reference expression
propertyExpression expression The accessed property (the right-hand side) of the attribute reference expression

Inherits properties from:

astnode

Example

The following CodeXM pattern matches an attribute expression that accesses a property named foo:

CXM code follows
pattern fooAttribute { attributeReference { .primaryExpression == stringLiteral { .valueString == "foo" } } };

duplicatedValue (pattern)

Matches expressions that describe other expressions already referenced in the abstract syntax tree (AST).

Details

Note: Python itself does not generate this pattern: It is a product of the Coverity AST.

This pattern only matches nodes of type expression.

Properties

duplicatedValue produces a record that contains the following properties:

Name Type Description
reusedExpression expression The reused expression

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a reused integer literal expression:

CXM code follows
pattern reusedInteger { duplicatedValue { .reusedExpression == integerLiteral } };

dynamicMapping (pattern)

Matches key/value mappings used in Python map and set data structures.

Properties

dynamicMapping produces a record that contains the following properties:

Name Type Description
key expression The key
value expression The value

Inherits properties from:

astnode

See Also

mapLiteral, setLiteral

functionCall (pattern)

Matches calls to functions

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> The arguments passed to the function
calledExpression expression The expression of the function being called
calledFunction functionSymbol The symbol of the function being called

Inherits properties from:

astnode

Example

The following CodeXM pattern finds function calls being passed arguments that are not variable references:

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

functionReference (pattern)

Matches references to function definitions.

Details

This pattern only matches nodes of type expression.

Properties

functionReference produces a record that contains the following properties:

Name Type Description
functionSymbol symbol The symbol of the referenced function

Inherits properties from:

astnode

lambdaExpression (pattern)

Matches lambda expressions.

Details

Python lambda expressions are represented by closures and have function definitions of their own.

Python 1 and Python 2: The lambda expression lambda x=1 : x is represented by the following abstract syntax:

        {
            _python_( function.__defaults__ = None ) ,
            ( ( function.__annotations__ = {} ) ,
            ( ( function.__doc__ = None ) , function ) )_
        }
        

Python 3: The lambda expression lambda x=1 : x is represented by the following abstract syntax:

        (
            function.__defaults__ = { 1 } ) ,
            ( ( function.__doc__ = None ) ,
            function
        )
        

In either case, you can use the assignmentOperator pattern to match the assignments that are implicit in the lambda expression.

This pattern only matches nodes of type expression.

Properties

lambdaExpression produces a record that contains the following properties:

Name Type Description
annotationsAssignmentOperator assignmentOperator? The assignment of the function.__annotations__ property (Python 3); null if this is not present
defaultsAssignmentOperator assignmentOperator The default argument values, function.__defaults__
docStringAssignmentOperator assignmentOperator The lambda doc string, function.__doc__
functionSymbol symbol The symbol of the lambda expression

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a lambda expression that accepts two arguments:

CXM code follows
pattern twoArgumentLambda { lambdaExpression { .functionSymbol == functionSymbol { .explicitParameterCount == 2 } } };

See Also

listComprehension, mapComprehension, setComprehension, tupleComprehension

listComprehension (pattern)

Matches list comprehensions.

Details

Python comprehensions are represented by closures (lambda-expressions) and have function definitions of their own.

This pattern only matches nodes of type expression.

Properties

listComprehension produces a record that contains the following properties:

Name Type Description
closure expression The lambda expression that describes the comprehension

Inherits properties from:

astnode

See Also

tupleComprehension, setComprehension, mapComprehension

mapComprehension (pattern)

Matches map comprehensions.

Details

Python comprehensions are represented by closures (lambda-expressions) and have function definitions of their own.

This pattern only matches nodes of type expression.

Properties

mapComprehension produces a record that contains the following properties:

Name Type Description
closure expression The lambda expression that describes the comprehension

Inherits properties from:

astnode

See Also

listComprehension, setComprehension, tupleComprehension

setComprehension (pattern)

Matches set comprehensions.

Details

Python comprehensions are represented by closures (lambda-expressions) and have function definitions of their own.

This pattern only matches nodes of type expression.

Properties

setComprehension produces a record that contains the following properties:

Name Type Description
closure expression The lambda expression that describes the comprehension

Inherits properties from:

astnode

See Also

listComprehension, tupleComprehension, mapComprehension

sliceExpression (pattern)

Matches slice expressions.

Details

A slice expression selects a range of items in a sequence. It has the following form: [<lowerBound>:<upperBound>:<stride>].

This pattern only matches nodes of type expression.

Properties

sliceExpression produces a record that contains the following properties:

Name Type Description
lowerBoundExpression expression? The lower bound of the sequence; null if this is absent
strideExpression expression? The stride of the sequence; null if this is absent
uppperBoundExpression expression? The upper bound of the sequence; null if this is absent

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a slice that selects a sequence that uses a stride of 1:

CXM code follows
pattern strideOfOneSlice { sliceExpression { .strideExpression == integerLiteral { .value == 1 } } };

subscriptExpression (pattern)

Matches subscript expressions.

Details

A subscript expression, enclosed in brackets ( [ ] ), selects an item of a sequence (a string, tuple, or list) or a mapping (dictionary) object.

This pattern only matches nodes of type expression.

Properties

subscriptExpression produces a record that contains the following properties:

Name Type Description
indexExpression expression The expression used as a subscript
primaryExpression expression The expression in which the subscript expression appears

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a subscript of 0:

CXM code follows
pattern subscriptOfZero { subscriptExpression { .indexExpression == integerLiteral { .value == 0 } } };

tupleComprehension (pattern)

Matches tuple comprehensions.

Details

Python comprehensions are represented by closures (lambda-expressions) and have function definitions of their own.

This pattern only matches nodes of type expression.

Properties

tupleComprehension produces a record that contains the following properties:

Name Type Description
closure expression The lambda expression that describes the comprehension

Inherits properties from:

astnode

See Also

listComprehension, setComprehension, mapComprehension

variableReference (pattern)

Matches references to variables.

Details

This pattern only matches nodes of type expression.

Properties

variableReference produces a record that contains the following properties:

Name Type Description
qualifiedName string The name of the variable, including scope information
scope enum variableScopeKind The scope of the variable: either `global` or `local`; see variableScopeKind
simpleName string The name of the variable, without scope information
variable symbol The symbol that represents ths variable

Inherits properties from:

astnode

Example

The following CodeXM matches all references to global variables:

CXM code follows
pattern globalVariableReference { variableReference { .scope == `global` } };

yieldExpression (pattern)

Matches yield expressions.

Details

This pattern only matches nodes of type expression.

Properties

yieldExpression produces a record that contains the following properties:

Name Type Description
expression expression The yielded expression

Inherits properties from:

astnode

Example

The following CodeXM pattern matches an expression that yields an integer:

CXM code follows
pattern yieldInteger { yieldExpression { .expression == integerLiteral } };

Literals

These patterns match literal values in the target code.

booleanLiteral (pattern)

Matches Boolean literals: either true or false (True or False as of Python 3).

Details

This pattern only matches nodes of type expression.

Properties

booleanLiteral produces a record that contains the following properties:

Name Type Description
value bool Either true or false

Inherits properties from:

astnode

Example

The following CodeXM pattern matches all True Boolean literals:

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

ellipsisLiteral (pattern)

Matches the ellipsis ( ... ).

Details

This pattern only matches nodes of type expression.

Properties

ellipsisLiteral does not expose any new properties.

Inherits properties from:

astnode

floatLiteral (pattern)

Matches literal floating-point values.

Details

The Python library does not distinguish between floating-point values of type float or complex. However, you can search for the imaginary component of a complex value: see imaginaryLiteral.

This pattern only matches nodes of type expression.

Properties

floatLiteral produces a record that contains the following properties:

Name Type Description
valueString string The floating-point value, represented as a string

Inherits properties from:

astnode

Example

The following source pattern:

Python code follows
2.5;

... could be matched by the following CodeXM code:

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

imaginaryLiteral (pattern)

Matches the imaginary part of literal complex-number values.

Details

This pattern only matches nodes of type expression.

Properties

imaginaryLiteral produces a record that contains the following properties:

Name Type Description
valueString string The complex component of the imaginary value, represented as a string

Inherits properties from:

astnode

Example

The following source pattern:

Python code follows
33.14j;

... could be matched by the following CodeXM code:

CXM code follows
f matches imaginaryLiteral { .valueString == "33.14" };

integerLiteral (pattern)

Matches literal integer values.

Details

The Python library does not distinguish between integers of type int or long.

This pattern only matches nodes of type expression.

Properties

integerLiteral produces a record that contains the following properties:

Name Type Description
base enum Either `binary`, `decimal`, `octal`, or `hexadecimal`
value int The value of the integer

Inherits properties from:

astnode

Example

The following source pattern:

Python code follows
f = 44;

... could be matched by the following CodeXM code:

CXM code follows
f matches integerLiteral { .valueString == "44" };

listLiteral (pattern)

Matches literal list expressions.

Details

This pattern only matches nodes of type expression.

Properties

listLiteral produces a record that contains the following properties:

Name Type Description
expressions list<expression> The expressions that comprise the list

Inherits properties from:

astnode

Example

The following CodeXM pattern finds empty list literals ( [] ):

CXM code follows
pattern emptyList { listLiteral as lst where lst.expressions.empty };

mapLiteral (pattern)

Matches literal map expressions.

Details

This pattern only matches nodes of type expression.

Properties

mapLiteral produces a record that contains the following properties:

Name Type Description
expressions list<dynamicMapping> The key/value pairs that comprise the map

Inherits properties from:

astnode

Example

In the following CodeXM code, the pattern mapWithKeyValue finds whether a map literal contains an element that maps the key string "foo" to the integer 3:

CXM code follows
pattern mapFooTo3 { dynamicMapping { .propertyName == stringLiteral { .valueString == "foo" }; .value == integerLiteral { .value == 3 } } }; pattern mapWithKeyValue { mapLiteral as mp where ( exists s in mp.expressions where s matches mapFooTo3 ) };

See Also

dynamicMapping

noneLiteral (pattern)

Matches None literals.

Details

This pattern only matches nodes of type expression.

Properties

noneLiteral does not expose any new properties.

Inherits properties from:

astnode

Example

The following CodeXM pattern finds all assignments to None; for example, a = None;:

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

setLiteral (pattern)

Matches literal set expressions.

Details

This pattern only matches nodes of type expression.

Properties

setLiteral produces a record that contains the following properties:

Name Type Description
expressions list<expression> The expressions that comprise the set

Inherits properties from:

astnode

Example

The following CodeXM pattern finds set literals that contain three elements; for example, {1,2,3}:

CXM code follows
pattern tripleSet { setLiteral as s where s.expressions.length == 3 };

stringLiteral (pattern)

Matches literal strings.

Details

This pattern only matches nodes of type expression.

Properties

stringLiteral produces a record that contains the following properties:

Name Type Description
valueString string The value of the string

Inherits properties from:

astnode

Example

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

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

tupleLiteral (pattern)

Matches literal tuple expressions.

Details

This pattern only matches nodes of type expression.

Properties

tupleLiteral produces a record that contains the following properties:

Name Type Description
expressions list<expression> The expressions that comprise the tuple

Inherits properties from:

astnode

Example

The following CodeXM pattern finds tuple literals that contain three elements; for example, (1,2,3):

CXM code follows
pattern tripleTuple { tupleLiteral as tup where tup.expressions.length == 3 };

undefinedLiteral (pattern)

Matches undefined literals.

Details

This pattern only matches nodes of type expression.

Properties

undefinedLiteral does not expose any new properties.

Inherits properties from:

astnode

Example

The Python language does not support an “undefined literal”, but sometimes one appears in the abstract syntax tree. Usually this happens when parsing creates a temporary variable whose value later needs to become undefined.

In the following Python code, at line 4 the variable a is set to an undefined literal. The undefinedLiteral pattern would match this occurrence:

Python code follows
def outer():
a = 0
class Cls:
b = (a + 1 for a in l);

Operators

These patterns match operators in the target code.

assignmentOperator (pattern)

Matches all forms of assignment.

Details

Watch out: This pattern does not appear in pattern decomposition: Use assignmentStatement instead. For more about decomposition, see Decomposing a Pattern to Match Specific Properties in Learning to Write CodeXM Checkers.

This pattern only matches nodes of type expression.

Properties

assignmentOperator produces a record that contains the following properties:

Name Type Description
operator enum One of `=`, `+=`, `-=`, `*=`, `/=`, `|=`, `&=`, `%=`, `^=`, `>>=`, or `<<=`
sourceExpression expression The source of the new value (the right-hand side of the operator)
targetExpression expression The expression to which the new value is assigned (the left-hand side of the operator)

Inherits properties from:

astnode

Example

The following CodeXM pattern matches only assignments made using the += operator:

CXM code follows
pattern incrementAssignmentOperator { assignmentOperator { .operator == `+=` } };

binaryOperator (pattern)

Matches all possible Python binary operators.

Details

Binary operators include the power operator **; the arithmetic operators *, //, /, %, +, and -; the shifting operators >> and <<; the bitwise operattors &, ^, and |; and the comparisons >, <, ==, >=, <=, !=, is, and in.

This pattern only matches nodes of type expression.

Properties

binaryOperator produces a record that contains the following properties:

Name Type Description
lhsExpression expression The left-hand side of the binary expression
operator enum One of `**`, `*`, `//`, `/`, `%`, `+`, `-`, `>>`, `<<`, `&`, `^`, `|`, `<`, `>`, `==`, `>=`, `<=`, `!=`, `is`, or `in`
rhsExpression expression The right-hand side of the binary 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 CodeXM pattern matches only multiplication:

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

See Also

unaryOperator

castOperator (pattern)

Matches implicit cast operations.

Details

Python does not officially support cast operations, but this pattern is included because some Python interpreters do perform casting.

This pattern only matches nodes of type expression.

Properties

castOperator produces a record that contains the following properties:

Name Type Description
operandExpression expression The expression whose type is being cast

Inherits properties from:

astnode

Example

The following CodeXM pattern matches a cast from an integer literal expression:

CXM code follows
pattern castFromInt { castOperator { .operandExpression == integerLiteral } };

conditionalOperator (pattern)

Matches the ternary conditional operator: <trueExpression> if <conditionExpression> else <falseExpression>.

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 condition of the operator (the first argument)
falseExpression expression The expression to evaluate if the condition is false (the third argument)
trueExpression expression The expression to evaluate if the condition is true (the second argument)

Inherits properties from:

astnode

Example

The following CodeXM pattern matches all conditional operators that use a binaryOperator as their condition:

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

unaryOperator (pattern)

Matches unary operators—those operators that have only one operand.

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 being operated upon
operator enum One of `**`, `-`, `+`, or `~` (tilde)

Inherits properties from:

astnode

Example

The following 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. 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.

aggregateInitializer (pattern)

Matches aggregate initializers for lists or expression.

Details

Watch out: This pattern does not appear in pattern decomposition. For more about decomposition, see Decomposing a Pattern to Match Specific Properties in Learning to Write CodeXM Checkers.

This pattern only matches nodes of type initializer.

Properties

aggregateInitializer produces a record that contains the following properties:

Name Type Description
expression expression The expression that initializes the list or expression

Inherits properties from:

astnode

expressionInitializer (pattern)

Matches expressions used as initializers.

Details

Watch out: This pattern does not appear in pattern decomposition. For more about decomposition, see Decomposing a Pattern to Match Specific Properties in Learning to Write CodeXM Checkers.

This pattern only matches nodes of type initializer.

Properties

expressionInitializer produces a record that contains the following properties:

Name Type Description
expression expression The expression used to initialize an object

Inherits properties from:

astnode

mapInitializer (pattern)

Matches map initializations (key/value mappings).

Details

Watch out: This pattern does not appear in pattern decomposition. For more about decomposition, see Decomposing a Pattern to Match Specific Properties in Learning to Write CodeXM Checkers.

This pattern only matches nodes of type initializer.

Properties

mapInitializer produces a record that contains the following properties:

Name Type Description
expression expression The expression used to initialize the map

Inherits properties from:

astnode

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 Python 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

functionSymbol (pattern)

Matches function variable symbols.

Details

This pattern only matches nodes of type symbol.

Properties

functionSymbol produces a record that contains the following properties:

Name Type Description
explicitParameterCount int The number of explicit parameters this function has
functionType functionType The type of the function
isClassInitializer bool true if the function is a class initializer
isCompilerGenerated bool true if the function is compiler-generated
qualifiedName string The name of the function, with scope informaton
simpleName string The name of the function, without scope information

Inherits properties from:

symbol

See Also

globalVariableSymbol, localVariableSymbol, parameterSymbol

globalVariableSymbol (pattern)

Matches global variable symbols.

Details

This pattern only matches nodes of type symbol.

Properties

globalVariableSymbol produces a record that contains the following properties:

Name Type Description
qualifiedName string The name of the variable, with scope information
simpleName string The name of the variable, without scope information

Inherits properties from:

symbol

Example

The following CodeXM pattern finds all uses of global variables whose type is composite:

CXM code follows
pattern useOfCompositeTypeGlobalVariable { variableReference { .variable == globalVariableSymbol { .type == compositeType } } };

See Also

localVariableSymbol, functionSymbol, parameterSymbol

localVariableSymbol (pattern)

Matches local variable symbols.

Details

This pattern only matches nodes of type symbol.

Properties

localVariableSymbol produces a record that contains the following properties:

Name Type Description
qualifiedName string The name of the variable, with scope information
simpleName string The name of the variable, without scope information

Inherits properties from:

symbol

Example

The following CodeXM pattern finds all uses of local variables whose type is composite:

CXM code follows
pattern useOfCompositeTypeLocalVariable { variableReference { .variable == localVariableSymbol { .type == compositeType } } };

See Also

globalVariableSymbol, functionSymbol, parameterSymbol

parameterSymbol (pattern)

Matches parameter symbols used in function declarations.

Details

This pattern only matches nodes of type symbol.

Properties

parameterSymbol produces a record that contains the following properties:

Name Type Description
extra extra Extra information used for defect reporting
location sourceloc The location of the parameter in the source code
position int The position of the parameter in the function declaration
qualifiedName string The name of the parameter, with scope information
scopeList list<string> The elements of the qualifiedNsame, broken up into a list
simpleName string The name of the parameter, without scope information
type type The parameter’s type

Inherits properties from:

symbol

Example

The following CodeXM pattern finds all uses of parameters whose type is composite:

CXM code follows
pattern useOfCompositeTypeParameter { variableReference { .variable == parameterSymbol { .type == compositeType } } };

Functions

The Python library does not provide any language-specific functions.

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

Python 2 Patterns

These patterns are specifically for use with a Python 2 interpreter. (Python 3 is not backward compatible with Python 2.)

Statements

These patterns match statements supported by Python 2.

execStatement (pattern)

Matches exec statements (Python 2).

Details

This pattern only matches nodes of type statement.

Properties

execStatement produces a record that contains the following properties:

Name Type Description
arguments list<expression> The arguments to the exec statement

Inherits properties from:

astnode

Example

The following CodeXM pattern matches the statement exec("ls");:

CXM code follows
pattern execLs { execStatement as e where e.arguments[0] matches stringLiteral { .valueString == "ls" } };

globalDeclarationStatement (pattern)

Matches global statements.

Details

Coverity Analysis recognizes global declarations but it does not consider them to be statements. Because of this, globalDeclarationStatement matches both global A; and global B;, but it does not provide any way to distinguish between the two declarations.

This pattern only matches nodes of type statement.

Properties

globalDeclarationStatement does not expose any new properties.

Inherits properties from:

astnode

printStatement (pattern)

Matches print statements (Python 2).

Details

This pattern only matches nodes of type statement.

Properties

printStatement produces a record that contains the following properties:

Name Type Description
arguments list<expression> The expressions to print

Inherits properties from:

astnode

Example

The following CodeXM pattern matches empty print statements:

CXM code follows
pattern printEmpty { printStatement as p where p.arguments.empty };

Conversion

This pattern matches Python 2 string conversion.

stringConversion (pattern)

Matches Python 2 string-conversion expressions; for example, `123`.

Details

This pattern only matches nodes of type expression.

Properties

stringConversion produces a record that contains the following properties:

Name Type Description
value expression? The result of the conversion; null if there is none

Inherits properties from:

astnode

Example

The following CodeXM pattern matches conversions of an integer literal to a string:

CXM code follows
pattern integerToString { stringConversion { .value == integerLiteral } };

Python 3 Patterns

These patterns are specifically for use with a Python 3 interpreter.

Statements

These patterns match statements supported by Python 3.

annotatedAssignmentStatement (pattern)

Matches Python 3 annotated assignment statements.

Details

Watch out: This pattern does not appear in pattern decomposition: Use assignmentStatement instead. For more about decomposition, see Decomposing a Pattern to Match Specific Properties in Learning to Write CodeXM Checkers.

An annotated assignment has the form, <variable> : <annotation> = <value>. (The assignment operator can be augmented as well as simple.) In abstract syntax, Coverity Analysis represents an annotated assignment as follows:

            {
                variable = value;
                __annotations__[ "variable" ] = annotation;
            }
        

This pattern only matches nodes of type statement.

Properties

annotatedAssignmentStatement produces a record that contains the following properties:

Name Type Description
annotation expression The annotation itself (<annotation>)
annotationAssignment expression The assignment expression (__annotations__[ "variable" ] = annotation;)
sourceExpression expression The source expression (<value>)
targetExpression expression The target expression (<variable>)
valueAssignment assignmentOperator The operator used for the assignment

Inherits properties from:

astnode

See Also

assignmentKind, assignmentStatement

globalOrNonlocalDeclarationStatement (pattern)

Matches global and Python 3 nonlocal declarations.

Details

Coverity Analysis recognizes global and nonlocal declarations but it does not consider them to be statements. Because of this, globalOrNonlocalDeclarationStatement matches both global C; and nonlocal D;, but it does not provide any way to distinguish between the two declarations.

This pattern only matches nodes of type statement.

Properties

globalOrNonlocalDeclarationStatement does not expose any new properties.

Inherits properties from:

astnode

Operators

This pattern matches the Python 3 unpack operator.

unpackOperator (pattern)

Matches unpack operators (Python 3).

Details

This pattern only matches nodes of type expression.

Properties

unpackOperator produces a record that contains the following properties:

Name Type Description
expression expression The expression that results from unpacking

Inherits properties from:

astnode

Example

The following CodeXM pattern matches applying the * operator to a list named args:

CXM code follows
pattern unpackArgs { unpackOperator { .expression == variableReference { .simpleName == "args" } } };

Expressions

This pattern matches the Python 3 await expression.

awaitExpression (pattern)

Matches await expressions (Python 3).

Details

This pattern only matches nodes of type expression.

Properties

awaitExpression produces a record that contains the following properties:

Name Type Description
expression expression The expression being awaited

Inherits properties from:

astnode

Example

The following CodeXM pattern matches an await expression that calls a function named ping():

CXM code follows
pattern awaitPing { awaitExpression { .expression == functionCall { .simpleName == "ping" } } };