summaryrefslogtreecommitdiff
path: root/cont.c
blob: 928f9381adca156acf87032f147cf2c198e9586f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**********************************************************************

  cont.c - 

  $Author$
  $Date$
  created at: Thu May 23 09:03:43 2007

  Copyright (C) 2007 Koichi Sasada

**********************************************************************/

#include "ruby.h"
#include "yarvcore.h"
#include "gc.h"
#include "eval_intern.h"

typedef struct rb_continuation_struct {
    rb_thread_t saved_thread;
    rb_jmpbuf_t jmpbuf;
    VALUE retval;
    VALUE *vm_stack;
    VALUE *machine_stack;
    VALUE *machine_stack_src;
    int machine_stack_size;
} rb_continuation_t;

#define GetContPtr(obj, ptr)  \
  Data_Get_Struct(obj, rb_continuation_t, ptr)

NOINLINE(static VALUE cont_capture(volatile int *stat));

void rb_thread_mark(rb_thread_t *th);

static void
cont_mark(void *ptr)
{
    MARK_REPORT_ENTER("cont");
    if (ptr) {
	rb_continuation_t *cont = ptr;
	rb_gc_mark(cont->retval);
	rb_thread_mark(&cont->saved_thread);

	if (cont->vm_stack) {
	    rb_gc_mark_locations(cont->vm_stack,
				 cont->vm_stack + cont->saved_thread.stack_size);
	}
	
	if (cont->machine_stack) {
	    rb_gc_mark_locations(cont->machine_stack,
				 cont->machine_stack + cont->machine_stack_size);
	}
    }
    MARK_REPORT_LEAVE("cont");
}

static void
cont_free(void *ptr)
{
    FREE_REPORT_ENTER("cont");
    if (ptr) {
	rb_continuation_t *cont = ptr;
	FREE_UNLESS_NULL(cont->machine_stack);
	FREE_UNLESS_NULL(cont->vm_stack);
	ruby_xfree(ptr);
    }
    FREE_REPORT_LEAVE("cont");
}

static VALUE
cont_capture(volatile int *stat)
{
    rb_continuation_t *cont;
    VALUE contval;
    rb_thread_t *th = GET_THREAD(), *sth;
    int size;

    contval = Data_Make_Struct(rb_cCont, rb_continuation_t,
			       cont_mark, cont_free, cont);

    /* save context */
    cont->saved_thread = *th;
    sth = &cont->saved_thread;
    sth->stack = 0; /* clear to skip GC marking */
    cont->vm_stack = ALLOC_N(VALUE, sth->stack_size);
    MEMCPY(cont->vm_stack, th->stack, VALUE, sth->stack_size);

    rb_gc_set_stack_end(&th->machine_stack_end);
    if (th->machine_stack_start > th->machine_stack_end) {
	size = cont->machine_stack_size = th->machine_stack_start - th->machine_stack_end;
	cont->machine_stack_src = th->machine_stack_end;
    }
    else {
	size = cont->machine_stack_size = th->machine_stack_end - th->machine_stack_start;
	cont->machine_stack_src = th->machine_stack_start;
    }

    cont->machine_stack = ALLOC_N(VALUE, size);
    MEMCPY(cont->machine_stack, cont->machine_stack_src, VALUE, size);

    if (ruby_setjmp(cont->jmpbuf)) {
	VALUE retval;

	retval = cont->retval;
	cont->retval = Qnil;
	*stat = 1;
	return retval;
    }
    else {
	*stat = 0;
	return contval;
    }
}

static void
cont_restore_context_1(rb_continuation_t *cont)
{
    rb_thread_t *th = GET_THREAD(), *sth = &cont->saved_thread;

    /* restore thread context */
    MEMCPY(th->stack, cont->vm_stack, VALUE, sth->stack_size);

    th->cfp = sth->cfp;
    th->safe_level = sth->safe_level;
    th->raised_flag = sth->raised_flag;
    th->state = sth->state;
    th->status = sth->status;
    th->tag = sth->tag;

    /* restore machine stack */
    MEMCPY(cont->machine_stack_src, cont->machine_stack,
	   VALUE, cont->machine_stack_size);

    ruby_longjmp(cont->jmpbuf, 1);
}

NORETURN(NOINLINE(static void restore_context_0(rb_continuation_t *, VALUE *)));

