Branch stack effects

Factor handbook » The language » Stack effect checking

Factor handbook » The language » Stack effect checking

Prev: | Recursive combinator stack effects |

Next: | Stack checker errors |

Conditionals such as if and combinators built on top have the same restrictions as inline combinators (see Combinator stack effects ) with the additional requirement that all branches leave the stack at the same height. If this is not the case, the stack checker throws an unbalanced-branches-error.

If all branches leave the stack at the same height, then the stack effect of the conditional is just the maximum of the stack effect of each branch. For example,

The call to if takes one value from the stack, a generalized boolean. The first branch [ + ] has stack effect ( x x -- x ) and the second has stack effect ( x -- ). Since both branches decrease the height of the stack by one, we say that the stack effect of the two branches is ( x x -- x ), and together with the boolean popped off the stack by if, this gives a total stack effect of ( x x x -- x ).

If all branches leave the stack at the same height, then the stack effect of the conditional is just the maximum of the stack effect of each branch. For example,

[ [ + ] [ drop ] if ] infer.

( x x x -- x )

( x x x -- x )

The call to if takes one value from the stack, a generalized boolean. The first branch [ + ] has stack effect ( x x -- x ) and the second has stack effect ( x -- ). Since both branches decrease the height of the stack by one, we say that the stack effect of the two branches is ( x x -- x ), and together with the boolean popped off the stack by if, this gives a total stack effect of ( x x x -- x ).