Synopsys logo

Coverity® 2020.12 CodeXM

C♯ Library Reference

Introduction

Specifying the Target Language

Class Definitions

‘enum’ Kinds

‘globalset’ Sets

Code Patterns

Records

Functions

Hide/show Contents

Coverity® 2020.12 CodeXM

C♯ 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 C# library provides access to C# coding constructs.

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

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 ctorinit (constructor 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 C# class, interface, enum, or code attribute.

Properties

classDefinition produces a record that contains the following properties:

Name Type Description
attributes list<codeAttribute> Any attributes specified for this class
declaredType classType The type of the class.
fieldList list<fieldSymbol> A list of fieldSymbols, one 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 functionSymbols, one for each non-static member function
parentList list<classParent> A list of parent classes
staticFieldList list<staticVariableSymbol> A list of staticVariableSymbol objects, one for each static field in the class
staticMemberFunctionList list<functionSymbol> A list of all the functionSymbol objects 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 C# parent class.

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 the constructors that are called in the initialization of this function
formalParameterList list<symbol> A list of parameterSymbol objects, one 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 the nodes within a function. For a variable, this is usually just its initialization.
location sourceloc The location in the source code. This is used for defect reporting.
paths executionPaths The execution paths used for path-sensitive analysis

staticVariableDefinition (class)

Describes a variable that is 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

Attribute Classes

Attribute classes match attribute constructs in the target code. Attributes 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 attribute can specify how Coverity Analysis should treat an object; for example, a call to a particular function.

attributeArgument (class)

Describes an attribute argument, whether positional or named.

Properties

This pattern does not expose any new properties.

attributeNamedArgument (class)

Describes a named attribute argument.

Properties

attributeNamedArgument produces a record that contains the following properties:

Name Type Description
name string The name of the argument
value expression The value of the named argument

Inherits properties from:

attributeArgument

attributePositionalArguments (class)

Describes the positional arguments in an attribute.

Properties

attributePositionalArguments produces a record that contains the following property:

Name Type Description
arguments list<expression> The positional arguments to the attribute
constructorFunction functionSymbol The symbol of the constructor function that retrieves the positional arguments

Inherits properties from:

attributeArgument

‘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 that C# supports.

Details

The following values are defined:

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

See Also

castOperator, castOperatorExplicit, castOperatorImplicit

cvModifierKind (enum)

Represents the kinds of cvModifier known to C# (that is, const or volatile).

Details

The following values are defined:

Name Description
`const` constant
`volatile` volatile

See Also

cvModifiedType, getQualifiers

floatKind (enum)

Represents the kinds of floating-point types known to C#.

Details

The following values are defined:

Name Description
`decimal` A 128-bit number with 28–29 significat digits
`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 is of the form:

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

An enhanced for loop is of the form:

C# code follows
foreach (int element in fibNumbers) {
// ...
};

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 C#.

Details

The following values are defined:

Name Description
`byte` Unsigned 8-bit integer
`char` Unicode 16-bit character
`int` Signed 32-bit integer
`long` Signed 64-bit integer
`sbyte` Signed 8-bit integer
`short` Signed 16-bit integer
`uint` Unsigned 32-bit integer
`ulong` Unsigned 64-bit integer
`ushort` Unsigned 16-bit integer

See Also

addressOf, integralLiteral, integralType

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.
`tryResource` The variable is declared in a block that belongs to a try statement.

See Also

variableDeclaration, variableReference, propertyReference

variableScopeKind (enum)

Represents the scope of a variable symbol.

Details

The following values are defined:

Name Description
`local` Scope is local to a function or a class
`static` Scope is static, variable is available globally

See Also

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 definition of all class, interface, and struct types in the current C# 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 statically 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 C# code.

See Also

allFunctionAndStaticVariableCode, allFunctionsAndGlobalVariableCode

allFunctionDefinitions (globalset)

Includes all function definitions in the current C# 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 C# code.

See Also

allFunctionCode

allStaticVariableCode (globalset)

Includes all statically declared variables in the current C# code.

See Also

allFunctionAndStaticVariableCode

allStaticVariableDefinitions (globalset)

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

See Also

allFunctionAndStaticVariableDefinitions

allTextFiles (globalset)

Includes all source files in the current project that are coded in the C# 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 for (simple/enhanced), while and do ... while loop statements. For specific patterns, with more details about each kind of loop, refer to forLoopSimple, forLoopEnhanced, whileLoop, and doWhileLoop.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

Example

The following pattern uses allLoops to determine whether the simpleStatement is a loop:

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

See Also

forLoopSimple, forLoopEnhanced, forLoop, whileLoop, doWhileLoop

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 property:

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

Inherits properties from:

astnode

Example

The following pattern finds blockStatement entities 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 property:

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 within 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 statement. See defaultStatement pattern.

This pattern only matches nodes of type statement.

Properties

caseStatement produces a record that contains the following property:

Name Type Description
valueExpression expression The value associated with the case

Inherits properties from:

astnode

Example

The following CodeXM pattern matches all case statements that have a case 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 property:

Name Type Description
controlStatement statement The flow-control statement within which the continue occurs. For example, while or switch.

Inherits properties from:

astnode

Example

The following example matches continue statements within 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 locations 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.

An empty statement can be a line with no executable code that is terminated by a semicolon; non-executable code enclosed by curly braces; or an implied branch of an if statement.

Details

The following are examples of emptyStatement situations:

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

This pattern only matches nodes of type statement.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

See Also

blockStatement, ifStatement

fixedStatement (pattern)

Matches fixed statements.

Details

This pattern only matches nodes of type statement.

Properties

fixedStatement produces a record that contains the following properties:

Name Type Description
bodyStatement statement The contained statement
declarations declaration Declaration of the fixed variables

Inherits properties from:

astnode

Example

The following pattern matches fixed statements that are empty:

CXM code follows
pattern emptyFixed { fixedStatement { .bodyStatement == emptyStatement; } };

forLoop (pattern)

Matches both simple and 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 ForLoopKinde

Inherits properties from:

astnode

Example

Matches any simple for loop:

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

See Also

forLoopSimple, forLoopEnhanced

forLoopEnhanced (pattern)

Matches enhanced for loops of the form foreach (int i in numbers).

Details

Matches only 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 pattern finds all enhanced for loops over an array of integers:

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

See Also

forLoopSimple, forLoop

forLoopSimple (pattern)

Matches simple for 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 here; otherwise this field is null
conditionExpression statement The conditional clause for the loop
initializationStatement statement The 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 its iterations:

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

See Also

forLoopEnhanced, forLoop

gotoStatement (pattern)

Matches goto statements.

Details

This pattern only matches nodes of type statement.

Properties

goToStatement produces a record that contains the following property:

Name Type Description
labelStatement statement The statement to go to

Inherits properties from:

astnode

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, or 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 continue 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:

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

labelStatement (pattern)

Matches statements that have a label.

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 that target the label 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 (that is, that do not return a value):

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

simpleStatement (pattern)

Matches individual executable statements.

Details

The term simple—as opposed to compound—means that the these statements are not flow-of-control statements. Simple statements include assignments, function calls, and function returns. Variable declarations (variableDeclaration) are not considered statements.

This pattern only matches nodes of type statement.

Properties

simpleStatement produces a record that contains the following property:

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

Inherits properties from:

astnode

Example

The following pattern matches a function call:

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

switchStatement (pattern)

Matches entire switch statements, including all the statements contained in their 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 the case names for the switch statement
conditionDeclaration variableDeclaration? If a variable is declared in the conditionExpression, it is identified here; if it is not, this field 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

This pattern 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 property:

Name Type Description
conditionExpression expression The expression that is thrown when an exception occurs

Inherits properties from:

astnode

Example

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

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

tryStatement (pattern)

Matches try statements, including their initial block, catch blocks, and finally block (if present).

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 initial try block
catchBlockList list<handler> The bodies of the catch blocks
finallyStatement statement? The body of the finally block, it if exists; null, otherwise
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. It uses the tryStatement pattern’s catchBlockList property, which provides 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

unsafeStatement (pattern)

Matches unsafe blocks.

Details

This pattern only matches nodes of type statement.

Properties

unsafeStatement produces a record that contains the following property:

Name Type Description
bodyStatement statement The body statement contained by unsafe

Inherits properties from:

astnode

Example

The following pattern matches unsafe statements that are empty:

CXM code follows
pattern emptyUnsafe { unsafeStatement { .bodyStatement == emptyStatement; } };

whileLoop (pattern)

Matches standard while loops.

Details

This pattern matches only while loops, and does not match do ... while or 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; if it is not, this field is null
conditionExpression expression The expression in the condition of the loop

Inherits properties from:

astnode

Example

The following pattern matches locations 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 initializer of the variable, if it exists
kind enum variabelDeclarationKind Either `local` or `static`; see variableDeclarationKind
variable symbol The identifier of the variable being declared

Inherits properties from:

astnode

Example

The following pattern matches all variables declared with the type char:

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

Types

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

arrayType (pattern)

Matches all array types.

Details

This pattern only matches nodes of type type.

Properties

arrayType produces a record that contains the following property:

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

Example

The following pattern finds all arrays whose elements are any type of integer:

CXM code follows
t matches arrayType { .elementType == integralType };

booleanType (pattern)

Matches the bool 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 pattern matches any expression of the type bool:

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

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 pattern matches any expression of the type char:

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

See Also

integralType

classType (pattern)

Matches all kinds of C# class types.

Details

This pattern matches the following kinds of C# classes:

This pattern only matches nodes of type type.

Properties

classType produces a record that contains the following properties:

Name Type Description
extra extra Extra information used for defect reporting
extraWithoutScope extra Extra information used for defect reporting. This version of the 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`, `delegate`, `enum`, `interface`, or `struct`
location location The location information of the class
qualifiedName string The name of the class including the class’s 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 matches all delegate classes:

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

cvModifiedType (pattern)

Matches const or volatile modified types in C#.

Details

This pattern only matches nodes of type type.

Properties

cvModifiedType produces a record that contains the following properties:

Name Type Description
cvFlags list<cvModifierKind> A list of the modifier types applied to the matched type
toType enum cvModifierKind The type of the object being modified.

Example

The following pattern:

CXM code follows
c matches cvModifiedType { .cvFlags.contains(`const`); .toType == charType };

... matches const char.

This pattern can be used to inspect target code such as the following:

C# code follows
class VolatileTest {
public volatile char c;
};

See Also

cvModifierKind, getQualifiers

enumType (pattern)

Matches all kinds of C# enum types.

Details

This pattern only matches nodes of type type.

Properties

enumType produces a record that contains the following properties:

Name Type Description
alignmentInBytes int The alignment of the enum, in bytes
extra extra Extra information used for defect reporting
extraWithoutScope extra Extra information used for defect reporting. This version of the extra information omits the scope details.
location location The location of the enum
qualifiedName string The name of the enum including its package
scopeList list<string> The scope of the enum. This is the elements of the qualified name broken up into a list.
simpleName string The name of the enum, without the package prefix
sizeInBytes int The size of the enum, in bytes

Example

The following CodeXM pattern matches all enum classes:

CXM code follows
c matches enumType;

floatType (pattern)

Matches C# floating-point types.

Details

This pattern only matches nodes of type type.

Properties

floatType produces a record that contains the following properties:

Name Type Description
alignmentInBytes int The alignment of the type, in bytes
kind enum floatKind The kind of floating-point type. See floatKind.
sizeInBits int The total size of the float, in bits
sizeInBytes int The size of the float, in bytes

Note: The representation of floating types is implementation-defined, so CodeXM does not show how bits are apportioned between the exponent and the mantissa.

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
isStatic bool true if the function is declared as static
parameterTypeList list<type> A list of all the parameter types for the function
returnType type The return type of the function

Example

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

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

genericType (pattern)

Matches C# generic types.

Details

This pattern only matches nodes of type type.

Properties

genericType produces a record that contains the following properties:

Name Type Description
genericClass type The generic type
isNullable bool true if this a nullable type
typeParameters list<typeParameterType> The type parameters

Example

The following CodeXM pattern matches all nullable types:

CXM code follows
g matches genericType { .isNullable == true };

See Also

typeParameterType

integralType (pattern)

Matches all C# integer types.

Details

This pattern only matches nodes of type type.

Properties

integralType produces a record that contains the following properties:

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

Example

The following pattern uses the kind property to match a long type:

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

See Also

charType, intKind

nullableType (pattern)

Matches C# nullable types.

Details

This pattern only matches nodes of type type.

Properties

nullableType produces a record that contains the following property:

Name Type Description
valueType type The underlying type that can be nulled

Example

The following pattern matches all nullable char instances:

CXM code follows
n matches nullableType { .valueType == charType }

outParamReferenceType (pattern)

Matches a C# out parameter.

Details

This pattern only matches nodes of type type.

Properties

outParamReferenceType produces a record that contains the following property:

Name Type Description
toType type The type the reference refers to

Example

The following pattern:

CXM code follows
o matches outParamReferenceType { .toType == integralType };

... matches integer out parameter types; for example:

C# code follows
void OutArgExample(out int number) {
number = 44;
};

See Also

referenceType

pointerType (pattern)

Matches C# pointer types.

Details

C# recognizes pointer types only in unsafe mode.

This pattern only matches nodes of type type.

Properties

pointerType produces a record that contains the following property:

Name Type Description
toType type The type of the object pointed to

Example

The following pattern matches all pointers to a class named MyClass:

CXM code follows
p matches pointerType { .toType == classType { .simpleName == "MyClass" } }

referenceParamType (pattern)

Matches C# reference (ref) parameter types.

Details

Reference types are used when something is passed as a reference (as opposed to by value); for example, in a function call such as myFun(ref count).

This pattern only matches nodes of type type.

Properties

referenceParamType produces a record that contains the following property:

Name Type Description
toType type The type the reference refers to

Examples

The following pattern matches all reference types to a class named MyClass:

CXM code follows
r matches referenceParamType { .toType == classType { .simpleName == "MyClass" } }

Here is another example of using ref:

C# code follows
void Method(ref int refArgument)
{
refArgument = refArgument + 44;
};
ref VeryLargeStruct reflocal = ref veryLargeStruct;

See Also

referenceType

referenceType (pattern)

Matches C# reference types.

Details

A C# reference type can be declared as a class, interface>, or delegate; the dynamic, object, and string types are inherently references.

This pattern only matches nodes of type type.

Properties

referenceType produces a record that contains the following property:

Name Type Description
toType type The type the reference refers to

Example

The following CodeXM pattern matches all references to a class named MyClass:

C# code follows
r matches referenceType { .toType == classType { .simpleName == "MyClass" } };

See Also

outParamReferenceType referenceParamType

tupleClassType (pattern)

Matches C# System.Tuple class types.

Details

This pattern only matches nodes of type type.

Properties

tupleClassType produces a record that contains the following property:

Name Type Description
componentTypes list<type> The types of the tuple’s components

Example

The following CodeXM pattern matches all instances of Tuple<char,bool>:

C# code follows
t matches tupleType { .componentTypes == [charType, booleanType] };

typeParameterType (pattern)

Matches all C# parameter types.

Details

This pattern only matches nodes of type type.

Properties

typeParameterType produces a record that contains the following property:

Name Type Description
name string The name of the parameter type

Example

The following CodeXM pattern matches all parameters whose type is Element:

C# code follows
t matches typeParameterType { .name == "Element" };

See Also

genericType

usingType (pattern)

Matches types that have been defined with the using keyword.

Details

This pattern only matches nodes of type type.

Properties

usingType produces a record that contains the following properties:

Name Type Description
alias string The (mangled) name of the type being defined
id symbol The identifier of the type being defined
targetType type The type being associated with the name

valueTupleType (pattern)

Matches any C# System.ValueTuple type.

Details

This pattern only matches nodes of type type.

Properties

valueTupleType produces a record that contains the following property:

Name Type Description
componentTypes list<type> The types of the tuple’s components

Example

The following CodeXM pattern matches all instances of ValueTuple<char,bool>:

CXM code follows
v matches valueTupleType { .componentTypes == [charType, booleanType] };

voidType (pattern)

Matches the void type.

Details

This pattern only matches nodes of type type.

Properties

This pattern does not expose any new properties.

Expressions

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

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

argList (pattern)

Matches the use of __arglist.

Details

In C#, you can use __arglist as an argument to a new ArgIterator object. This allows you to later call that object using __arglist(args) and specify an arbitrary number of arguments in place of "args".

In other words, __arglist behaves somewhat like the ... construct for “tuple” arguments in C++.

Here is an example of using __arglist in a new declaration:

C# code follows
ArgList(__arglist)
{
var iterator = new System.ArgIterator(__arglist);
// ...

This pattern only matches nodes of type expression.

Properties

argList produces a record that contains the following property:

Name Type Description
type type The type of the expression

Inherits properties from:

astnode

arrayLength (pattern)

Matches all expressions, such as array.length, that get the length of an array.

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 == integralType } } };