static void
cont_restore_context_0(rb_continuation_t *cont, VALUE *addr_in_prev_frame)
{
#define STACK_PAD_SIZE 1024
    VALUE space[STACK_PAD_SIZE];

#if STACK_GROW_DIRECTION < 0 /* downward */
    if (addr_in_prev_frame > cont->machine_stack_src) {
	cont_restore_context_0(cont, &space[0]);
    }
#elif STACK_GROW_DIRECTION > 0 /* upward */
    if (addr_in_prev_frame < cont->machine_stack_src + cont->machine_stack_size) {
	cont_restore_context_0(cont, &space[STACK_PAD_SIZE-1]);
    }
#else
    if (addr_in_prev_frame > &space[0]) {
	/* Stack grows downward */
	if (addr_in_prev_frame > cont->saved_thread.machine_stack_src) {
	    cont_restore_context_0(cont, &space[0]);
	}
    }
    else {
	/* Stack grows upward */
	if (addr_in_prev_frame < cont->machine_stack_src + cont->machine_stack_size) {
	    cont_restore_context_0(cont, &space[STACK_PAD_SIZE-1]);
	}
    }
#endif
    cont_restore_context_1(cont);
}

/*
 *  Document-class: Continuation
 *
 *  Continuation objects are generated by
 *  <code>Kernel#callcc</code>. They hold a return address and execution
 *  context, allowing a nonlocal return to the end of the
 *  <code>callcc</code> block from anywhere within a program.
 *  Continuations are somewhat analogous to a structured version of C's
 *  <code>setjmp/longjmp</code> (although they contain more state, so
 *  you might consider them closer to threads).
 *     
 *  For instance:
 *     
 *     arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
 *     callcc{|$cc|}
 *     puts(message = arr.shift)
 *     $cc.call unless message =~ /Max/
 *     
 *  <em>produces:</em>
 *     
 *     Freddie
 *     Herbie
 *     Ron
 *     Max
 *     
 *  This (somewhat contrived) example allows the inner loop to abandon
 *  processing early:
 *     
 *     callcc {|cont|
 *       for i in 0..4
 *         print "\n#{i}: "
 *         for j in i*5...(i+1)*5
 *           cont.call() if j == 17
 *           printf "%3d", j
 *         end
 *       end
 *     }
 *     print "\n"
 *     
 *  <em>produces:</em>
 *     
 *     0:   0  1  2  3  4
 *     1:   5  6  7  8  9
 *     2:  10 11 12 13 14
 *     3:  15 16
 */

VALUE rb_cCont;

/*
 *  call-seq:
 *     callcc {|cont| block }   =>  obj
 *  
 *  Generates a <code>Continuation</code> object, which it passes to the
 *  associated block. Performing a <em>cont</em><code>.call</code> will
 *  cause the <code>callcc</code> to return (as will falling through the
 *  end of the block). The value returned by the <code>callcc</code> is
 *  the value of the block, or the value passed to
 *  <em>cont</em><code>.call</code>. See class <code>Continuation</code>
 *  for more details. Also see <code>Kernel::throw</code> for
 *  an alternative mechanism for unwinding a call stack.
 */

static VALUE
rb_callcc(VALUE self)
{
    volatile int called;
    volatile VALUE val = cont_capture(&called);

    if (called) {
	return val;
    }
    else {
	return rb_yield(val);
    }
}

/*
 *  call-seq:
 *     cont.call(args, ...)
 *     cont[args, ...]
 *  
 *  Invokes the continuation. The program continues from the end of the
 *  <code>callcc</code> block. If no arguments are given, the original
 *  <code>callcc</code> returns <code>nil</code>. If one argument is
 *  given, <code>callcc</code> returns it. Otherwise, an array
 *  containing <i>args</i> is returned.
 *     
 *     callcc {|cont|  cont.call }           #=> nil
 *     callcc {|cont|  cont.call 1 }         #=> 1
 *     callcc {|cont|  cont.call 1, 2, 3 }   #=> [1, 2, 3]
 */

static VALUE
rb_cont_call(int argc, VALUE *argv, VALUE contval)
{
    rb_continuation_t *cont;
    rb_thread_t *th = GET_THREAD();
    GetContPtr(contval, cont);

    if (cont->saved_thread.value != th->value) {
	rb_raise(rb_eRuntimeError, "continuation called across threads");
    }
    if (cont->saved_thread.trap_tag != th->trap_tag) {
	rb_raise(rb_eRuntimeError, "continuation called across trap");
    }

    switch(argc) {
      case 0:
	cont->retval = Qnil;
	break;
      case 1:
	cont->retval = argv[0];
	break;
      default:
	cont->retval = rb_ary_new4(argc, argv);
	break;
    }

    cont_restore_context_0(cont, (VALUE *)&cont);
    return Qnil; /* unreachable */
}

void
Init_Cont(void)
{
    rb_cCont = rb_define_class("Continuation", rb_cObject);
    rb_undef_alloc_func(rb_cCont);
    rb_undef_method(CLASS_OF(rb_cCont), "new");
    rb_define_method(rb_cCont, "call", rb_cont_call, -1);
    rb_define_method(rb_cCont, "[]", rb_cont_call, -1);
    rb_define_global_function("callcc", rb_callcc, 0);
}