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:
| Pattern | Matches |
|---|---|
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 == $X | A 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:
$_matches anything, and its occurrences need not match the same code:$_ == $_matches every comparison with==;$...ARGS, a metavariable after..., matches a sequence like the ellipsis and binds it, for example the arguments of a call infoo($...ARGS).
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: ERRORapp.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: WARNINGself-compare.py
# ruleid: self-compareif token == token: pass# ok: self-compareif token == expected: passCommand and result
$ opengrep test .
1/1: ✓ All tests passed
No tests for fixes found.