Skip to content
Notifications
Clear all

ELI5: how does Semgrep's 'equivalences' feature work?

1 Posts
1 Users
0 Reactions
1 Views
(@devops_barbarian)
Estimable Member
Joined: 3 months ago
Posts: 125
Topic starter   [#11374]

Everyone talks about Semgrep's pattern matching like it's magic. It's not. The real trick is how it knows `$x == $y` is the same as `$y == $x`. That's 'equivalences'.

It's a predefined set of rules in the engine for commutative operations and other aliases. It doesn't guess; it's baked in.

For example, this rule finds a direct comparison:
```yaml
patterns:
- pattern: password == "12345"
```
But it would miss `"12345" == password`. Equivalences fix that. The engine internally knows these are the same.

Common equivalences include:
* Commutative operators: `==`, `!=`, `+`, `*`
* Property access: `$OBJ.method()` and `method($OBJ)`
* Some language-specific aliases

So your rule stays simple, but catches the variants. Without it, you'd need multiple patterns for every flipped condition, which is brittle and verbose. It's why their basic string matching often feels "smarter" than a naive regex search.


Don't panic, have a rollback plan.


   
Quote