reference Pattern syntax

Typed metavariables

See also
$X, metavariable-type

In languages with declared types, a metavariable can be given a type: it then matches only an expression of that type. The type is the one Opengrep infers from the declarations in the file, such as the type of a parameter or of a local variable. The form follows the way the language writes a type:

LanguageFormExample
Java, C#, C(TYPE $X)(Statement $S).execute(...)
Go, Kotlin, TypeScript($X: TYPE)log(($X: string))

The form is written where an expression is expected. metavariable-type expresses the same condition as a separate key, which also applies to a metavariable bound elsewhere in the rule.

Examples

execute on a database statement only

statement-execute.yaml
rules:  - id: statement-execute    pattern: (java.sql.Statement $S).execute($Q)    message: SQL executed through a Statement; prefer a PreparedStatement    languages: [java]    severity: WARNING
statement-execute.java
import java.sql.Statement;import java.util.concurrent.ExecutorService;class Jobs {    void run(Statement stmt, ExecutorService pool, String sql, Runnable task) throws Exception {        // ruleid: statement-execute        stmt.execute(sql);        // ok: statement-execute        pool.execute(task);    }}
Command and result
$ opengrep test .
1/1: ✓ All tests passed
No tests for fixes found.