coroutines: 4-space style.

db4
John Benediktsson 2012-09-22 12:57:46 -07:00
parent fa310fe054
commit b9b5c6e927
1 changed files with 27 additions and 26 deletions

View File

@ -9,43 +9,44 @@ SYMBOL: current-coro
TUPLE: coroutine resumecc exitcc originalcc ; TUPLE: coroutine resumecc exitcc originalcc ;
: cocreate ( quot -- co ) : cocreate ( quot -- co )
coroutine new coroutine new
dup current-coro associate dup current-coro associate
[ swapd , , \ with-variables , [
"Coroutine has terminated illegally." , \ throw , swapd , , \ with-variables ,
] [ ] make "Coroutine has terminated illegally." , \ throw ,
[ >>resumecc ] [ >>originalcc ] bi ; ] [ ] make
[ >>resumecc ] [ >>originalcc ] bi ;
: coresume ( v co -- result ) : coresume ( v co -- result )
[ [
>>exitcc >>exitcc
resumecc>> call( -- ) resumecc>> call( -- )
#! At this point, the coroutine quotation must have terminated #! At this point, the coroutine quotation must have terminated
#! normally (without calling coyield, coreset, or coterminate). #! normally (without calling coyield, coreset, or coterminate).
#! This shouldn't happen. #! This shouldn't happen.
f over f over
] callcc1 2nip ; ] callcc1 2nip ;
: coresume* ( v co -- ) coresume drop ; inline : coresume* ( v co -- ) coresume drop ; inline
: *coresume ( co -- result ) f swap coresume ; inline : *coresume ( co -- result ) f swap coresume ; inline
: coyield ( v -- result ) : coyield ( v -- result )
current-coro get current-coro get
[ [
[ continue-with ] curry [ continue-with ] curry
>>resumecc >>resumecc
exitcc>> continue-with exitcc>> continue-with
] callcc1 2nip ; ] callcc1 2nip ;
: coyield* ( v -- ) coyield drop ; inline : coyield* ( v -- ) coyield drop ; inline
: *coyield ( -- v ) f coyield ; inline : *coyield ( -- v ) f coyield ; inline
: coterminate ( v -- ) : coterminate ( v -- )
current-coro get current-coro get
[ ] >>resumecc [ ] >>resumecc
exitcc>> continue-with ; exitcc>> continue-with ;
: coreset ( v -- ) : coreset ( v -- )
current-coro get dup current-coro get dup
originalcc>> >>resumecc originalcc>> >>resumecc
exitcc>> continue-with ; exitcc>> continue-with ;