reference Pattern syntax

Metavariables: $X

See also
..., (TYPE $X), message, focus-metavariable, metavariable-regex, <... ...>, imports and aliases, "..."

A metavariable is a $ followed by capital letters, digits and underscores, such as $X or $USER_ID. It matches any expression, or any name where the pattern has a name, and binds what it matched:

PatternMatches
eval($X)A call to eval with one argument, bound to $X.
$OBJ.$METHOD(...)Any method call; $OBJ binds the object, $METHOD the name of the method.
def $FUNC(...): ...Any function definition; $FUNC binds its name.
$X == $XA comparison of an expression with itself.

A metavariable that appears more than once must match the same code at each place: $X == $X matches token == token but not token == expected.

Two forms do not bind:

The code that a metavariable binds can be used in the rest of the rule: in the message and fix, which replace it with that code, and in conditions such as metavariable-regex and metavariable-pattern.

Examples

A method name in the message

pickle-load.yaml
rules:  - id: pickle-load    pattern: pickle.$LOAD(...)    message: pickle.$LOAD deserializes untrusted data    languages: [python]    severity: ERROR
app.py
import picklesession = pickle.loads(cookie)config = pickle.load(handle)
Command and result
$ opengrep scan -q --config pickle-load.yaml app.py
app.py

  error  pickle-load
  pickle.loads deserializes untrusted data

     3: session = pickle.loads(cookie)

  error  pickle-load
  pickle.load deserializes untrusted data

     4: config = pickle.load(handle)

The same code twice

self-compare.yaml
rules:  - id: self-compare    pattern: $X == $X    message: $X is compared with itself    languages: [python]    severity: WARNING
self-compare.py
# ruleid: self-compareif token == token:    pass# ok: self-compareif token == expected:    pass
Command and result
$ opengrep test .
1/1: ✓ All tests passed
No tests for fixes found.