boxExpression (pattern)

Matches box expressions: both boxing a value and unboxing a reference.

Details

This pattern only matches nodes of type expression.

Properties

boxExpression produces a record that contains the following property:

Name Type Description
expression expression The expression being boxed or unboxed

Inherits properties from:

astnode

Example

The following pattern matches all unboxing expressions that directly call a function:

CXM code follows
pattern functionCallInBox { boxExpression { .expression == functionCall } };

checkedBlock (pattern)

Matches checked blocks.

Details

This pattern only matches nodes of type statement.

Properties

checkedBlock produces a record that contains the following property:

Name Type Description
bodyStatement statement The statements contained in the block

Inherits properties from:

astnode

Example

The following pattern matches checked statements that are empty:

CXM code follows
pattern emptyChecked { checkedBlock { .bodyStatement == emptyStatement; } };

See Also

checkedexpression uncheckedexpression uncheckedBlock

checkedExpression (pattern)

Matches checked expressions.

Details

This pattern only matches nodes of type expression.

Properties

checkedExpression produces a record that contains the following property:

Name Type Description
expression expression The expression being checked

Inherits properties from:

astnode

Example

The following pattern matches all checked expressions on integer types:

CXM code follows
pattern checkedExpressionOnInt { checkedExpression { .expression == expression { .type == integralType } } };

