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
pub use super::pend_once::PendOnce;
pub use decurse_macro::decurse_sound;
use pfn::PFnOnce;
use pinned_vec::PinnedVec;
use scoped_tls::scoped_thread_local;
use std::{any::Any, cell::RefCell, future::Future, task::Poll};

pub struct Context<F: Future> {
	next: RefCell<Option<F>>,
	result: RefCell<Option<F::Output>>,
}

impl<F: Future + 'static> Context<F> {
	pub fn new() -> Self {
		Self {
			next: RefCell::new(None),
			result: RefCell::new(None),
		}
	}
	pub fn set_next(self_ptr: &Box<dyn Any>, fut: F) {
		let this: &Self = self_ptr.downcast_ref().unwrap();
		*this.next.borrow_mut() = Some(fut);
	}
	pub fn get_result(self_ptr: &Box<dyn Any>) -> F::Output {
		let this: &Self = self_ptr.downcast_ref().unwrap();
		this.result.borrow_mut().take().unwrap()
	}
}

scoped_thread_local! (static CONTEXT: Box<dyn Any>);

pub fn set_next<F: Future + 'static>(fut: F) {
	CONTEXT.with(|c| Context::set_next(c, fut))
}

pub fn get_result<A, R, F>(_phantom: R) -> F::Output
where
	R: PFnOnce<A, PFnOutput = F>,
	F: Future + 'static,
{
	CONTEXT.with(|c| Context::<F>::get_result(c))
}

pub fn execute<F>(fut: F) -> F::Output
where
	F: Future + 'static,
{
	let dummy_waker = waker_fn::waker_fn(|| {});
	let mut dummy_async_cx: std::task::Context = std::task::Context::from_waker(&dummy_waker);
	let ctx: Context<F> = Context::new();
	let any_ctx: Box<dyn Any> = Box::new(ctx);
	let ctx: &Context<F> = any_ctx.downcast_ref().unwrap();

	let output = CONTEXT.set(&any_ctx, || {
		let mut heap_stack: PinnedVec<F> = PinnedVec::new();
		heap_stack.push(fut);
		loop {
			let len = heap_stack.len();
			// UNWRAP Safety: The only way len could go down is through the pop in the Poll::Ready case,
			// in which we return if len is 1. So len never gets to 0.
			let fut = heap_stack.get_mut(len - 1).unwrap();
			let polled = fut.poll(&mut dummy_async_cx);
			match polled {
				Poll::Ready(r) => {
					if len == 1 {
						break r;
					} else {
						let mut bm = ctx.result.borrow_mut();
						*bm = Some(r);
						heap_stack.pop();
					}
				}
				Poll::Pending => {
					// UNWRAP Safety: The decurse macro only yields when recursing,
					// in which case `next` would be filled before Pending is returned (see ctx.set_next).
					heap_stack.push(ctx.next.borrow_mut().take().unwrap());
				}
			}
		}
	});
	output
}

#[macro_export]
macro_rules! for_macro_only_recurse_sound {
    ($func:path, ($($args:expr),*)) => {
        ({
            $crate::for_macro_only::sound::set_next($func ($($args),*));
            $crate::for_macro_only::sound::PendOnce::new().await;
            $crate::for_macro_only::sound::get_result($func)
        })
    };
}

#[cfg(test)]
mod tests {
	use super::*;
	#[test]
	fn stack_factorial() {
		fn factorial(x: u32) -> u32 {
			if x == 0 {
				1
			} else {
				x * factorial(x - 1)
			}
		}
		assert_eq!(factorial(6), 720);
	}
	#[test]
	fn stack_fibonacci() {
		fn fibonacci(x: u32) -> u32 {
			if x == 0 || x == 1 {
				1
			} else {
				fibonacci(x - 1) + fibonacci(x - 2)
			}
		}
		assert_eq!(fibonacci(10), 89);
	}

	#[test]
	fn factorial() {
		async fn factorial(x: u32) -> u32 {
			if x == 0 {
				1
			} else {
				for_macro_only_recurse_sound!(factorial, (x - 1)) * x
			}
		}
		assert_eq!(execute(factorial(6)), 720);
	}

	#[test]
	fn fibonacci() {
		async fn fibonacci(x: u32) -> u32 {
			if x == 0 || x == 1 {
				1
			} else {
				for_macro_only_recurse_sound!(fibonacci, (x - 1))
					+ for_macro_only_recurse_sound!(fibonacci, (x - 2))
			}
		}
		assert_eq!(execute(fibonacci(10)), 89);
	}

	// This test cause stack overflow.
	// #[test]
	// fn stack_triangular() {
	//     fn stack_triangular(x: u64) -> u64 {
	//         if x == 0 {
	//             0
	//         } else {
	//             stack_triangular(x - 1) + x
	//         }
	//     }
	//     assert_eq!(20000100000, stack_triangular(200000));
	// }

	#[test]
	fn triangular() {
		fn triangular(x: u64) -> u64 {
			async fn decurse_triangular(x: u64) -> u64 {
				if x == 0 {
					0
				} else {
					for_macro_only_recurse_sound!(decurse_triangular, (x - 1)) + x
				}
			}
			execute(decurse_triangular(x))
		}
		assert_eq!(20000100000, triangular(200000));
	}
}