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.


    Not finding what you need in this doc? Ask questions in our Community Slack group, or see Support for other ways to get help.