See Also

checkedexpression, uncheckedexpression, checkedBlock

deconstructionExpression (pattern)

Matches deconstruction expressions.

Details

This pattern only matches nodes of type expression.

Properties

deconstructionExpression produces a record that contains the following properties:

Name Type Description
sourceExpression expression The source of the deconstruction
targetStatements list<statement> The targets of the deconstruction

Inherits properties from:

astnode

Example

The following pattern matches the deconstruction of value tuples:

CXM code follows
pattern tupleDeconstruction { deconstructionExpression { .sourceExpression == expression { .type = valueTupleType } } };

dynamicCastExpression (pattern)

Matches dynamic casts.

Details

This pattern only matches nodes of type expression.

Properties

dynamicCastExpression produces a record that contains the following property:

Name Type Description
expression expression The expression being cast

Inherits properties from:

astnode

Example

The following pattern matches casts to short:

CXM code follows
pattern dynamicCastToShort { dynamicCastExpression { .type == shortType } };

See Also

castOperatorImplicit, castOperator

dynamicFunctionCall (pattern)

Matches dynamic function calls.

Details

This pattern only matches nodes of type expression.

Properties

dynamicFunctionCall produces a record that contains the following properties:

Name Type Description
callKind DynamicFuncKind One of `DFK_METHOD`, `DFK_INVOKE`, `DFK_PROPERTY`, `DFK_INDEXER`, `DFK_OPERATOR`, or `DFK_CONVERSION`
name string The name of the function

