1use lua_types::{
19 error::LuaError,
20 value::LuaValue,
21 LuaType,
22 LuaStatus,
23 gc::GcRef,
24};
25use crate::state_stub::{LuaState, LuaStateStubExt as _, lua_CFunction, upvalue_index};
26
27const COS_RUN: i32 = 0;
32
33const COS_DEAD: i32 = 1;
35
36const COS_YIELD: i32 = 2;
38
39const COS_NORM: i32 = 3;
41
42const STAT_NAMES: [&[u8]; 4] = [b"running", b"dead", b"suspended", b"normal"];
46
47pub const CO_FUNCS: &[(&[u8], lua_CFunction)] = &[
55 (b"create", co_create),
56 (b"resume", co_resume),
57 (b"running", co_running),
58 (b"status", co_status),
59 (b"wrap", co_wrap),
60 (b"yield", co_yield),
61 (b"isyieldable", co_isyieldable),
62 (b"close", co_close),
63];
64
65fn get_co(state: &mut LuaState) -> Result<GcRef<lua_types::value::LuaThread>, LuaError> {
71 let co = state.to_thread(1);
72 if co.is_none() {
73 let got = state.arg(1);
74 return Err(LuaError::type_arg_error(1, "thread", &got));
75 }
76 Ok(co.expect("checked above"))
77}
78
79fn aux_status(state: &mut LuaState, co: &GcRef<lua_types::value::LuaThread>) -> i32 {
91 let co_id = co.id;
92 let entry_rc = {
93 let g = state.global();
94 if co_id == g.current_thread_id {
95 return COS_RUN;
96 }
97 if co_id == g.main_thread_id {
98 return COS_NORM;
99 }
100 match g.threads.get(&co_id) {
101 Some(e) => e.state.clone(),
102 None => return COS_DEAD,
103 }
104 };
105 let co_state = match entry_rc.try_borrow() {
106 Ok(state) => state,
107 Err(_) => {
108 return COS_NORM;
113 }
114 };
115 let raw_status = co_state.status;
116 if raw_status == LuaStatus::Yield as u8 {
117 return COS_YIELD;
118 }
119 if raw_status != LuaStatus::Ok as u8 {
120 return COS_DEAD;
121 }
122 let has_frames = co_state.ci.as_usize() > 0;
123 if has_frames {
124 return COS_NORM;
125 }
126 let ci_func = co_state.call_info[0].func.0;
127 let top = co_state.top.0;
128 let lua_gettop = top as i64 - ci_func as i64 - 1;
129 if lua_gettop == 0 {
130 COS_DEAD
131 } else {
132 COS_YIELD
133 }
134}
135
136fn aux_resume(state: &mut LuaState, co: GcRef<lua_types::value::LuaThread>, narg: i32) -> i32 {
153 let co_id = co.id;
154 let entry_rc = {
155 let g = state.global();
156 match g.threads.get(&co_id) {
157 Some(e) => e.state.clone(),
158 None => {
159 drop(g);
160 push_lit_or_nil(state, b"cannot resume dead coroutine");
161 return -1;
162 }
163 }
164 };
165 let parent_thread_id = state.global().current_thread_id;
166 let top_before = state.get_top();
167 if top_before < narg {
168 push_lit_or_nil(state, b"not enough arguments to resume");
169 return -1;
170 }
171 let first_arg_idx = top_before - narg + 1;
172 let args: Vec<LuaValue> = (first_arg_idx..=top_before)
173 .map(|i| state.value_at(i))
174 .collect();
175 lua_vm::api::set_top(state, (top_before - narg) as i32).ok();
176
177 let parent_open_upval_slots: Vec<(u64, lua_vm::state::StackIdx)> = state
178 .openupval
179 .iter()
180 .filter_map(|uv| match &*uv.slot() {
181 lua_types::UpValState::Open { thread_id, idx } => {
182 Some((*thread_id as u64, *idx))
183 }
184 lua_types::UpValState::Closed(_) => None,
185 })
186 .collect();
187 {
188 let mut g = state.global_mut();
189 for (tid, idx) in &parent_open_upval_slots {
190 let val = state.get_at(*idx);
191 g.cross_thread_upvals.insert((*tid, *idx), val);
192 }
193 }
194
195 push_parent_gc_snapshot(state);
196
197 let (status, results_or_err): (LuaStatus, Vec<LuaValue>) = {
198 let mut co_state = match entry_rc.try_borrow_mut() {
199 Ok(b) => b,
200 Err(_) => {
201 pop_parent_gc_snapshot(state);
202 let mut g = state.global_mut();
203 for (tid, idx) in &parent_open_upval_slots {
204 g.cross_thread_upvals.remove(&(*tid, *idx));
205 }
206 drop(g);
207 push_lit_or_nil(state, b"cannot resume non-suspended coroutine");
208 return -1;
209 }
210 };
211 if co_state.check_stack(narg + 1).is_err() {
212 drop(co_state);
213 pop_parent_gc_snapshot(state);
214 let mut g = state.global_mut();
215 for (tid, idx) in &parent_open_upval_slots {
216 g.cross_thread_upvals.remove(&(*tid, *idx));
217 }
218 drop(g);
219 push_lit_or_nil(state, b"too many arguments to resume");
220 return -1;
221 }
222 for v in args {
223 co_state.push(v);
224 }
225 co_state.global_mut().current_thread_id = co_id;
226 let mut nres: i32 = 0;
227 let status = lua_vm::do_::lua_resume(&mut *co_state, Some(state), narg, &mut nres);
228 co_state.global_mut().current_thread_id = parent_thread_id;
229 let co_top = co_state.top_idx().0 as i32;
230 let ci_func = co_state.current_call_info().func.0 as i32;
231 let count = if status == LuaStatus::Ok || status == LuaStatus::Yield {
232 nres
233 } else {
234 1
235 };
236 let start = co_top - count;
237 let vals: Vec<LuaValue> = (start..co_top)
238 .map(|i| co_state.get_at(lua_vm::state::StackIdx(i as u32)))
239 .collect();
240 let new_co_top = if status == LuaStatus::Ok || status == LuaStatus::Yield {
241 (co_top - count).max(ci_func + 1)
242 } else {
243 co_top - count
244 };
245 co_state.set_top(lua_vm::state::StackIdx(new_co_top.max(0) as u32));
246 (status, vals)
247 };
248
249 pop_parent_gc_snapshot(state);
251
252 {
253 let mut g = state.global_mut();
254 let mut flush: Vec<(lua_vm::state::StackIdx, LuaValue)> = Vec::new();
255 for (tid, idx) in &parent_open_upval_slots {
256 if let Some(v) = g.cross_thread_upvals.remove(&(*tid, *idx)) {
257 flush.push((*idx, v));
258 }
259 }
260 drop(g);
261 for (idx, v) in flush {
262 state.set_at(idx, v);
263 }
264 }
265
266 match status {
267 LuaStatus::Ok | LuaStatus::Yield => {
268 if state.check_stack(results_or_err.len() as i32 + 1).is_err() {
269 push_lit_or_nil(state, b"too many results to resume");
270 return -1;
271 }
272 let n = results_or_err.len();
273 for v in results_or_err {
274 state.push(v);
275 }
276 n as i32
277 }
278 _ => {
279 for v in results_or_err {
280 state.push(v);
281 }
282 -1
283 }
284 }
285}
286
287fn push_parent_gc_snapshot(state: &mut LuaState) {
288 let top = state.top_idx();
289 let stack_snapshot: Vec<LuaValue> = (0..top.0)
290 .map(|i| state.get_at(lua_vm::state::StackIdx(i)))
291 .collect();
292 let open_upval_snapshot = state.openupval.clone();
293 let mut g = state.global_mut();
294 g.suspended_parent_stacks.push(stack_snapshot);
295 g.suspended_parent_open_upvals.push(open_upval_snapshot);
296}
297
298fn pop_parent_gc_snapshot(state: &mut LuaState) {
299 let mut g = state.global_mut();
300 g.suspended_parent_open_upvals.pop();
301 g.suspended_parent_stacks.pop();
302}
303
304fn push_lit_or_nil(state: &mut LuaState, bytes: &[u8]) {
306 match state.intern_str(bytes) {
307 Ok(s) => state.push(LuaValue::Str(s)),
308 Err(_) => state.push(LuaValue::Nil),
309 }
310}
311
312pub fn co_resume(state: &mut LuaState) -> Result<usize, LuaError> {
320 let co = get_co(state)?;
321 let narg = state.get_top() - 1;
324 let r = aux_resume(state, co, narg);
325 if r < 0 {
326 state.push(LuaValue::Bool(false));
327 state.insert(-2)?;
328 Ok(2)
329 } else {
330 state.push(LuaValue::Bool(true));
331 state.insert(-(r + 1))?;
332 Ok((r + 1) as usize)
333 }
334}
335
336fn aux_wrap(state: &mut LuaState) -> Result<usize, LuaError> {
344 let up = state.value_at(upvalue_index(1));
345 let co = match up {
346 LuaValue::Thread(t) => t,
347 _ => {
348 return Err(LuaError::runtime(format_args!(
349 "coroutine.wrap: upvalue is not a thread"
350 )))
351 }
352 };
353 let narg = state.get_top();
354 let r = aux_resume(state, co.clone(), narg);
355 if r < 0 {
356 let top = state.get_top();
357 let mut err_val = state.value_at(top);
358 if aux_status(state, &co) == COS_DEAD {
359 let old_err = state.pop();
360 let nclose = close_suspended_or_dead(state, co)?;
361 err_val = if nclose >= 2 {
362 let top = state.get_top();
363 state.value_at(top)
364 } else {
365 old_err
366 };
367 state.pop_n(nclose);
368 }
369 Err(LuaError::from_value(err_val))
370 } else {
371 Ok(r as usize)
372 }
373}
374
375pub fn co_create(state: &mut LuaState) -> Result<usize, LuaError> {
388 state.check_arg_type(1, LuaType::Function)?;
389 let body = state.value_at(1);
390 let _nl = state.new_thread(Some(body))?;
391 Ok(1)
392}
393
394pub fn co_wrap(state: &mut LuaState) -> Result<usize, LuaError> {
402 co_create(state)?;
403 state.push_cclosure(aux_wrap, 1)?;
404 Ok(1)
405}
406
407pub fn co_yield(state: &mut LuaState) -> Result<usize, LuaError> {
414 let n = state.get_top();
415 let r = lua_vm::do_::lua_yieldk(state, n, 0, None)?;
416 Ok(r as usize)
417}
418
419pub fn co_status(state: &mut LuaState) -> Result<usize, LuaError> {
424 let co = get_co(state)?;
425 let idx = aux_status(state, &co) as usize;
426 let name: &[u8] = STAT_NAMES[idx];
427 let interned = state.intern_str(name)?;
428 state.push(LuaValue::Str(interned));
429 Ok(1)
430}
431
432pub fn co_isyieldable(state: &mut LuaState) -> Result<usize, LuaError> {
436 let is_yieldable = if matches!(state.type_at(1), LuaType::None) {
437 state.is_yieldable()
438 } else {
439 let co = get_co(state)?;
440 let co_id = co.id;
441 let (is_main, is_current) = {
442 let g = state.global();
443 (co_id == g.main_thread_id, co_id == g.current_thread_id)
444 };
445 if is_main {
446 false
447 } else if is_current {
448 state.is_yieldable()
449 } else {
450 let entry_rc = {
451 let g = state.global();
452 g.threads
453 .get(&co_id)
454 .expect("thread value carries an id that must resolve in GlobalState::threads")
455 .state
456 .clone()
457 };
458 let target_is_yieldable = match entry_rc.try_borrow() {
459 Ok(b) => b.is_yieldable(),
460 Err(_) => false,
461 };
462 target_is_yieldable
463 }
464 };
465 state.push(LuaValue::Bool(is_yieldable));
466 Ok(1)
467}
468
469pub fn co_running(state: &mut LuaState) -> Result<usize, LuaError> {
474 let is_main = state.push_thread()?;
477 state.push(LuaValue::Bool(is_main));
478 Ok(2)
479}
480
481pub fn co_close(state: &mut LuaState) -> Result<usize, LuaError> {
489 lua_vm::state::inc_c_stack(state)?;
490 let result = (|| {
491 let co = get_co(state)?;
492 let status = aux_status(state, &co);
493 match status {
494 COS_DEAD | COS_YIELD => close_suspended_or_dead(state, co),
495 _ => {
496 let name = if status == COS_RUN { "running" } else { "normal" };
497 Err(LuaError::runtime(format_args!(
498 "cannot close a {} coroutine",
499 name
500 )))
501 }
502 }
503 })();
504 state.n_ccalls -= 1;
505 result
506}
507
508fn close_suspended_or_dead(
510 state: &mut LuaState,
511 co: GcRef<lua_types::value::LuaThread>,
512) -> Result<usize, LuaError> {
513 let co_id = co.id;
514 let entry_rc_opt = {
515 let g = state.global();
516 g.threads.get(&co_id).map(|e| e.state.clone())
517 };
518 let entry_rc = match entry_rc_opt {
519 Some(rc) => rc,
520 None => {
521 state.push(LuaValue::Bool(true));
522 return Ok(1);
523 }
524 };
525 let parent_thread_id = state.global().current_thread_id;
526 let caller_c_calls = state.c_calls();
527
528 let parent_open_upval_slots: Vec<(u64, lua_vm::state::StackIdx)> = state
529 .openupval
530 .iter()
531 .filter_map(|uv| match &*uv.slot() {
532 lua_types::UpValState::Open { thread_id, idx } => {
533 Some((*thread_id as u64, *idx))
534 }
535 lua_types::UpValState::Closed(_) => None,
536 })
537 .collect();
538 {
539 let mut g = state.global_mut();
540 for (tid, idx) in &parent_open_upval_slots {
541 let val = state.get_at(*idx);
542 g.cross_thread_upvals.insert((*tid, *idx), val);
543 }
544 }
545
546 push_parent_gc_snapshot(state);
547
548 let (status, err_value): (i32, Option<LuaValue>) = {
549 let mut co_state = entry_rc.borrow_mut();
550 co_state.global_mut().current_thread_id = co_id;
551 co_state.n_ccalls = caller_c_calls;
552 let in_status = co_state.status as i32;
553 let s = lua_vm::state::reset_thread(&mut *co_state, in_status);
554 co_state.global_mut().current_thread_id = parent_thread_id;
555 if s == LuaStatus::Ok as i32 {
556 (s, None)
557 } else {
558 let top = co_state.top_idx().0;
559 if top > 0 {
560 let err = co_state.get_at(lua_vm::state::StackIdx(top - 1));
561 co_state.set_top(lua_vm::state::StackIdx(top - 1));
562 (s, Some(err))
563 } else {
564 (s, Some(LuaValue::Nil))
565 }
566 }
567 };
568
569 pop_parent_gc_snapshot(state);
570
571 {
572 let mut g = state.global_mut();
573 let mut flush: Vec<(lua_vm::state::StackIdx, LuaValue)> = Vec::new();
574 for (tid, idx) in &parent_open_upval_slots {
575 if let Some(v) = g.cross_thread_upvals.remove(&(*tid, *idx)) {
576 flush.push((*idx, v));
577 }
578 }
579 drop(g);
580 for (idx, v) in flush {
581 state.set_at(idx, v);
582 }
583 }
584
585 if status == LuaStatus::Ok as i32 {
586 state.push(LuaValue::Bool(true));
587 Ok(1)
588 } else {
589 state.push(LuaValue::Bool(false));
590 if let Some(v) = err_value {
591 state.push(v);
592 } else {
593 state.push(LuaValue::Nil);
594 }
595 Ok(2)
596 }
597}
598
599pub fn open_coroutine(state: &mut LuaState) -> Result<usize, LuaError> {
605 state.new_lib(CO_FUNCS)?;
608 Ok(1)
609}
610
611