Syntax node can be matched by when blocks or selectors. A typical rules has various entry points for different types of AST nodes.
syntax rule MyRule on ApexPage, ApexComponent {
when element x {
// executed when a node of type "element" is found in the AST
}
when content x {
// executed when a node of type "content" is found in the AST
}
on detection x {
// This is executed for every detection captured
}
}
AST nodes have the following properties, that can be used in expressions
Example
when annotation x {
if (x.text .= "IsTest") {
// do this if the AST node's text contains "IsTest"
}
}
When checking expressions, we can check whether they invoke a target function by using its reference and the call-to operator (=>
).
when expression x {
if (x => @System.assert{1}) {
// the expression calls the System.assert function
}
}
Rules eventually capture violations (detections) on certain AST nodes. To report a violation on a node, we use the capture
statement
when element x {
if (x.line == 10) {
// capture a violation on x
capture x
}
}
When capturing nodes, additional attributes can be attached with the violation
when element x {
if (x.line == 10) {
// capture a violation on x, with the addition of two attributes
// 1) an attribute named "content", which contains the text content of x
// 2) an attribute named "type", which contains a constant string
capture x (content = x.text, type = "typeName")
}
}
When working with arrays of nodes (i.e. from a selector) you can capture multiple violations in one go.
var nodes = [x : find descendants ... ] // selector returns many nodes
capture nodes // capture a violation on all the nodes