Inherits properties from:

astnode

Example

The following pattern matches calls to the dynamic function named example():

CXM code follows
pattern dynamicExampleCall { dynamicFunctionCall { .name == "example" } };

enumReference (pattern)

Matches expressions that reference 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 symbol that refers to this enum

Inherits properties from:

astnode

Example

The following pattern matches enum instances that have the identifer Example:

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

expressionPattern (pattern)

Matches C# query-expression patterns.

Details

This pattern matches C# patterns (not to be confused with CodeXM patterns). In C#, a query-expression pattern matches other portions of the C# code.

C# code follows
if (o is null) return; // matches against the expression 'null'

Properties

expressionPattern produces a record that contains the following property:

Name Type Description
expression expression The C# expression used for matching

Inherits properties from:

astnode

Example

The following pattern matches an expression that contains the C# pattern match expression is null:

CXM code follows
pattern isNullMatchPattern { patternMatchExpression { .matchPattern == expressionPattern { .expr == nullLiteral } } };

See Also

patternMatchExpression, namedPattern, isPattern

expressionTree (pattern)

Matches all expression trees.

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 matches only expression trees whose root is a binary operator:

CXM code follows
pattern binaryExpressionTree { expressionTree { .expr == binaryOperator } };

fieldAccess (pattern)

Matches expressions that access 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

The following pattern matches all accesses to public fields:

CXM code follows
pattern publicFieldAccess { fieldAccess { .field == fieldSymbol { .access == `public` } } };

fieldReference (pattern)

Matches expressions that reference fields.

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 field symbol

Inherits properties from:

astnode

Example

The following pattern matches when a field example is referenced:

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

functionCall (pattern)

Matches calls to functions.

Details

This pattern only matches nodes of type expression.

Properties

functionCall 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 finds function calls whose arguments 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 expressions that reference functions.

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 that represents the function

Inherits properties from:

astnode

Example

The following pattern matches calls to a function named example():

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

See Also

functionCall

instanceOf (pattern)

Matches the C# instanceof() function.

Properties

instanceOf produces a record that contains the following properties:

Name Type Description
expression expression The expression being examined
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" } } };

isPattern (pattern)

Matches C# patterns that perform dynamic type checks.

Details

In C#, you can used an is pattern (not to be confused with a CodeXM pattern) to perform a dynamic type check. The C# pattern can have an optional subpattern: If the type check succeeds, the subpattern is matched against the expression. This pattern is usually followed by a namedPattern.

For example, the following C# snippet matches the variable o against the type int. If the variable is not an integer, the function containing this statement returns:

C# code follows
if (!(o is int)) return;

Properties

isPattern produces a record that contains the following properties:

Name Type Description
subPattern pattern The subpattern to match if the type check succeeds
type type The type to match against

Inherits properties from:

astnode

Example

The following pattern matches an expression that contains the C# pattern-match expression is int:

CXM code follows
pattern isIntMatchPattern { patternMatchExpression { .matchPattern == isPattern { .type == integralType { .kind == `int` } } } };

See Also

patternMatchExpression, namedPattern, expressionPattern

makeRefExpression (pattern)

Matches expressions that use the C# keyword ref to make references.

Details

This pattern only matches nodes of type expression.

Properties

makeRefExpression produces a record that contains the following property:

Name Type Description
expression expression The expression being used

Inherits properties from:

astnode

Example

The following pattern matches all make reference expressions within functions:

CXM code follows
pattern makeRefToFunctionCallExpression { makeRefExpression { .expression == functionCall } };

multiSubscriptReference (pattern)

Matches expressions that use a multi-subscript operator on a multidimensional array.

Details

This pattern only matches nodes of type expression.

Properties

multiSubscriptReference produces a record that contains the following properties:

Name Type Description
arrayExpression expression The array the subscript is being used on
indices list<expression> The values inside the brackets ( [ ] ).

Inherits properties from:

astnode

Example

The following pattern matches all two-dimensional arrays:

CXM code follows
pattern variableArrayLookup { multiSubscript as mss where mss.indicies.length == 2 };

namedPattern (pattern)

Matches C# named patterns that bind names to values.

Details

In C#, you can used a named pattern (not to be confused with a CodeXM pattern) to bind a name to a value: usually this follows an isPattern expression, as in the following example:

C# code follows
if (!(o is int i)) return; // Two pattern matches here:
// 1. is int -> isPattern
// 2. is int i -> namedPattern where
// New name 'i' is bound to the
// value of o
var z = i; // Using the new name 'i'

Properties

namedPattern produces a record that contains the following property:

Name Type Description
variable variable The variable the value is being bound to

Inherits properties from:

astnode

Example

The following pattern matches an expression that contains the C# pattern-match expression is int i:

