What is Constant Folding?
Constant folding is an optimization technique that evaluates constant expressions at compile time rather than runtime. For example, the expression1 + 2 can be replaced with 3, and "hello" .. " world" can become "hello world".
This optimization:
- Reduces runtime computation
- Makes code easier to read in some cases
- Can help with further optimizations
- Preserves program behavior
ConstantFolder Class
TheConstantFolder is a LuaSyntaxRewriter that walks through syntax trees and replaces constant expressions with their computed values.
Usage
Use theConstantFold extension method to apply constant folding to any syntax node:
ConstantFoldingOptions
TheConstantFoldingOptions record allows you to configure constant folding behavior.
Available Options
When enabled, the folder will extract numeric values from string literals when they’re used in numeric operations.
Presets
ConstantFoldingOptions.Default - The most conservative preset with all options disabled:Custom Options
Create custom options by instantiating the record:Supported Operations
The constant folder supports a wide range of Lua operations:Arithmetic Operations
- Addition:
1 + 2→3 - Subtraction:
5 - 3→2 - Multiplication:
4 * 5→20 - Division:
10 / 2→5 - Modulo:
10 % 3→1 - Exponentiation:
2 ^ 3→8 - Unary minus:
-5→-5
Bitwise Operations (Lua 5.3+)
- Bitwise OR:
5 | 3→7 - Bitwise AND:
5 & 3→1 - Bitwise XOR:
5 ~ 3→6 - Bitwise NOT:
~5→-6 - Left shift:
1 << 3→8 - Right shift:
8 >> 2→2
String Operations
- Concatenation:
"hello" .. " " .. "world"→"hello world" - Length:
#"hello"→5 - Boolean concatenation:
"value: " .. true→"value: true"
Comparison Operations
- Equality:
5 == 5→true - Inequality:
5 ~= 3→true - Less than:
3 < 5→true - Less than or equal:
3 <= 3→true - Greater than:
5 > 3→true - Greater than or equal:
5 >= 5→true
Logical Operations
- NOT:
not false→true - AND:
true and 5→5,false and 5→false - OR:
true or 5→true,false or 5→5
Table Operations
- Member access on constant tables:
{x = 5}.x→5 - Element access on constant tables:
{["key"] = 10}["key"]→10
Other Optimizations
- Removes redundant parentheses:
((5))→5
Before and After Example
Limitations
The constant folder has important limitations:Special Values
- NaN and Infinity: Operations that produce
NaNorInfinityare not folded to preserve safety - Example:
0 / 0is not folded because it producesNaN
Dynamic Values
- Function calls cannot be folded:
math.sqrt(16)remains as-is - Variable references cannot be folded:
x + 1wherexis a variable - Indexing non-constant tables:
someTable[key]remains as-is
Scope Limitations
- Only literal values and expressions built from literals are folded
- No cross-statement or cross-function analysis is performed
Type Coercion
- String-to-number coercion requires
ExtractNumbersFromStringsoption - Complex type coercions may not be supported
When to Use Constant Folding
Good Use Cases
- Code generators: Pre-compute values in generated code
- Optimization pipelines: As part of a larger optimization strategy
- Dead code elimination: Simplify conditional expressions for further analysis
- Build-time optimization: Optimize code during build/deployment
When to Avoid
- Debugging: Folded constants can make debugging harder
- Source mapping: May complicate source map generation
- Readability: Sometimes the original expression is clearer than the folded value
- Float precision: Be cautious with floating-point operations where precision matters
See Also
- Minifier - Reduce code size and obfuscate variable names
- Experimental Package Overview - Learn about other experimental features