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
use std::any::Any;
use gen_impl::Generator;
use rt::{Context, ContextStack, Error};
use reg_context::RegContext;
#[macro_export]
macro_rules! done { () => ({ return $crate::done() }) }
#[inline]
pub fn done<T>() -> T {
ContextStack::current().top()._ref = 0xf;
unsafe { ::std::mem::uninitialized() }
}
#[inline]
pub fn yield_now() {
let env = ContextStack::current();
let cur = env.top();
raw_yield_now(&env, cur);
}
#[inline]
pub fn raw_yield_now(env: &ContextStack, cur: &mut Context) {
let parent = env.pop_context(cur as *mut _);
RegContext::swap(&mut cur.regs, &parent.regs);
}
#[inline]
fn raw_yield<T: Any>(env: &ContextStack, context: &mut Context, v: T) {
if !context.is_generator() {
panic!("yield from none generator context");
}
context.set_ret(v);
context._ref -= 1;
raw_yield_now(env, context);
if context._ref != 1 {
panic!(Error::Cancel);
}
}
#[inline]
pub fn yield_with<T: Any>(v: T) {
let env = ContextStack::current();
let context = env.top();
raw_yield(&env, context, v);
}
#[inline]
pub fn get_yield<A: Any>() -> Option<A> {
let context = ContextStack::current().top();
raw_get_yield(context)
}
#[inline]
fn raw_get_yield<A: Any>(context: &mut Context) -> Option<A> {
if !context.is_generator() {
error!("get yield from none generator context");
panic!(Error::ContextErr);
}
context.get_para()
}
#[inline]
pub fn yield_<A: Any, T: Any>(v: T) -> Option<A> {
let env = ContextStack::current();
let context = env.top();
raw_yield(&env, context, v);
raw_get_yield(context)
}
pub fn yield_from<A: Any, T: Any>(mut g: Generator<A, T>) -> Option<A> {
let env = ContextStack::current();
let context = env.top();
let mut p = context.get_para();
while !g.is_done() {
match g.raw_send(p) {
None => return None,
Some(r) => raw_yield(&env, context, r),
}
p = context.get_para();
}
p
}
pub fn co_yield_with<T: Any>(v: T) {
let env = ContextStack::current();
let context = env.co_ctx().unwrap();
if context._ref != 1 {
panic!(Error::Cancel);
}
context.set_ret(v);
context._ref -= 1;
let parent = env.pop_context(context);
let top = unsafe { &mut *context.parent };
RegContext::swap(&mut top.regs, &parent.regs);
}
pub fn co_get_yield<A: Any>() -> Option<A> {
match ContextStack::current().co_ctx() {
Some(ctx) => ctx.get_para(),
None => None,
}
}