Stack effect declarations
Factor handbook ยป The language

Prev:Stack machine model
Next:Stack effect checking


Word definition words such as : and GENERIC: have a stack effect declaration as part of their syntax. A stack effect declaration takes the following form:
( input1 input2 ... -- output1 ... )

Stack elements in a stack effect are ordered so that the top of the stack is on the right side. Here is an example:
IN: math MATH: + ( x y -- z )

Parameters which are quotations can be declared by suffixing the parameter name with : and then writing a nested stack effect declaration. If the number of inputs or outputs depends on the stack effects of quotation parameters, row variables can be declared:
Stack effect row variables
Some examples of row-polymorphic combinators:
IN: kernel : while ( ..a pred: ( ..a -- ..b ? ) body: ( ..b -- ..a ) -- ..b )


IN: kernel : if* ( ..a ? true: ( ..a ? -- ..b ) false: ( ..a -- ..b ) -- ..b )


IN: sequences : each ( ... seq quot: ( ... x -- ... ) -- ... )

For words that are not inline, only the number of inputs and outputs carries semantic meaning, and effect variables are ignored. However, nested quotation declarations are enforced for inline words. Nested quotation declarations are optional for non-recursive inline combinators and only provide better error messages. However, quotation inputs to recursive combinators must have an effect declared. See Recursive combinator stack effects.

In concatenative code, input and output names are for documentation purposes only and certain conventions have been established to make them more descriptive. For code written with Lexical variables, stack values are bound to local variables named by the stack effect's input parameters.

Inputs and outputs are typically named after some pun on their data type, or a description of the value's purpose if the type is very general. The following are some examples of value names:
?a boolean
<=>an ordering specifier; see Ordering specifiers
eltan object which is an element of a sequence
m, nan integer
objan object
quota quotation
seqa sequence
assocan associative mapping
stra string
x, y, za number
loca screen location specified as a two-element array holding x and y coordinates
dima screen dimension specified as a two-element array holding width and height values
*when this symbol appears by itself in the list of outputs, it means the word unconditionally throws an error

For reflection and metaprogramming, you can use Stack effect syntax to include literal stack effects in your code, or these constructor words to construct stack effect objects at runtime:
<effect> ( in out -- effect )

<terminated-effect> ( in out terminated? -- effect )

<variable-effect> ( in-var in out-var out -- effect )


See also
Stack effect checking