Debian Codegraph @

gcc/testsuite/g++.dg/coroutines/torture/extern-c-coroutine.C

raw
1 // { dg-skip-if "requires hosted libstdc++ for cstdio" { ! hostedlib } }
2
3 #include <coroutine>
4 #include <cstdio>
5
6 #ifndef OUTPUT
7 # define PRINT(X)
8 # define PRINTF(X,...)
9 #else
10 # define PRINT(X) puts(X)
11 # define PRINTF printf
12 #endif
13
14 struct future {
15 struct promise_type;
16 using handle_type = std::coroutine_handle<future::promise_type>;
17 handle_type handle;
18 future () : handle(0) {}
19 future (handle_type _handle)
20 : handle(_handle) {
21 PRINT("Created future object from handle");
22 }
23 future (const future &) = delete; // no copying
24 future (future &&s) : handle(s.handle) {
25 s.handle = nullptr;
26 PRINT("future mv ctor ");
27 }
28 future &operator = (future &&s) {
29 handle = s.handle;
30 s.handle = nullptr;
31 PRINT("future op= ");
32 return *this;
33 }
34 ~future() {
35 PRINT("Destroyed future");
36 if ( handle )
37 handle.destroy();
38 }
39
40 struct promise_type {
41 void return_value (int v) {
42 PRINTF ("return_value (%d)\n", v);
43 vv = v;
44 }
45
46 std::suspend_always initial_suspend() noexcept { return {}; }
47 std::suspend_always final_suspend() noexcept { return {}; }
48 void unhandled_exception() {}
49 auto get_return_object() {return handle_type::from_promise (*this);}
50
51 int get_value () { return vv; }
52 private:
53 int vv;
54 };
55 bool await_ready() { return false; }
56 void await_suspend(std::coroutine_handle<>) {}
57 void await_resume() {}
58 };
59
60 extern "C" future
61 test () {
62 co_return 22;
63 }
64
65 extern "C" future
66 f () noexcept
67 {
68 PRINT ("future: about to return");
69 co_return 42;
70 }
71
72 int main ()
73 {
74 PRINT ("main: create future");
75 future x = f ();
76 PRINT ("main: got future - resuming");
77 if (x.handle.done())
78 __builtin_abort ();
79 x.handle.resume();
80 PRINT ("main: after resume");
81 int y = x.handle.promise().get_value();
82 if ( y != 42 )
83 __builtin_abort ();
84 if (!x.handle.done())
85 {
86 PRINT ("main: apparently not done...");
87 __builtin_abort ();
88 }
89 PRINT ("main: returning");
90 return 0;
91 }