CXM code follows
pattern isIntWithNameMatchPattern { patternMatchExpression { .matchPattern == isPattern { .type == integralType { .kind == `int` } .subPattern = namedPattern } } };

patternMatchExpression, expressionPattern, isPattern

nullableGetValue (pattern)

Matches expressions that reference nullable values.

Details

This pattern only matches nodes of type expression.

Properties

nullableGetValue produces a record that contains the following property:

Name Type Description
from expression The expression that resulted in a nullable

Inherits properties from:

astnode

Example

The following pattern matches when references of nullables result from a division:

CXM code follows
pattern nullableFromDivision { nullableGetValue { .from == binaryOperator { .operator == `/` } } };

patternMatchExpression (pattern)

Matches C# pattern-match expressions.

Details

This pattern matches a C# pattern-match expression (not to be confused with a CodeXM pattern). Pattern matching can be used in if and switch statements.

Properties

patternMatchExpression produces a record that contains the following properties:

Name Type Description
expression expression The expression to be matched by the pattern
matchPattern pattern The pattern to match

Inherits properties from:

astnode

Example

The following pattern matches an expression that contains the C# pattern-match expression is int:

CXM code follows
pattern isIntMatchPattern { patternMatchExpression { .matchPattern == isPattern { .type == integralType { .kind == `int` } } } };

See Also

namedPattern, expressionPattern, isPattern

propertyReference (pattern)

Matches expressions that reference a C# property.

Details

This pattern only matches nodes of type expression.

Properties

propertyReference 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 variableDeclarationKind The scope of the variable: one of `static`, `local`, or `tryResource`; see variableDeclarationKind
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 propertyReferenceFinal { propertyReference { .isFinal == true; } };

propertyUpdate (pattern)

Matches all property updates.

Details

This pattern only matches nodes of type expression.

Properties

propertyUpdate produces a record that contains the following property:

Name Type Description
setterCall functionSymbol The setter to be called

Inherits properties from:

astnode

referenceDereference (pattern)

Matches locations where a reference-type expression has been 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 C# function:

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

... you might use the following pattern to match the dereferences of the parameter o:

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

See Also

referenceType

refTypeExpression (pattern)

Matches expressions that make references by using the __reftype construct.

Details

The following code is an example of using __reftype:

C# code follows
void Test_RefType(System.TypedReference typedRef) {
var res01 = __reftype(typedRef);
};

This pattern only matches nodes of type expression.

Properties

refTypeExpression produces a record that contains the following property:

Name Type Description
expression expression The expression being used

Inherits properties from:

astnode

Example

The following pattern matches all make-reference-type expressions from function calls:

CXM code follows
pattern makeRefToFunctionCallExpression { refTypeExpression { .expression == functionCall } };

refValueExpression (pattern)

Matches expressions that make references by using the __refvalue construct.

Details

The following code is an example of using __refvalue:

C# code follows
void Test_RefValue(System.TypedReference typedRef) {
var res01 = __refvalue(typedRef, int);
};

This pattern only matches nodes of type expression.

Properties

refValueExpression produces a record that contains the following property:

Name Type Description
expression expression The expression being used

Inherits properties from:

astnode

Example

The following pattern matches all make-reference-value expressions from function calls:

CXM code follows
pattern makeRefToFunctionCallExpression { refValueExpression { .expression == functionCall } };

stackAllocation (pattern)

Matches stack allocations made by using the keyword stackalloc.

Details

This pattern only matches nodes of type expression.

Properties

stackAllocation produces a record that contains the following property:

Name Type Description
type expression The expression being used

Inherits properties from:

astnode

Example

The following pattern matches all stackalloc allocations of more than 100 objects:

CXM code follows
pattern stackAllocMoreThan100 { stackAllocation as sa where sa.count > 100 };

subscriptReference (pattern)

Matches uses of a subscript to find a value in 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 pattern matches where a variable is used as an index to look up a value in an array:

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

temporaryConstruction (pattern)

Matches all locations where a temporary variable is constructed.

Details

This pattern only matches nodes of type expression.

Properties

temporaryConstruction produces a record that contains the following property:

Name Type Description
expression expression How the temporary variable was constructed

Inherits properties from:

astnode

Example

The following pattern finds all assignments from temporary variables:

CXM code follows
pattern assignmentFromTemp { assignmentOperator { sourceExpression == temporaryConstruction } };

temporaryExpression (pattern)

Matches all locations where a temporary object is constructed.

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 matches temporary constructions of collections:

CXM code follows
pattern temporaryCollectionConstruction { temporaryExpression { .initializer = objectInitializer { .memberInitializers == addMemberInitializer } } };

temporaryVariableReference (pattern)

Matches references to compiler-generated temporary variables.

Properties

This pattern does not expose any new properties.

Note: The real name of a compiler-generated variable is not accessable.

Inherits properties from:

astnode

uncheckedBlock (pattern)

Matches statements in unchecked blocks.

Details

This pattern only matches nodes of type statement.

Properties

uncheckedBlock produces a record that contains the following property:

Name Type Description
checked statement The statement

Inherits properties from:

astnode

Example

The following pattern matches unchecked statements that are empty:

CXM code follows
pattern emptyUnchecked { uncheckedBlock { .bodyStatement == emptyStatement; } };

See Also

checkedexpression, uncheckedexpression, checkedBlock

uncheckedExpression (pattern)

Matches unchecked expressions.

Details

This pattern only matches nodes of type expression.

Properties

uncheckedExpression produces a record that contains the following property:

Name Type Description
expression expression The expression

Inherits properties from:

astnode

Example

The following pattern matches all unchecked expression on integer types:

CXM code follows
pattern uncheckedExpressionOnInt { uncheckedExpression { .expression == expression { .type == integralType } } };

See Also

checkedexpression uncheckedexpression uncheckedBlock

variableReference (pattern)

Matches where variables are referenced in expressions.

Details

This pattern only matches nodes of type expression.

Properties

variableReference produces a record that contains the following properties by variableReference:

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 variableDeclarationKind The scope of the variable: one of `static`, `local`, or `tryResource`; see variableDeclarationKind
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 pattern matches all references to final static variables:

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

yieldExpression (pattern)

