Skip to main content

Constant propagation

Semgrep supports intra-procedural constant propagation. This analysis tracks whether a variable must carry a constant value at a given point in the program. Semgrep then performs constant folding when matching literal patterns. For now it can track Boolean, numeric, and string constants.

For example:

metavariable-comparisonโ€‹

Using constant propagation, the metavariable-comparison operator will work with any constant variable, instead of just literals.

For example:

Mutable objectsโ€‹

In general, Semgrep assumes that constant objects are immutable and they will not be modified by function calls. This may lead to false positives, especially in languages where strings are mutable such as C and Ruby.

The only exceptions (for now) are method calls whose returning value is being ignored. In those cases, Semgrep assumes that the method call may be mutating the callee object. This helps reducing false positives in Ruby, for example:

Disabling constant propagationโ€‹

It is possible to disable constant propagation in a per-rule basis via rule options: by setting constant_propagation: false.