Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement continuations?

I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal.

What is the simplest way to implement continuations for Scheme in C?

like image 641
Kyle Cronin Avatar asked Aug 09 '08 01:08

Kyle Cronin


People also ask

How are continuations implemented?

Continuations basically consist of the saved state of the stack and CPU registers at the point of context switches. At the very least you don't have to copy the entire stack to the heap when switching, you could only redirect the stack pointer. Continuations are trivially implemented using fibers.

What are continuations in scheme?

An expression's continuation is "the computation that will receive the result of that expression". For example, in the expression (+ 4 (+ 1 2)) the result of (+ 1 2) will be added to 4. The addition to 4 is that expression's continuation.


1 Answers

A good summary is available in Implementation Strategies for First-Class Continuations, an article by Clinger, Hartheimer, and Ost. I recommend looking at Chez Scheme's implementation in particular.

Stack copying isn't that complex and there are a number of well-understood techniques available to improve performance. Using heap-allocated frames is also fairly simple, but you make a tradeoff of creating overhead for "normal" situation where you aren't using explicit continuations.

If you convert input code to continuation passing style (CPS) then you can get away with eliminating the stack altogether. However, while CPS is elegant it adds another processing step in the front end and requires additional optimization to overcome certain performance implications.

like image 159
Josh Segall Avatar answered Oct 16 '22 08:10

Josh Segall