Matches yield return expressions.

Details

This pattern only matches nodes of type expression.

Properties

yieldExpression produces a record that contains the following property:

Name Type Description
expression expression The expression being yielded

Inherits properties from:

astnode

Example

The following pattern matches all yield return expressions that return integral types:

CXM code follows
pattern yieldingIntExpression { yieldExpression { .expression == expression { .type == integralType } } };

Literals

These patterns match literal values in the target code.

booleanLiteral (pattern)

Matches Boolean literals: that is, either true or false.

Details

This pattern only matches nodes of type expression.

Properties

booleanLiteral produces a record that contains the following property:

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

Inherits properties from:

astnode

Example

The following pattern matches all literal Boolean values:

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 property:

Name Type Description
value int The value of the character

Inherits properties from:

astnode

Example

The following pattern matches all 'a' characters:

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 property:

Name Type Description
targetType type The type of the class

Inherits properties from:

astnode

Example

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

CXM code follows
pattern boolTypeLiteral { classLiteral { .targetType == booleanType } };

enumLiteral (pattern)

Matches enum literals.

Details

This pattern only matches nodes of type expression.

Properties

enumLiteral produces a record that contains the following properties:

Name Type Description
type type The underlying type of the enum
value int The underlying value

Inherits properties from:

astnode

Example

The following pattern matches only enum literal values whose underlying type is byte:

CXM code follows
pattern enumByteLiteral { enumLiteral { .type == integralType { .kind = `byte` } } };

floatLiteral (pattern)

Matches floating-point 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 numerals
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 pattern:

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

... matches this target-code expression:

C# code follows
float f = 2.5;

integralLiteral (pattern)

Matches integer literals; that is, all literals of the type int, short, long, or byte.

Details

This pattern only matches nodes of type expression.

Properties

integralLiteral produces a record that contains the following properties:

