Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-fiber/src/fiber.c

raw
1 #include <mruby.h>
2 #include <mruby/array.h>
3 #include <mruby/class.h>
4 #include <mruby/error.h>
5 #include <mruby/proc.h>
6
7 #define fiber_ptr(o) ((struct RFiber*)mrb_ptr(o))
8
9 #define FIBER_STACK_INIT_SIZE 64
10 #define FIBER_CI_INIT_SIZE 8
11 /* copied from vm.c */
12 #define CINFO_RESUMED 3
13
14 /*
15 * call-seq:
16 * Fiber.new{...} -> obj
17 *
18 * Creates a fiber, whose execution is suspended until it is explicitly
19 * resumed using <code>Fiber#resume</code> method.
20 * The code running inside the fiber can give up control by calling
21 * <code>Fiber.yield</code> in which case it yields control back to caller
22 * (the caller of the <code>Fiber#resume</code>).
23 *
24 * Upon yielding or termination the Fiber returns the value of the last
25 * executed expression
26 *
27 * For instance:
28 *
29 * fiber = Fiber.new do
30 * Fiber.yield 1
31 * 2
32 * end
33 *
34 * puts fiber.resume
35 * puts fiber.resume
36 * puts fiber.resume
37 *
38 * <em>produces</em>
39 *
40 * 1
41 * 2
42 * resuming dead fiber (FiberError)
43 *
44 * The <code>Fiber#resume</code> method accepts an arbitrary number of
45 * parameters, if it is the first call to <code>resume</code> then they
46 * will be passed as block arguments. Otherwise they will be the return
47 * value of the call to <code>Fiber.yield</code>
48 *
49 * Example:
50 *
51 * fiber = Fiber.new do |first|
52 * second = Fiber.yield first + 2
53 * end
54 *
55 * puts fiber.resume 10
56 * puts fiber.resume 14
57 * puts fiber.resume 18
58 *
59 * <em>produces</em>
60 *
61 * 12
62 * 14
63 * resuming dead fiber (FiberError)
64 *
65 */
66 static mrb_value
67 fiber_init(mrb_state *mrb, mrb_value self)
68 {
69 static const struct mrb_context mrb_context_zero = { 0 };
70 struct RFiber *f = fiber_ptr(self);
71 struct mrb_context *c;
72 struct RProc *p;
73 mrb_callinfo *ci;
74 mrb_value blk;
75 size_t slen;
76
77 mrb_get_args(mrb, "&!", &blk);
78
79 if (f->cxt) {
80 mrb_raise(mrb, E_RUNTIME_ERROR, "cannot initialize twice");
81 }
82 p = mrb_proc_ptr(blk);
83 if (MRB_PROC_CFUNC_P(p)) {
84 mrb_raise(mrb, E_FIBER_ERROR, "tried to create Fiber from C defined method");
85 }
86
87 c = (struct mrb_context*)mrb_malloc(mrb, sizeof(struct mrb_context));
88 *c = mrb_context_zero;
89 f->cxt = c;
90
91 /* initialize VM stack */
92 slen = FIBER_STACK_INIT_SIZE;
93 if (p->body.irep->nregs > slen) {
94 slen += p->body.irep->nregs;
95 }
96 c->stbase = (mrb_value*)mrb_malloc(mrb, slen*sizeof(mrb_value));
97 c->stend = c->stbase + slen;
98
99 {
100 mrb_value *p = c->stbase;
101 mrb_value *pend = c->stend;
102
103 while (p < pend) {
104 SET_NIL_VALUE(*p);
105 p++;
106 }
107 }
108
109 /* copy receiver from a block */
110 c->stbase[0] = mrb->c->ci->stack[0];
111
112 /* initialize callinfo stack */
113 c->cibase = (mrb_callinfo*)mrb_calloc(mrb, FIBER_CI_INIT_SIZE, sizeof(mrb_callinfo));
114 c->ciend = c->cibase + FIBER_CI_INIT_SIZE;
115 c->ci = c->cibase;
116
117 /* adjust return callinfo */
118 ci = c->ci;
119 mrb_vm_ci_target_class_set(ci, MRB_PROC_TARGET_CLASS(p));
120 mrb_vm_ci_proc_set(ci, p);
121 mrb_field_write_barrier(mrb, (struct RBasic*)mrb_obj_ptr(self), (struct RBasic*)p);
122 ci->stack = c->stbase;
123 ci[1] = ci[0];
124 c->ci++; /* push dummy callinfo */
125
126 c->fib = f;
127 c->status = MRB_FIBER_CREATED;
128
129 return self;
130 }
131
132 static struct mrb_context*
133 fiber_check(mrb_state *mrb, mrb_value fib)
134 {
135 struct RFiber *f = fiber_ptr(fib);
136
137 mrb_assert(f->tt == MRB_TT_FIBER);
138 if (!f->cxt) {
139 mrb_raise(mrb, E_FIBER_ERROR, "uninitialized Fiber");
140 }
141 return f->cxt;
142 }
143
144 static mrb_value
145 fiber_result(mrb_state *mrb, const mrb_value *a, mrb_int len)
146 {
147 if (len == 0) return mrb_nil_value();
148 if (len == 1) return a[0];
149 return mrb_ary_new_from_values(mrb, len, a);
150 }
151
152 /* mark return from context modifying method */
153 #define MARK_CONTEXT_MODIFY(c) (c)->ci->u.target_class = NULL
154
155 static void
156 fiber_check_cfunc(mrb_state *mrb, struct mrb_context *c)
157 {
158 mrb_callinfo *ci;
159
160 for (ci = c->ci; ci >= c->cibase; ci--) {
161 if (ci->cci > 0) {
162 mrb_raise(mrb, E_FIBER_ERROR, "can't cross C function boundary");
163 }
164 }
165 }
166
167 static void
168 fiber_switch_context(mrb_state *mrb, struct mrb_context *c)
169 {
170 if (mrb->c->fib) {
171 mrb_write_barrier(mrb, (struct RBasic*)mrb->c->fib);
172 }
173 c->status = MRB_FIBER_RUNNING;
174 mrb->c = c;
175 }
176
177 /*
178 * Argument mesg is limited to a string literal or "static const" string.
179 * Also, it must be called as `return fiber_error(...)`.
180 */
181 static mrb_value
182 fiber_error(mrb_state *mrb, const char *mesg)
183 {
184 mrb_value str = mrb_str_new_static(mrb, mesg, strlen(mesg));
185 mrb_value exc = mrb_exc_new_str(mrb, E_FIBER_ERROR, str);
186
187 if (mrb->jmp) {
188 mrb_exc_raise(mrb, exc);
189 }
190
191 mrb->exc = mrb_obj_ptr(exc);
192
193 return exc;
194 }
195
196 /* This function must be called as `return fiber_switch(...)` */
197 static mrb_value
198 fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)
199 {
200 struct mrb_context *c = fiber_check(mrb, self);
201 struct mrb_context *old_c = mrb->c;
202 enum mrb_fiber_state status;
203 mrb_value value;
204
205 if (resume && c == mrb->c) {
206 return fiber_error(mrb, "attempt to resume the current fiber");
207 }
208
209 fiber_check_cfunc(mrb, c);
210 status = c->status;
211 switch (status) {
212 case MRB_FIBER_TRANSFERRED:
213 if (resume) {
214 return fiber_error(mrb, "resuming transferred fiber");
215 }
216 break;
217 case MRB_FIBER_RUNNING:
218 case MRB_FIBER_RESUMED:
219 return fiber_error(mrb, "double resume");
220 break;
221 case MRB_FIBER_TERMINATED:
222 return fiber_error(mrb, "resuming dead fiber");
223 break;
224 default:
225 break;
226 }
227 if (resume) {
228 old_c->status = MRB_FIBER_RESUMED;
229 c->prev = mrb->c;
230 }
231 else {
232 old_c->status = MRB_FIBER_TRANSFERRED;
233 // c->prev = mrb->root_c;
234 c->prev = NULL;
235 }
236 fiber_switch_context(mrb, c);
237 if (status == MRB_FIBER_CREATED) {
238 mrb_value *b, *e;
239
240 if (!c->ci->proc) {
241 return fiber_error(mrb, "double resume (current)");
242 }
243 if (vmexec) {
244 c->ci--; /* pop dummy callinfo */
245 }
246 if (len >= 15) {
247 mrb_stack_extend(mrb, 3); /* for receiver, args and (optional) block */
248 c->stbase[1] = mrb_ary_new_from_values(mrb, len, a);
249 len = 15;
250 }
251 else {
252 mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */
253 b = c->stbase+1;
254 e = b + len;
255 while (b<e) {
256 *b++ = *a++;
257 }
258 }
259 c->cibase->n = (uint8_t)len;
260 struct REnv *env = MRB_PROC_ENV(c->cibase->proc);
261 if (env && env->stack) {
262 value = env->stack[0];
263 }
264 else {
265 value = mrb_top_self(mrb);
266 }
267 c->stbase[0] = value;
268 }
269 else {
270 value = fiber_result(mrb, a, len);
271 if (vmexec) {
272 c->ci[1].stack[0] = value;
273 }
274 }
275
276 if (vmexec) {
277 c->vmexec = TRUE;
278 value = mrb_vm_exec(mrb, c->ci->proc, c->ci->pc);
279 mrb->c = old_c;
280 }
281 else {
282 MARK_CONTEXT_MODIFY(c);
283 }
284 return value;
285 }
286
287 /*
288 * call-seq:
289 * fiber.resume(args, ...) -> obj
290 *
291 * Resumes the fiber from the point at which the last <code>Fiber.yield</code>
292 * was called, or starts running it if it is the first call to
293 * <code>resume</code>. Arguments passed to resume will be the value of
294 * the <code>Fiber.yield</code> expression or will be passed as block
295 * parameters to the fiber's block if this is the first <code>resume</code>.
296 *
297 * Alternatively, when resume is called it evaluates to the arguments passed
298 * to the next <code>Fiber.yield</code> statement inside the fiber's block
299 * or to the block value if it runs to completion without any
300 * <code>Fiber.yield</code>
301 *
302 * This method cannot be called from C using <code>mrb_funcall()</code>.
303 * Use <code>mrb_fiber_resume()</code> function instead.
304 */
305 static mrb_value
306 fiber_resume(mrb_state *mrb, mrb_value self)
307 {
308 const mrb_value *a;
309 mrb_int len;
310
311 fiber_check_cfunc(mrb, mrb->c);
312 mrb_get_args(mrb, "*!", &a, &len);
313 return fiber_switch(mrb, self, len, a, TRUE, FALSE);
314 }
315
316 MRB_API mrb_value
317 mrb_fiber_resume(mrb_state *mrb, mrb_value fib, mrb_int len, const mrb_value *a)
318 {
319 return fiber_switch(mrb, fib, len, a, TRUE, TRUE);
320 }
321
322 /*
323 * call-seq:
324 * fiber.alive? -> true or false
325 *
326 * Returns true if the fiber can still be resumed. After finishing
327 * execution of the fiber block this method will always return false.
328 */
329 MRB_API mrb_value
330 mrb_fiber_alive_p(mrb_state *mrb, mrb_value self)
331 {
332 struct mrb_context *c = fiber_check(mrb, self);
333 return mrb_bool_value(c->status != MRB_FIBER_TERMINATED);
334 }
335 #define fiber_alive_p mrb_fiber_alive_p
336
337 static mrb_value
338 fiber_eq(mrb_state *mrb, mrb_value self)
339 {
340 mrb_value other = mrb_get_arg1(mrb);
341
342 if (!mrb_fiber_p(other)) {
343 return mrb_false_value();
344 }
345 return mrb_bool_value(fiber_ptr(self) == fiber_ptr(other));
346 }
347
348 /*
349 * call-seq:
350 * fiber.transfer(args, ...) -> obj
351 *
352 * Transfers control to receiver fiber of the method call.
353 * Unlike <code>resume</code> the receiver wouldn't be pushed to call
354 * stack of fibers. Instead it will switch to the call stack of
355 * transferring fiber.
356 * When resuming a fiber that was transferred to another fiber it would
357 * cause double resume error. Though when the fiber is re-transferred
358 * and <code>Fiber.yield</code> is called, the fiber would be resumable.
359 */
360 static mrb_value
361 fiber_transfer(mrb_state *mrb, mrb_value self)
362 {
363 struct mrb_context *c = fiber_check(mrb, self);
364 const mrb_value* a;
365 mrb_int len;
366
367 fiber_check_cfunc(mrb, mrb->c);
368 mrb_get_args(mrb, "*!", &a, &len);
369
370 if (c->status == MRB_FIBER_RESUMED) {
371 mrb_raise(mrb, E_FIBER_ERROR, "attempt to transfer to a resuming fiber");
372 }
373
374 if (c == mrb->root_c) {
375 mrb->c->status = MRB_FIBER_TRANSFERRED;
376 fiber_switch_context(mrb, c);
377 MARK_CONTEXT_MODIFY(c);
378 return fiber_result(mrb, a, len);
379 }
380
381 if (c == mrb->c) {
382 return fiber_result(mrb, a, len);
383 }
384
385 return fiber_switch(mrb, self, len, a, FALSE, FALSE);
386 }
387
388 MRB_API mrb_value
389 mrb_fiber_yield(mrb_state *mrb, mrb_int len, const mrb_value *a)
390 {
391 struct mrb_context *c = mrb->c;
392
393 if (!c->prev) {
394 return fiber_error(mrb, "attempt to yield on a not resumed fiber");
395 }
396 if (c == mrb->root_c) {
397 return fiber_error(mrb, "can't yield from root fiber");
398 }
399 if (c->prev->status == MRB_FIBER_TRANSFERRED) {
400 return fiber_error(mrb, "attempt to yield on a not resumed fiber");
401 }
402
403 fiber_check_cfunc(mrb, c);
404 c->status = MRB_FIBER_SUSPENDED;
405 fiber_switch_context(mrb, c->prev);
406 c->prev = NULL;
407 if (c->vmexec) {
408 c->vmexec = FALSE;
409 mrb->c->ci->cci = CINFO_RESUMED;
410 c->ci--; /* pop callinfo for yield */
411 }
412 MARK_CONTEXT_MODIFY(mrb->c);
413 return fiber_result(mrb, a, len);
414 }
415
416 /*
417 * call-seq:
418 * Fiber.yield(args, ...) -> obj
419 *
420 * Yields control back to the context that resumed the fiber, passing
421 * along any arguments that were passed to it. The fiber will resume
422 * processing at this point when <code>resume</code> is called next.
423 * Any arguments passed to the next <code>resume</code> will be the
424 *
425 * mruby limitation: Fiber resume/yield cannot cross C function boundary.
426 * thus you cannot yield from #initialize which is called by mrb_funcall().
427 *
428 * This method cannot be called from C using <code>mrb_funcall()</code>.
429 * Use <code>mrb_fiber_yield()</code> function instead.
430 */
431 static mrb_value
432 fiber_yield(mrb_state *mrb, mrb_value self)
433 {
434 const mrb_value *a;
435 mrb_int len;
436
437 mrb_get_args(mrb, "*!", &a, &len);
438 return mrb_fiber_yield(mrb, len, a);
439 }
440
441 /*
442 * call-seq:
443 * Fiber.current() -> fiber
444 *
445 * Returns the current fiber. If you are not running in the context of
446 * a fiber this method will return the root fiber.
447 */
448 static mrb_value
449 fiber_current(mrb_state *mrb, mrb_value self)
450 {
451 if (!mrb->c->fib) {
452 struct RFiber *f = MRB_OBJ_ALLOC(mrb, MRB_TT_FIBER, mrb_class_ptr(self));
453
454 f->cxt = mrb->c;
455 mrb->c->fib = f;
456 }
457 return mrb_obj_value(mrb->c->fib);
458 }
459
460 void
461 mrb_mruby_fiber_gem_init(mrb_state* mrb)
462 {
463 struct RClass *c;
464
465 c = mrb_define_class(mrb, "Fiber", mrb->object_class);
466 MRB_SET_INSTANCE_TT(c, MRB_TT_FIBER);
467
468 mrb_define_method(mrb, c, "initialize", fiber_init, MRB_ARGS_NONE()|MRB_ARGS_BLOCK());
469 mrb_define_method(mrb, c, "resume", fiber_resume, MRB_ARGS_ANY());
470 mrb_define_method(mrb, c, "transfer", fiber_transfer, MRB_ARGS_ANY());
471 mrb_define_method(mrb, c, "alive?", fiber_alive_p, MRB_ARGS_NONE());
472 mrb_define_method(mrb, c, "==", fiber_eq, MRB_ARGS_REQ(1));
473
474 mrb_define_class_method(mrb, c, "yield", fiber_yield, MRB_ARGS_ANY());
475 mrb_define_class_method(mrb, c, "current", fiber_current, MRB_ARGS_NONE());
476
477 mrb_define_class(mrb, "FiberError", E_STANDARD_ERROR);
478 }
479
480 void
481 mrb_mruby_fiber_gem_final(mrb_state* mrb)
482 {
483 }