+\ ---- Continuations ---- {{{
+
+: cons-return-stack ( -- listobj )
+ rsp@ 1- rsp0 = if
+ nil exit
+ then
+
+ nil rsp@ 1- rsp0 do
+ i 1+ @ fixnum-type 2swap cons
+ loop
+
+ rsp@ 1- rsp0 - fixnum-type 2swap cons
+;
+
+: cons-param-stack ( -- listobj )
+ nil
+
+ depth 2- object-stack-base @ = if
+ exit
+ then
+
+ depth 2- object-stack-base @ do
+ PSP0 i + 1 + @
+ PSP0 i + 2 + @
+
+ 2swap cons
+ 2 +loop
+
+ depth 2- 2/ fixnum-type 2swap cons
+;
+
+: make-continuation ( -- continuation true-obj )
+ \ true-obj allows calling code to detect whether
+ \ it is being called immediately following make-continuation
+ \ or by a restore-continuation.
+
+ cons-param-stack
+ cons-return-stack
+ cons drop continuation-type
+
+ true boolean-type
+;
+
+: continuation->pstack-list
+ drop pair-type car ;
+
+: continuation->rstack-list
+ drop pair-type cdr ;
+
+: stack-list-len ( stack-list -- n )
+ car drop
+;
+
+: restore-param-stack ( continuation -- obj_stack )
+ continuation->pstack-list
+ 2dup >R >R
+
+ ( Allocate stack space first using psp!,
+ then copy objects from list. )
+
+ car drop 2*
+ object-stack-base @ psp0 + + psp!
+
+ R> R> 2dup cdr
+ 2swap
+ stack-list-len 1- 0 swap do
+
+ 2dup car
+ PSP0 object-stack-base @ + i 2* + 2 + !
+ PSP0 object-stack-base @ + i 2* + 1 + !
+ cdr
+
+ -1 +loop
+
+ 2drop
+;
+
+: restore-return-stack ( continuation -- )
+
+ continuation->rstack-list
+
+ 2dup cdr 2swap stack-list-len ( list n )
+
+ dup RSP0 + RSP! \ expand return stack to accommodate entries
+
+ ( list n )
+
+ 1- \ initial offset n-1
+ 0 \ final offset 0
+ swap
+ do
+ 2dup cdr 2swap car drop
+ RSP0 i 1+ + !
+ -1 +loop
+
+ 2drop
+;
+
+: restore-continuation-with-arg ( continuation obj -- )
+
+ >R >R \ Store obj on return stack
+
+ 2dup >R >R \ Store copy of continuation on return stack
+
+ restore-param-stack
+
+ R> R> \ Pop continuation from return stack
+
+ R> R> \ Pop obj from return stack
+
+ 2swap
+
+ false boolean-type \ Add flag signifying continuation restore
+
+ 2swap
+
+ restore-return-stack
+;
+
+\ }}}
+