Name Type Description
base enum One of `binary`, `decimal`, `octal`, or `hexadecimal`.
kind Subset of enum intKind One of `short`, `byte`, `int`, or `long`; see also 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 { integralLiteral { .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.

Properties

stringLiteral produces a record that contains the following property:

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.

addressOf (pattern)

Matches instances of the address-of ( & ) operator.

Details

This pattern only matches nodes of type expression.

Properties

addressOf produces a record that contains the following property.

Name Type Description
kind enum intKind The type to find the address of: one of `bool`, `byte`, `char`, `decimal`, `double`, `dynamic`, `enum`, `float`, `int`, `object`, `sbyte`, `short`, `string`, `uint`, `ulong`, or `ushort`; see intKind

Inherits properties from:

astnode

Example

The following pattern matches operations that obtain the address of int variables:

CXM code follows
pattern addressOfInt { addressOf { .operandType == integralType { .kind == `int` } } };

assignmentOperator (pattern)

Matches all forms of the assignment operator where it occurs.

Details

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 expression on the right-hand side of the assignment operator
targetExpression expression The expression on the left-hand side of the assignment operator

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 such as 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 expression on the right-hand side of the assignment operator
targetExpression expression The expression on the left-hand side of the assignment operator

Inherits properties from:

astnode

Example

The following pattern matches 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 expression on the right-hand side of the assignment operator
targetExpression expression The expression on the left-hand side of the assignment operator

Inherits properties from:

astnode

Example

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

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

See Also

assignmentOperatorCompound, assignmentOperator

awaitOperator (pattern)

Matches await operators.

Details

This pattern only matches nodes of type expression.

Properties

awaitOperator produces a record that contains the following property:

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

Inherits properties from:

astnode

Example

The following pattern find all await occurrences in a function named example():

CXM code follows
pattern awaitExample { awaitOperator { .operandExpression == functionCall { .calledFunction == functionSymbol { .simpleName == "example" } } } };

binaryOperator (pattern)

Matches all possible C# binary operators.

Details

This pattern only matches nodes of type expression.

Properties

binaryOperator produces a record that contains the following properties:

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

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 nullableBinaryOperator

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
`dynamic` A dynamic 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 CodeXM pattern matches all kinds of casts (implicit, explicit, checked) to type int:

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

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

For the following snippet of C#:

C# code follows
int i = 5;
short a = (short) i;

... the following pattern matches casts to short, so it would match the preceding snippet:

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

See Also

castOperatorImplicit, castOperator

castOperatorImplicit (pattern)

Matches implicit casts; that is, casts that are not explicitly stated but are performed by the C# compiler.

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

In the following snippet of C#:

C# code follows
int num = 2147483647;
long bigNum = num;

... there is an implicit cast between the int and the long. To detect such a cast, you could use the following pattern:

CXM code follows
pattern implicitCastFromString { castOperatorImplicit { .operandExpression == expression { .type == integralType { .kind == `int` } } } };

See Also

castOperator, castOperatorExplicit

conditionalOperator (pattern)

Matches the conditional operator ? :, sometimes called the “ternary&Cx201d; 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 (the first argument)
falseExpression expression The expression on the false side of the operator (the third argument)
trueExpression expression The expression on the true side of the operator (the second argument)

Inherits properties from:

astnode

Example

The following pattern matches all conditional operators whose condition uses a binary operator:

CXM code follows
pattern binaryOperatorCondition { conditionalOperator { .conditionExpression == 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 pattern 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 C# 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
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" } } };

nullableBinaryOperator (pattern)

Matches all possible C# binary operations with nullable values (all of these are comparisons).

Details

This pattern only matches nodes of type expression.

Properties

nullableBinaryOperator produces a record that contains the following properties:

Name Type Description
isImplicit bool true if the operator is implicit
lhsExpression expression The expression on the left-hand side of the operator
operator enum The operator this pattern represents: one of `==`, `!=`, `&`, `^`, or `|`
rhsExpression expression The expression on the right-hand side of the operator

Inherits properties from:

astnode

Example

The following pattern matches only a comparison for equality:

CXM code follows
pattern nullableEqaulityCheck { nullableBinaryOperator { .operator == `==` } };

See Also

binaryOperator

nullCoalescingOperator (pattern)

Matches the null-coalescing operator ??.

Details

This pattern only matches nodes of type expression.

Properties

nullCoalescingOperator produces a record that contains the following properties:

Name Type Description
nonNullExpression expression The value to be coalesced.
nullExpression expression The value to use if the nullable value is actually null

Inherits properties from:

astnode

Example

The following pattern matches only null-coalescing of Boolean values:

CXM code follows
pattern boolNullCoalescing { nullCoalescingOperator { .nullExpression == expression { .type = booleanType } } };

sizeofOperator (pattern)

Matches all size-of operations.

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 calls to sizeof() when the type is int:

CXM code follows
pattern sizeOfOnInt { sizeofOperator { .operandType == integralType { .kind == `int` } } };

The pattern would locate the following call:

C# code follows
// Constant value 4:
int intSize = sizeof(int);

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 finds all throws of type Exception:

`
pattern throwException { throwOperator { .operandExpression == expression { .type == classType { .simpleName == "Exception" } } } };

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 the operation is performed on
operator enum The unary operator this pattern represents: one of `+`, `-`, `!`, or `~` (tilde for bitwise negation)

Inherits properties from:

astnode

Example

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

addMemberInitializer (pattern)

Matches collection initializers.

Details

Collection initializers let you specify one or more element initializers when you initialize a collection type that implements IEnumerable and has an add method. For example:

C# code follows
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

This pattern only matches nodes of type addMemberInitializer, assignmentMemberInitializer, or nestedMemberInitializer.

Properties

addMemberInitializer produces a record that contains the following properties:

Name Type Description
addFunction functionType The add method used
arguments list<expression> The argument used for add
typeArguments list<type>? The type argument if Generic is involved

Inherits properties from:

astnode

Example

The following pattern matches the C# example shown in the previous section:

CXM code follows
pattern collectionInitializer { objectInitializer { .memberInitializers == addMemberInitializer } };

See Also

objectInitializer, nestedMemberInitializer, assignmentMemberInitializer

arrayDimensionsInitializer (pattern)

Matches multidimensional array initializations.

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> A list of the dimensions

Inherits properties from:

astnode

Example

The arrayDimensionsInitializer pattern matches code such as the following array initialization:

C# code follows
int a[][][] = new int[3][][];

arrayInitializer (pattern)

Matches the initializations of linear arrays that use a list enclosed in braces (curly brackets).

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 in the curly braces

Inherits properties from:

astnode

Example

The arrayInitializer pattern matches code such as the following array initialization:

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

assignmentMemberInitializer (pattern)

Matches object initializers that set the value of their members.

Details

Object initializers let you assign values to any accessible fields or properties of an object at creation time. If you use an object initializer, you don’t have to invoke a constructor followed by lines of assignment statements. For example:

C# code follows
Cat cat = new Cat { Age = 10, Name = "Fluffy" };

This pattern only matches nodes of type addMemberInitializer, assignmentMemberInitializer, or nestedMemberInitializer.

Properties

assignmentMemberInitializer produces a record that contains the following properties:

Name Type Description
expression expression The expression for the initial value.
fieldOrSetter bool Whether we are setting via a field (true) or via a getter (false)
typeArguments list<type>? The type argument if Generic is involved; null otherwise

Inherits properties from:

astnode

Example

The following pattern matches the C# example shown in the “Detail” section, above:

CXM code follows
pattern objectInitializerWithNull { objectInitializer { .memberInitializers == assignmentMemberInitializer { .expression = nullLIteral } } };

See Also

objectInitializer, nestedMemberInitializer, addMemberInitializer

baseClassInitializer (pattern)

Matches initialization calls to the super() function.

Details

This pattern only matches nodes of type constructorInitializer.

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

Given the following CodeXM pattern:

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

... it would match the call to super() in the following C# code:

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

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 the arguments passed to the constructor
constructorFunction symbol The symbol that represents the constructor function used
enclosingClassReference expression? Non-null when an inner class is used. For example, in the initializer y.new X() this value would be "y".

Inherits properties from:

astnode

Example

For the following C# initialization:

C# code follows
ExampleObj o = new ExampleObject(5);

... the following CodeXM can be used to match it. The example pattern matches a constructor that takes an integer literal as 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 the value that is used to initialize the scalar object

Inherits properties from:

astnode

Examples

The expressionInitializer pattern would match the following C# initialization:

C# code follows
int a = x + y;

The following pattern matches all initializations done using binary operations.

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 constructorInitializer.

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

nestedMemberInitializer (pattern)

Matches object initializers that allow further nesting of initializers.

Details

You can apply an initializer to a field or value obtained from a getter, as in the following example:

C# code follows
var t = new T {
nestedItem = // nestedMemberInitializer
{ // addMemberInitializer
{ x, y }
}
};

This pattern only matches nodes of type addMemberInitializer, assignmentMemberInitializer, or nestedMemberInitializer.

Properties

nestedMemberInitializer produces a record that contains the following properties:

Name Type Description
fieldOrGetter bool Whether we are setting the value by using a field (true) or by using a getter (false)
initializer initializer The initializer used.

Note: You can use any kind of initializer, not just member initializers.

typeArguments list<type>? The type arguments if Generic is involved; null otherwise

Inherits properties from:

astnode

Example

The following pattern would match the C# example shown in the previous section:

CXM code follows
pattern nestingWithAddInitializer { objectInitializer { .memberInitializers == nestedMemberInitializer { .initializer == objectInitializer { .memberInitializers == addMemberInitializer } } } };

See Also

objectInitializer, addMemberInitializer, assignmentMemberInitializer

objectInitializer (pattern)

Matches object initializers used in variable declarations and temporary constructions.

Details

The constructor is called first, then additional initializers are called. A user can specify a series of field or property assignments. For example:

C# code follows
Cat cat = new Cat { Age = 10, Name = "Fluffy" };

Also, collections can have multiple values which are all added via calls to collection, as in the following code:

C# code follows
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

This pattern only matches nodes of type initializer.

Properties

objectInitializer produces a record that contains the following properties:

Name Type Description
initializer initializer The constructor used
memberInitializers memberInitializer The member initializer used

Inherits properties from:

astnode

Example

The following pattern matches a collection initializer:

CXM code follows
pattern collectionInitializer { objectInitializer { .memberInitializers == addMemberInitializer } };

See Also

temporaryExpression, temporaryConstruction, variableDeclaration, nestedMemberInitializer, addMemberInitializer, assignmentMemberInitializer

peerConstructorInitializer (pattern)

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

Details

This pattern only matches nodes of type constructorInitializer.

Properties

This pattern does not expose any new properties.

Inherits properties from:

astnode

zeroInitializer (pattern)

Matches initializations where no value is provided.

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 class declared as follows:

C# code follows
class Example {
private int a;
};

... the initialization of the field `a` will match 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 C# 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

enumeratorSymbol (pattern)

Matches the symbols in an enum.

Details

This pattern only matches nodes of type symbol.

Properties

enumeratorSymbol produces a record that contains the following properties:

Name Type Description
isExplicit bool Whether this enum is explicit
ownerEnumType type The owner enum type
value int The integer value of the symbol

Inherits properties from:

symbol

enumVariableSymbol (pattern)

Matches symbols used in 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 pattern finds all uses of enum variables:

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

fieldSymbol (pattern)

Matches field symbols in class declarations.

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`
attributes list<codeAttribute> A list of the code attributes 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 the 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
attributes list<codeAttribute> A list of the code attributes 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
isAnonymous bool true if the function is a lambda or anonymous method
isAsync bool true if the function is async
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
isDestructor bool true if the function is a destructor
isExtension bool true if the function is an extension method
isFinal bool true if the function is declared final
isGeneric bool true if the function is generic
isOverride bool true if the function is overriding
isStaticConstructor bool true if the function is a static constructor
isStaticMethod bool true if the function is a static method
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 calls to synchronized functions:

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

localVariableSymbol (pattern)

Matches the 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 they symbol 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 pattern finds all uses of local variables:

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

parameterSymbol (pattern)

Matches parameter symbols 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
access enum The type of access: `public`, `private`, or `protected`
extra extra 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
location location The parameter’s location information
ownerClass classType The owner class for the symbol
position sourceloc 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 parameter’s type

Inherits properties from:

symbol

Example

The following pattern finds all uses of parameters that are references:

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

staticVariableSymbol (pattern)

Matches symbols for variables declared 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
attributes list<codeAttribute> A list of the code attributes applied to this variable
isFinal bool true if the variable is declared final
ownerClass classType The class this variable is located in
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 pattern 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
variableScopeKind enum Either `local` for local variables, or `static` for statically defined variables; see variableScopeKind
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.

codeAttribute (record)

Represents a code attribute. Attributes can be placed on classes, class variables, or methods.

Properties

Name Type Description
attributeType classType The attribute type
arguments list<attributeArgument> The arguments to the attribute

Example

This type can be used to inspect attributes such as the [Obsolete] attribute in the following sample code:

C# code follows
class Example {
[Obsolete]
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 (possibly null)
kind variableDeclarationKind The kind of declaration
variable symbol The symbol of the variable

Example

The following pattern matches a try-with-resource statement, using a resource named 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 a try/catch block.

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 that represents the exception being 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 C# 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 it is available to the analysis.

Parameters and Return Value

Name Type Description
classTypeResult classType The class type whose definition will be fetched
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 target-code array int[] a gives you the result integralType.

stripReferenceTypes( t )

A function that removes the reference types around a base type.

Details

It is sometimes useful to strip away the reference types 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 Values

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

Example

For the following C# code:

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

... the parameter c can be passed as a referenceType. To inspect the type being referenced, you can use the following pattern:

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.

aliasTypeOf( baseType )

This function matches any aliased type (for example, one aliased via a using statement) defined in terms of the parameter given.

Details

Use this function to detect not only a specified type, but any other type defined as an alias of that type.

Parameters and Return Values

Name Type Description
baseType pattern(type) -> Result A pattern based on a specific type
return value pattern(type) -> Result A pattern similarly matching the desired type, or any alias

Example

Assuming that the following type definitions appear in your source code:

C# code follows
using myInt = int;
using myNewInt = myInt;

... then the use of the following pattern:

CXM code follows
aliasTypeOf(int);

... matches the actual type int in your source code, as well as any uses of type myInt, and even myNewInt (or any other alias based on any of these types).

arrayOf( typePattern )

A function that generates a pattern to match arrays of a particular type.

Details

This can be used to construct patterns that match nested structure. å

Parameters and Return Values

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

constOf( typePattern )

Matches types that have a const qualification.

Details

The pattern produced by this function matches various forms of const qualification of the type described by the typePattern field, including the following kinds of constants:

Parameters and Return Values

Name Type Description
typePattern pattern(type) -> Result A pattern matching some simple type
return value pattern(type) -> Result A pattern that matches a const-qualified variation of the given type

Example

Assuming that the following type definition appears in your source code:

C# code follows
const int ci;

... then the use of this pattern:

CXM code follows
constOf(int);

... matches the actual type const int in your source code.

See Also

cvModifiedType, cvModifierKind

getQualifiers( t )

Returns a list of const/volatile qualifiers, including ones that are hidden behind aliases.

Parameters and Return Value

Name Type Description
t type The input type
return value list<cvModifiedType> A list of modifiers

See Also

cvModifiedType, cvModifierKind

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 C# snippet:

C# 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:

C# code follows
void example(int i, short s) {
s = (short) i;
}

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

See Also

stripBoxes, stripCastsAndBoxes

stripCastsAndBoxes( e )

This function strips an outermost cast and box expression, if those are present, and returns the underlying expression.

If the expression consists of sub-expressions which themselves are cast or box expressions, 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 )

This function decomposes expressions that have implicit casts. In other words, it strips casts that are not explicitly placed in the source code, but rather are implicitly put there by the C# compiler.

Parameters and Return Value

Name Type Description
e expression The expression to strip casts from. If a non-cast is passed here it is just returned.
return value expression The expression, free of casts

Example

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

C# code follows
short s = 5;
long l;
l = s; // implicit cast here

To match all assignments from short integers, we might need to use stripImplicitCasts in the following way:

CXM code follows
pattern allAssignmentsFromShorts { assignmentOperator as assignment where stripImplicitCasts( assignment.sourceExpression ) matches variableReference as v && v.type matches integralType { .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 whether a function overrides a function named 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;