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
#[macro_export]
macro_rules! call_function {
    (fn($($argument_type:ty),* $(,)?) -> $result_type:ty, $function:expr) => {
        call_function!(fn($($argument_type),*) -> $result_type, $function,)
    };
    (fn($($argument_type:ty),* $(,)?) -> $result_type:ty, $function:expr, $($argument:expr),* $(,)?) => {
        async {
            use core::{future::poll_fn, task::Poll};
            use $crate::{cps, future::__private::INITIAL_STACK_CAPACITY};

            type AsyncStack = cps::AsyncStack<$result_type>;

            type Trampoline = cps::Trampoline<$result_type, $result_type>;

            extern "C" fn resolve(stack: &mut AsyncStack, value: $result_type) {
                stack.resolve(value);
            }

            // Move arguments into an initializer function.
            let mut initialize = Some(|stack: &mut AsyncStack| {
                let function = $function;

                unsafe { function(stack, resolve, $($argument),*) };
            });

            let mut trampoline: Option<Trampoline> = None;
            let mut stack = AsyncStack::new(INITIAL_STACK_CAPACITY);

            poll_fn(move |context| {
                if let Some(initialize) = initialize.take() {
                    stack.run_with_context(context, initialize);
                } else if let Some((step, continue_)) = trampoline.take() {
                    stack.run_with_context(context, |stack| step(stack, continue_));
                } else {
                    unreachable!("suspension must return trampoline functions")
                }

                if let Some(value) = stack.resolved_value() {
                    value.into()
                } else {
                    trampoline = Some(stack.resume().unwrap());
                    Poll::Pending
                }
            })
            .await
        }
    };
}

#[cfg(test)]
mod tests {
    use crate::{
        cps::{AsyncStack, ContinuationFunction},
        ByteString, Number,
    };
    use core::future::ready;

    unsafe extern "C" fn get_number(
        stack: &mut AsyncStack<Number>,
        continue_: ContinuationFunction<Number, Number>,
    ) {
        continue_(stack, 42.0.into())
    }

    #[tokio::test]
    async fn call_with_no_argument() {
        assert_eq!(
            call_function!(fn() -> Number, get_number,).await,
            42.0.into()
        );
    }

    unsafe extern "C" fn pass_through_number(
        stack: &mut AsyncStack<Number>,
        continue_: ContinuationFunction<Number, Number>,
        x: Number,
    ) {
        continue_(stack, x)
    }

    #[tokio::test]
    async fn call_one_argument_closure() {
        let value = 42.0;

        assert_eq!(
            call_function!(fn(Number) -> Number, pass_through_number, value.into()).await,
            value.into()
        );
    }

    unsafe extern "C" fn add_numbers(
        stack: &mut AsyncStack<Number>,
        continue_: ContinuationFunction<Number, Number>,
        x: Number,
        y: Number,
    ) {
        continue_(stack, (f64::from(x) + f64::from(y)).into())
    }

    #[tokio::test]
    async fn call_two_argument_closure() {
        assert_eq!(
            call_function!(
                fn(Number, Number) -> Number,
                add_numbers,
                40.0.into(),
                2.0.into(),
            )
            .await,
            42.0.into()
        );
    }

    unsafe extern "C" fn get_number_with_suspension(
        stack: &mut AsyncStack<Number>,
        continue_: ContinuationFunction<Number, Number>,
    ) {
        fn step(stack: &mut AsyncStack<Number>, continue_: ContinuationFunction<Number, Number>) {
            continue_(stack, 42.0.into())
        }

        stack.suspend(step, continue_, ready(())).unwrap();

        // Wake immediately as we are waiting for nothing!
        stack.context().unwrap().waker().wake_by_ref();
    }

    #[tokio::test]
    async fn call_closure_with_suspension() {
        assert_eq!(
            call_function!(fn() -> Number, get_number_with_suspension,).await,
            42.0.into()
        );
    }

    unsafe extern "C" fn closure_entry_function_with_string(
        stack: &mut AsyncStack<ByteString>,
        continue_: ContinuationFunction<ByteString, ByteString>,
        x: ByteString,
    ) {
        continue_(stack, x)
    }

    #[tokio::test]
    async fn move_argument() {
        let value = "foo";

        assert_eq!(
            call_function!(
                fn(ByteString) -> ByteString,
                closure_entry_function_with_string,
                value.into(),
            )
            .await,
            value.into()
        );
    }

    #[tokio::test]
    async fn move_argument_in_closure() {
        let value = ByteString::from("foo");

        assert_eq!(
            call_function!(
                fn(ByteString) -> ByteString,
                closure_entry_function_with_string,
                value.clone(),
            )
            .await,
            value
        );
    }
}