Factor handbook » The language » Words » Compiler declarations



: foo ... ; foldable

Word description
Declares that the most recently defined word may be evaluated at compile-time if all inputs are literal. Foldable words must satisfy a very strong contract:
foldable words must not have any observable side effects,
foldable words must halt - for example, a word computing a series until it coverges should not be foldable, since compilation will not halt in the event the series does not converge.
both inputs and outputs of foldable words must be immutable.

The last restriction ensures that words such as clone do not satisfy the foldable word contract. Indeed, clone will output a mutable object if its input is mutable, and so it is undesirable to evaluate it at compile-time, since doing so would give incorrect semantics for code that clones mutable objects and proceeds to mutate them.

Folding optimizations are not applied if the call site of a word is in the same source file as the word. This is a side-effect of the compilation unit system; see Compilation units.

Most operations on numbers are foldable. For example, 2 2 + compiles to a literal 4, since + is declared foldable.