about summary refs log tree commit diff stats
path: root/003trace.cc
blob: 92a6d069fbbc02de3e701096291d1e3690df582f (plain) (blame)
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//: The goal of layers is to make programs more easy to understand and more
//: malleable, easy to rewrite in radical ways without accidentally breaking
//: some corner case. Tests further both goals. They help understandability by
//: letting one make small changes and get feedback. What if I wrote this line
//: like so? What if I removed this function call, is it really necessary?
//: Just try it, see if the tests pass. Want to explore rewriting this bit in
//: this way? Tests put many refactorings on a firmer footing.
//:
//: But the usual way we write tests seems incomplete. Refactorings tend to
//: work in the small, but don't help with changes to function boundaries. If
//: you want to extract a new function you have to manually test-drive it to
//: create tests for it. If you want to inline a function its tests are no
//: longer valid. In both cases you end up having to reorganize code as well as
//: tests, an error-prone activity.
//:
//: In response, this layer introduces the notion of *domain-driven* testing.
//: We focus on the domain of inputs the whole program needs to handle rather
//: than the correctness of individual functions. All tests invoke the program
//: in a single way: by calling run() with some input. As the program operates
//: on the input, it traces out a list of _facts_ deduced about the domain:
//:   trace("label") << "fact 1: " << val;
//:
//: Tests can now check these facts:
//:   :(scenario foo)
//:   34  # call run() with this input
//:   +label: fact 1: 34  # 'run' should have deduced this fact
//:   -label: fact 1: 35  # the trace should not contain such a fact
//:
//: Since we never call anything but the run() function directly, we never have
//: to rewrite the tests when we reorganize the internals of the program. We
//: just have to make sure our rewrite deduces the same facts about the domain,
//: and that's something we're going to have to do anyway.
//:
//: To avoid the combinatorial explosion of integration tests, each layer
//: mainly logs facts to the trace with a common *label*. All tests in a layer
//: tend to check facts with this label. Validating the facts logged with a
//: specific label is like calling functions of that layer directly.
//:
//: To build robust tests, trace facts about your domain rather than details of
//: how you computed them.
//:
//: More details: http://akkartik.name/blog/tracing-tests
//:
//: ---
//:
//: Between layers and domain-driven testing, programming starts to look like a
//: fundamentally different activity. Instead of a) superficial, b) local rules
//: on c) code [like say http://blog.bbv.ch/2013/06/05/clean-code-cheat-sheet],
//: we allow programmers to engage with the a) deep, b) global structure of the
//: c) domain. If you can systematically track discontinuities in the domain,
//: you don't care if the code used gotos as long as it passed the tests. If
//: tests become more robust to run it becomes easier to try out radically
//: different implementations for the same program. If code is super-easy to
//: rewrite, it becomes less important what indentation style it uses, or that
//: the objects are appropriately encapsulated, or that the functions are
//: referentially transparent.
//:
//: Instead of plumbing, programming becomes building and gradually refining a
//: map of the environment the program must operate under. Whether a program is
//: 'correct' at a given point in time is a red herring; what matters is
//: avoiding regression by monotonically nailing down the more 'eventful' parts
//: of the terrain. It helps readers new and old, and rewards curiosity, to
//: organize large programs in self-similar hierarchies of example scenarios
//: colocated with the code that makes them work.
//:
//:   "Programming properly should be regarded as an activity by which
//:   programmers form a mental model, rather than as production of a program."
//:   -- Peter Naur (http://alistair.cockburn.us/ASD+book+extract%3A+%22Naur,+Ehn,+Musashi%22)

:(before "End Types")
struct trace_line {
  int depth;  // optional field just to help browse traces later
  string label;
  string contents;
  trace_line(string l, string c) :depth(0), label(l), contents(c) {}
  trace_line(int d, string l, string c) :depth(d), label(l), contents(c) {}
};

:(before "End Globals")
bool Hide_errors = false;
bool Dump_trace = false;
string Dump_label = "";
:(before "End Reset")
Hide_errors = false;
Dump_trace = false;
Dump_label = "";

:(before "End Types")
// Pre-define some global constants that trace_stream needs to know about.
// Since they're in the Types section, they'll be included in any cleaved
// compilation units. So no extern linkage.
const int Max_depth = 9999;
const int Error_depth = 0;  // definitely always print errors
const int App_depth = 2;  // temporarily where all Mu code will trace to

struct trace_stream {
  vector<trace_line> past_lines;
  // accumulator for current line
  ostringstream* curr_stream;
  string curr_label;
  int curr_depth;
  int callstack_depth;
  int collect_depth;
  ofstream null_stream;  // never opens a file, so writes silently fail
  trace_stream() :curr_stream(NULL), curr_depth(Max_depth), callstack_depth(0), collect_depth(Max_depth) {}
  ~trace_stream() { if (curr_stream) delete curr_stream; }

  ostream& stream(string label) {
    return stream(Max_depth, label);
  }

  ostream& stream(int depth, string label) {
    if (depth > collect_depth) return null_stream;
    curr_stream = new ostringstream;
    curr_label = label;
    curr_depth = depth;
    return *curr_stream;
  }

  void dump() {
    ofstream fout("last_run");
    fout << readable_contents("");
    fout.close();
  }

  // be sure to call this before messing with curr_stream or curr_label
  void newline();
  // useful for debugging
  string readable_contents(string label);  // empty label = show everything
};

:(code)
void trace_stream::newline() {
  if (!curr_stream) return;
  string curr_contents = curr_stream->str();
  if (!curr_contents.empty()) {
    past_lines.push_back(trace_line(curr_depth, trim(curr_label), curr_contents));  // preserve indent in contents
    if ((!Hide_errors && curr_label == "error")
        || Dump_trace
        || (!Dump_label.empty() && curr_label == Dump_label))
      cerr << curr_label << ": " << curr_contents << '\n';
  }
  delete curr_stream;
  curr_stream = NULL;
  curr_label.clear();
  curr_depth = Max_depth;
}

string trace_stream::readable_contents(string label) {
  ostringstream output;
  label = trim(label);
  for (vector<trace_line>::iterator p = past_lines.begin();  p != past_lines.end();  ++p)
    if (label.empty() || label == p->label) {
      output << std::setw(4) << p->depth << ' ' << p->label << ": " << p->contents << '\n';
    }
  return output.str();
}

:(before "End Globals")
trace_stream* Trace_stream = NULL;
int Trace_errors = 0;  // used only when Trace_stream is NULL

:(before "End Includes")
#define CLEAR_TRACE  delete Trace_stream, Trace_stream = new trace_stream;

// Top-level helper. IMPORTANT: can't nest
#define trace(...)  !Trace_stream ? cerr /*print nothing*/ : Trace_stream->stream(__VA_ARGS__)

// Just for debugging; 'git log' should never show any calls to 'dbg'.
#define dbg trace(0, "a")
#define DUMP(label)  if (Trace_stream) cerr << Trace_stream->readable_contents(label);

// Errors are a special layer.
#define raise  (!Trace_stream ? (scroll_to_bottom_and_close_console(),++Trace_errors,cerr) /*do print*/ : Trace_stream->stream(Error_depth, "error"))
// If we aren't yet sure how to deal with some corner case, use assert_for_now
// to indicate that it isn't an inviolable invariant.
#define assert_for_now assert

//: Automatically close the console in some situations.
:(before "End One-time Setup")
atexit(scroll_to_bottom_and_close_console);
:(code)
void scroll_to_bottom_and_close_console() {
  if (!tb_is_active()) return;
  // leave the screen in a relatively clean state
  tb_set_cursor(tb_width()-1, tb_height()-1);
  cout << "\r\n";
  tb_shutdown();
}

// Inside tests, fail any tests that displayed (unexpected) errors.
// Expected errors in tests should always be hidden and silently checked for.
:(before "End Test Teardown")
if (Passed && !Hide_errors && trace_contains_errors()) {
  Passed = false;
}
:(code)
bool trace_contains_errors() {
  return Trace_errors > 0 || trace_count("error") > 0;
}

:(before "End Types")
struct end {};
:(code)
ostream& operator<<(ostream& os, vestigial end) {
  if (Trace_stream) Trace_stream->newline();
  return os;
}

:(before "End Globals")
bool Save_trace = false;

// Trace_stream is a resource, lease_tracer uses RAII to manage it.
:(before "End Types")
struct lease_tracer {
  lease_tracer();
  ~lease_tracer();
};
:(code)
lease_tracer::lease_tracer() { Trace_stream = new trace_stream; }
lease_tracer::~lease_tracer() {
  if (!Trace_stream) return;  // in case tests close Trace_stream
  if (Save_trace) Trace_stream->dump();
  delete Trace_stream, Trace_stream = NULL;
}
:(before "End Includes")
#define START_TRACING_UNTIL_END_OF_SCOPE  lease_tracer leased_tracer;
:(before "End Test Setup")
START_TRACING_UNTIL_END_OF_SCOPE

:(before "End Includes")
#define CHECK_TRACE_CONTENTS(...)  check_trace_contents(__FUNCTION__, __FILE__, __LINE__, __VA_ARGS__)

#define CHECK_TRACE_CONTAINS_ERRORS()  CHECK(trace_contains_errors())
#define CHECK_TRACE_DOESNT_CONTAIN_ERRORS() \
  if (Passed && trace_contains_errors()) { \
    cerr << "\nF - " << __FUNCTION__ << "(" << __FILE__ << ":" << __LINE__ << "): unexpected errors\n"; \
    DUMP("error"); \
    Passed = false; \
    return; \
  }

#define CHECK_TRACE_COUNT(label, count) \
  if (Passed && trace_count(label) != (count)) { \
    cerr << "\nF - " << __FUNCTION__ << "(" << __FILE__ << ":" << __LINE__ << "): trace_count of " << label << " should be " << count << '\n'; \
    cerr << "  got " << trace_count(label) << '\n';  /* multiple eval */ \
    DUMP(label); \
    Passed = false; \
    return;  /* Currently we stop at the very first failure. */ \
  }

#define CHECK_TRACE_DOESNT_CONTAIN(...)  CHECK(trace_doesnt_contain(__VA_ARGS__))

:(code)
bool check_trace_contents(string FUNCTION, string FILE, int LINE, string expected) {
  if (!Passed) return false;
  if (!Trace_stream) return false;
  vector<string> expected_lines = split(expected, "");
  int curr_expected_line = 0;
  while (curr_expected_line < SIZE(expected_lines) && expected_lines.at(curr_expected_line).empty())
    ++curr_expected_line;
  if (curr_expected_line == SIZE(expected_lines)) return true;
  string label, contents;
  split_label_contents(expected_lines.at(curr_expected_line), &label, &contents);
  for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
    if (label != p->label) continue;
    if (contents != trim(p->contents)) continue;
    ++curr_expected_line;
    while (curr_expected_line < SIZE(expected_lines) && expected_lines.at(curr_expected_line).empty())
      ++curr_expected_line;
    if (curr_expected_line == SIZE(expected_lines)) return true;
    split_label_contents(expected_lines.at(curr_expected_line), &label, &contents);
  }

  if (line_exists_anywhere(label, contents)) {
    cerr << "\nF - " << FUNCTION << "(" << FILE << ":" << LINE << "): line [" << label << ": " << contents << "] out of order in trace:\n";
    DUMP("");
  }
  else {
    cerr << "\nF - " << FUNCTION << "(" << FILE << ":" << LINE << "): missing [" << contents << "] in trace:\n";
    DUMP(label);
  }
  Passed = false;
  return false;
}

void split_label_contents(const string& s, string* label, string* contents) {
  static const string delim(": ");
  size_t pos = s.find(delim);
  if (pos == string::npos) {
    *label = "";
    *contents = trim(s);
  }
  else {
    *label = trim(s.substr(0, pos));
    *contents = trim(s.substr(pos+SIZE(delim)));
  }
}

bool line_exists_anywhere(const string& label, const string& contents) {
  for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
    if (label != p->label) continue;
    if (contents == trim(p->contents)) return true;
  }
  return false;
}

int trace_count(string label) {
  return trace_count(label, "");
}

int trace_count(string label, string line) {
  if (!Trace_stream) return 0;
  long result = 0;
  for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
    if (label == p->label) {
      if (line == "" || trim(line) == trim(p->contents))
        ++result;
    }
  }
  return result;
}

int trace_count_prefix(string label, string prefix) {
  if (!Trace_stream) return 0;
  long result = 0;
  for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
    if (label == p->label) {
      if (starts_with(trim(p->contents), trim(prefix)))
        ++result;
    }
  }
  return result;
}

bool trace_doesnt_contain(string label, string line) {
  return trace_count(label, line) == 0;
}

bool trace_doesnt_contain(string expected) {
  vector<string> tmp = split_first(expected, ": ");
  return trace_doesnt_contain(tmp.at(0), tmp.at(1));
}

vector<string> split(string s, string delim) {
  vector<string> result;
  size_t begin=0, end=s.find(delim);
  while (true) {
    if (end == string::npos) {
      result.push_back(string(s, begin, string::npos));
      break;
    }
    result.push_back(string(s, begin, end-begin));
    begin = end+SIZE(delim);
    end = s.find(delim, begin);
  }
  return result;
}

vector<string> split_first(string s, string delim) {
  vector<string> result;
  size_t end=s.find(delim);
  result.push_back(string(s, 0, end));
  if (end != string::npos)
    result.push_back(string(s, end+SIZE(delim), string::npos));
  return result;
}

string trim(const string& s) {
  string::const_iterator first = s.begin();
  while (first != s.end() && isspace(*first))
    ++first;
  if (first == s.end()) return "";

  string::const_iterator last = --s.end();
  while (last != s.begin() && isspace(*last))
    --last;
  ++last;
  return string(first, last);
}

:(before "End Includes")
#include <vector>
using std::vector;
#include <list>
using std::list;
#include <map>
using std::map;
#include <set>
using std::set;

#include <sstream>
using std::istringstream;
using std::ostringstream;

#include <fstream>
using std::ifstream;
using std::ofstream;

#include "termbox/termbox.h"

:(before "End Globals")
//: In future layers we'll use the depth field as follows:
//:
//: Errors will be depth 0.
//: Mu 'applications' will be able to use depths 1-100 as they like.
//: Primitive statements will occupy 101-9989
extern const int Initial_callstack_depth = 101;
extern const int Max_callstack_depth = 9989;
//: Finally, details of primitive Mu statements will occupy depth 9990-9999
//: (more on that later as well)
//:
//: This framework should help us hide some details at each level, mixing
//: static ideas like layers with the dynamic notion of call-stack depth.
the previous revision' href='/akkartik/mu/blame/062scheduler.cc?h=hlt&id=27ba0937a3747684f299bb7a8b3cdd0fbb689db3'>^
7a84094a ^
6d17ef49 ^
1ead3562 ^
7a84094a ^
6d17ef49 ^


1326a4ec ^

d9a7e6ab ^
7a84094a ^

d9a7e6ab ^


d9a7e6ab ^
1ead3562 ^
7a84094a ^
d9a7e6ab ^











1ead3562 ^
7a84094a ^

d9a7e6ab ^


82ceda30 ^
75a00270 ^


5f98a10c ^
75a00270 ^
1ead3562 ^
83d8299d ^
7a84094a ^

75a00270 ^
1ead3562 ^
75a00270 ^
7a84094a ^

75a00270 ^

7a84094a ^

75a00270 ^

5f98a10c ^
75a00270 ^


45ca3bb7 ^
00b808d9 ^

1ead3562 ^
83d8299d ^
00b808d9 ^

1ead3562 ^
7a84094a ^
00b808d9 ^


45ca3bb7 ^
6c96a437 ^
45ca3bb7 ^

19695cc7 ^
00b808d9 ^
00b808d9 ^

45ca3bb7 ^


b24eb476 ^
6c96a437 ^
45ca3bb7 ^





82ceda30 ^



1ead3562 ^
7a84094a ^

82ceda30 ^
7a84094a ^
82ceda30 ^
1ead3562 ^
7a84094a ^
82ceda30 ^







795f5244 ^
166e3c0d ^
82ceda30 ^
166e3c0d ^
8d72e565 ^
e4630643 ^

7afe09fb ^
9dcbec39 ^
e4630643 ^

166e3c0d ^



b24eb476 ^

6c96a437 ^
05d17773 ^

82ceda30 ^


cfb142b9 ^
827898fc ^
82ceda30 ^

9d670bb5 ^
45ca3bb7 ^

9d670bb5 ^
134dad7c ^

795f5244 ^
166e3c0d ^
134dad7c ^
166e3c0d ^
8d72e565 ^
e4630643 ^

7afe09fb ^
9dcbec39 ^
e4630643 ^

166e3c0d ^



b24eb476 ^
6c96a437 ^
134dad7c ^








a6cdf15c ^

795f5244 ^
166e3c0d ^



a6cdf15c ^

6c96a437 ^
00b808d9 ^
a6cdf15c ^


88e99894 ^




1ead3562 ^
7a84094a ^

b291d6f9 ^
7a84094a ^


88e99894 ^
1ead3562 ^
b291d6f9 ^

88e99894 ^








dd2e01e4 ^
88e99894 ^







6abdff27 ^



6abdff27 ^
6abdff27 ^



6abdff27 ^
6abdff27 ^


6c96a437 ^
6abdff27 ^





88e99894 ^
b24eb476 ^
88e99894 ^





795f5244 ^
166e3c0d ^
88e99894 ^
166e3c0d ^
8d72e565 ^
88e99894 ^

7afe09fb ^
9dcbec39 ^
88e99894 ^

7afe09fb ^
9dcbec39 ^
88e99894 ^

166e3c0d ^



b24eb476 ^
6c96a437 ^
88e99894 ^






94fed202 ^
d8c6265d ^
ccba6718 ^
d8c6265d ^
ccba6718 ^


d8c6265d ^






8d72e565 ^
d8c6265d ^











6c96a437 ^
d8c6265d ^
ccba6718 ^
d8c6265d ^






27d90d80 ^
9c184f02 ^
1ead3562 ^
7a84094a ^
94fed202 ^
7a84094a ^
94fed202 ^
7a84094a ^
94fed202 ^
1ead3562 ^
9c184f02 ^
7a84094a ^

94fed202 ^
9c184f02 ^


d8c6265d ^
9c184f02 ^
bd3d6c9e ^
d8c6265d ^
7a84094a ^
d8c6265d ^
7a84094a ^
d8c6265d ^
7a84094a ^
d8c6265d ^

bd3d6c9e ^
7a84094a ^



d8c6265d ^
27d90d80 ^

bd3d6c9e ^
9c184f02 ^





760f683f ^
9c184f02 ^

7a84094a ^
9c184f02 ^


760f683f ^
9c184f02 ^
760f683f ^
9c184f02 ^
7a84094a ^
9c184f02 ^

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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696

                                                                             
 
                     
        
                  

                      
                         
   
 
        
                 


             
 
                                         

                              














                                                                                                       

                                          




                          
                       





                                   
                       
                          
                              

                          
                 

                                         





                         
                                                              
                                
                           

                                              
                                                                
                          
                                  
                                     

                                         


                            
   
                    

 
                          
                                              
                                         
                   






                                                       
                                                 
                                                                                                                  
                                           
                                
                                       

             


   
                                



                                        
                       
                                     
                                                                               
                                          
                                                  



                      
                        
                                          
                        
                 
                       
 


                                                    
                                                 




                                                    
                                    
                       
                                        
                                                   
   
                    

 
                                                           
 
                                                                             
                                                             
                              
       
                       
                        



                                   
                  
 


                                                                
                                                         


                                   
                                             
              
                                        
                                                    
                                       
                     
                                 
                                                                                                                                      

          
                                              
                                                                                                                                                                      

          



                                                
                                                              
                                                    
                         
                                                                       
                                                                             
                                                                         
                              
                                                                 
                                            
   
                                  
                     
                                            

        
 

                                         
        

                 

             
                                          
             
                                          
 

                                          
        
                  

                 
 
        

                 

             
                                          
             
                                          
             
                                          
             
                                          
             
                                          
 
                                           
        
                     

                      
                         
   
 
        

                          


                             


                                                                      
                          


                    
                                                            

                     


                        
                            



                              
                         

                  
                      











                                                                                    


                                                                                                  
               

 
















                                                                                        
                                                 
                                                 


                                       
               
             
                                               
                                                                 
                       
                             



             
                                                                         
               
                               
                               
                               





                                                                                   
 
                                            
        
                           
 
        
                   


                             

                                                                
                                              

                                                                        


                                                             
                                                 
        
                 











                                                                                  
        

                 


             
 


                                                      
                     
                          
        
                  

                 
 
        
                     

                                     

                                        

                                                                   

                                              
                                                                               


                                       
                                                               

                                   
          
                  

                                                                              
        
                 


             
                                 
                                            

                                                                 
                                                      
                                

                                      


       
                                              
                                                                           





                                           



                                                              
        

                                                                          
                                                                                          
                                             
 
        
                  







                                                                 
                                                    
                                       
                     
                                    
                                                                                                                                                  

          
                                              
                                                                                                                                                                                                            

          



                                                

                                   
                                              

                                     


            
                     
                                   

        
 

                          
                                             

                                        
                                  
                                       
            
                                    
                                                                                                                                         

          
                                              
                                                                                                                                                                                                   

          



                                                
                                   
                                              








                                             

                                        
                                                      



                                       

                                                
                                              
                                                                                                                           


        




                                                             
        

                                    
                                                           


                            
 
        

                                            








                                                      
                                                                                        







                                                  



                                                       
 



                                                                                   
 


                                
                                              





                                              
                              
          





                                             
                                              
                                       
                  
                                    
                                                                                                                                               

          
                                              
                                                                                                                                                                                                         

          
                                              
                                                                                                                                                                                                      

          



                                                
                                   
                                              






                                                      
 
                              
                     
                                   


                                                                                             






                                                                      
                                                                                                                                                           











                                                                                                                                                                                                                     
                                              
                                   
                                                






                                   
 
                                  
        
                                     
   
                      
   
                                         
 
        
                                

                  
 


                                                                   
 
                                                                       
                          
        
                                     
   
                      
   
                                         

        
                                



                  
 

                                                                   
                              





                                                                
                                

                           
                         


        
                                
                                          
                                              
                      
                     

                             
//: Run a second routine concurrently using 'start-running', without any
//: guarantees on how the operations in each are interleaved with each other.

:(scenario scheduler)
def f1 [
  start-running f2
  # wait for f2 to run
  {
    jump-unless 1:num, -1
  }
]
def f2 [
  1:num <- copy 1
]
+schedule: f1
+schedule: f2

//: first, add a deadline to run(routine)
:(before "End Globals")
int Scheduling_interval = 500;
:(before "End routine Fields")
int instructions_run_this_scheduling_slice;
:(before "End routine Constructor")
instructions_run_this_scheduling_slice = 0;
:(before "Running One Instruction")
 ++Current_routine->instructions_run_this_scheduling_slice;
:(replace{} "bool should_continue_running(const routine* current_routine)")
bool should_continue_running(const routine* current_routine) {
  assert(current_routine == Current_routine);  // argument passed in just to make caller readable above
  return Current_routine->state == RUNNING
      && Current_routine->instructions_run_this_scheduling_slice < Scheduling_interval;
}
:(after "stop_running_current_routine:")
// Reset instructions_run_this_scheduling_slice
Current_routine->instructions_run_this_scheduling_slice = 0;

//: now the rest of the scheduler is clean

:(before "struct routine")
enum routine_state {
  RUNNING,
  COMPLETED,
  // End routine States
};
:(before "End routine Fields")
enum routine_state state;
:(before "End routine Constructor")
state = RUNNING;

:(before "End Globals")
vector<routine*> Routines;
int Current_routine_index = 0;
:(before "End Setup")
Scheduling_interval = 500;
Routines.clear();
:(replace{} "void run(recipe_ordinal r)")
void run(recipe_ordinal r) {
  run(new routine(r));
}

:(code)
void run(routine* rr) {
  Routines.push_back(rr);
  Current_routine_index = 0, Current_routine = Routines.at(0);
  while (!all_routines_done()) {
    skip_to_next_routine();
    assert(Current_routine);
    assert(Current_routine->state == RUNNING);
    trace(9990, "schedule") << current_routine_label() << end();
    run_current_routine();
    // Scheduler State Transitions
    if (Current_routine->completed())
      Current_routine->state = COMPLETED;
    // End Scheduler State Transitions

    // Scheduler Cleanup
    // End Scheduler Cleanup
  }
  // End Run Routine
}

bool all_routines_done() {
  for (int i = 0;  i < SIZE(Routines);  ++i) {
    if (Routines.at(i)->state == RUNNING)
      return false;
  }
  return true;
}

// skip Current_routine_index past non-RUNNING routines
void skip_to_next_routine() {
  assert(!Routines.empty());
  assert(Current_routine_index < SIZE(Routines));
  for (int i = (Current_routine_index+1)%SIZE(Routines);  i != Current_routine_index;  i = (i+1)%SIZE(Routines)) {
    if (Routines.at(i)->state == RUNNING) {
      Current_routine_index = i;
      Current_routine = Routines.at(i);
      return;
    }
  }
}

string current_routine_label() {
  return routine_label(Current_routine);
}

string routine_label(routine* r) {
  ostringstream result;
  const call_stack& calls = r->calls;
  for (call_stack::const_iterator p = calls.begin();  p != calls.end();  ++p) {
    if (p != calls.begin()) result << '/';
    result << get(Recipe, p->running_recipe).name;
  }
  return result.str();
}

:(before "End Teardown")
for (int i = 0;  i < SIZE(Routines);  ++i)
  delete Routines.at(i);
Routines.clear();
Current_routine = NULL;

//: special case for the very first routine
:(replace{} "void run_main(int argc, char* argv[])")
void run_main(int argc, char* argv[]) {
  recipe_ordinal r = get(Recipe_ordinal, "main");
  assert(r);
  routine* main_routine = new routine(r);
  // pass in commandline args as ingredients to main
  // todo: test this
  Current_routine = main_routine;
  for (int i = 1;  i < argc;  ++i) {
    vector<double> arg;
    arg.push_back(new_mu_text(argv[i]));
    current_call().ingredient_atoms.push_back(arg);
  }
  run(main_routine);
}

//:: To schedule new routines to run, call 'start-running'.

//: 'start-running' will return a unique id for the routine that was created.
//: routine id is a number, but don't do any arithmetic on it
:(before "End routine Fields")
int id;
:(before "End Globals")
int Next_routine_id = 1;
:(before "End Setup")
Next_routine_id = 1;
:(before "End routine Constructor")
id = Next_routine_id;
++Next_routine_id;

//: routines save the routine that spawned them
:(before "End routine Fields")
// todo: really should be routine_id, but that's less efficient.
int parent_index;  // only < 0 if there's no parent_index
:(before "End routine Constructor")
parent_index = -1;

:(before "End Primitive Recipe Declarations")
START_RUNNING,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "start-running", START_RUNNING);
:(before "End Primitive Recipe Checks")
case START_RUNNING: {
  if (inst.ingredients.empty()) {
    raise << maybe(get(Recipe, r).name) << "'start-running' requires at least one ingredient: the recipe to start running\n" << end();
    break;
  }
  if (!is_mu_recipe(inst.ingredients.at(0))) {
    raise << maybe(get(Recipe, r).name) << "first ingredient of 'start-running' should be a recipe, but got '" << to_string(inst.ingredients.at(0)) << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case START_RUNNING: {
  routine* new_routine = new routine(ingredients.at(0).at(0));
  new_routine->parent_index = Current_routine_index;
  // populate ingredients
  for (int i = 1;  i < SIZE(current_instruction().ingredients);  ++i) {
    new_routine->calls.front().ingredient_atoms.push_back(ingredients.at(i));
    reagent/*copy*/ ingredient = current_instruction().ingredients.at(i);
    canonize_type(ingredient);
    new_routine->calls.front().ingredients.push_back(ingredient);
    // End Populate start-running Ingredient
  }
  Routines.push_back(new_routine);
  products.resize(1);
  products.at(0).push_back(new_routine->id);
  break;
}

:(scenario scheduler_runs_single_routine)
% Scheduling_interval = 1;
def f1 [
  1:num <- copy 0
  2:num <- copy 0
]
+schedule: f1
+run: {1: "number"} <- copy {0: "literal"}
+schedule: f1
+run: {2: "number"} <- copy {0: "literal"}

:(scenario scheduler_interleaves_routines)
% Scheduling_interval = 1;
def f1 [
  start-running f2
  1:num <- copy 0
  2:num <- copy 0
]
def f2 [
  3:num <- copy 0
  4:num <- copy 0
]
+schedule: f1
+run: start-running {f2: "recipe-literal"}
+schedule: f2
+run: {3: "number"} <- copy {0: "literal"}
+schedule: f1
+run: {1: "number"} <- copy {0: "literal"}
+schedule: f2
+run: {4: "number"} <- copy {0: "literal"}
+schedule: f1
+run: {2: "number"} <- copy {0: "literal"}

:(scenario start_running_takes_ingredients)
def f1 [
  start-running f2, 3
  # wait for f2 to run
  {
    jump-unless 1:num, -1
  }
]
def f2 [
  1:num <- next-ingredient
  2:num <- add 1:num, 1
]
+mem: storing 4 in location 2

//: more complex: refcounting management when starting up new routines

:(scenario start_running_immediately_updates_refcounts_of_ingredients)
% Scheduling_interval = 1;
def main [
  local-scope
  create-new-routine
  # padding to make sure we run new-routine before returning
  dummy:num <- copy 0
  dummy:num <- copy 0
]
def create-new-routine [
  local-scope
  n:&:num <- new number:type
  *n <- copy 34
  start-running new-routine, n
  # refcount of n decremented
]
def new-routine n:&:num [
  local-scope
  load-ingredients
  1:num/raw <- copy *n
]
# check that n wasn't reclaimed when create-new-routine returned
+mem: storing 34 in location 1

//: to support the previous scenario we'll increment refcounts for all call
//: ingredients right at call time, and stop incrementing refcounts inside
//: next-ingredient
:(before "End Populate Call Ingredient")
increment_any_refcounts(ingredient, ingredients.at(i));
:(before "End Populate start-running Ingredient")
increment_any_refcounts(ingredient, ingredients.at(i));
:(before "End should_update_refcounts_in_write_memory Special-cases For Primitives")
if (inst.operation == NEXT_INGREDIENT || inst.operation == NEXT_INGREDIENT_WITHOUT_TYPECHECKING) {
  if (space_index(inst.products.at(0)) > 0) return true;
  if (has_property(inst.products.at(0), "raw")) return true;
  return false;
}

// ensure this works with indirect calls using 'call' as well
:(scenario start_running_immediately_updates_refcounts_of_ingredients_of_indirect_calls)
% Scheduling_interval = 1;
def main [
  local-scope
  n:&:num <- new number:type
  *n <- copy 34
  call f1, n
  1:num/raw <- copy *n
]
def f1 n:&:num [
  local-scope
  load-ingredients
]
# check that n wasn't reclaimed when f1 returned
+mem: storing 34 in location 1

:(scenario next_ingredient_never_leaks_refcounts)
def create-space n:&:num -> default-space:space [
  default-space <- new location:type, 2
  load-ingredients
]
def use-space [
  local-scope
  0:space/names:create-space <- next-ingredient
  n:&:num/space:1 <- next-ingredient  # should decrement refcount
  *n/space:1 <- copy 34
  n2:num <- add *n/space:1, 1
  reply n2
]
def main [
  local-scope
  n:&:num <- copy 12000/unsafe  # pretend allocation with a known address
  *n <- copy 23
  space:space <- create-space n
  n2:&:num <- copy 13000/unsafe
  n3:num <- use-space space, n2
]
+run: {n: ("address" "number"), "space": "1"} <- next-ingredient
+mem: decrementing refcount of 12000: 2 -> 1
+run: {n: ("address" "number"), "space": "1", "lookup": ()} <- copy {34: "literal"}

//: back to testing 'start-running'

:(scenario start_running_returns_routine_id)
def f1 [
  1:num <- start-running f2
]
def f2 [
  12:num <- copy 44
]
+mem: storing 2 in location 1

//: this scenario will require some careful setup in escaped C++
//: (straining our tangle capabilities to near-breaking point)
:(scenario scheduler_skips_completed_routines)
% recipe_ordinal f1 = load("recipe f1 [\n1:num <- copy 0\n]\n").front();
% recipe_ordinal f2 = load("recipe f2 [\n2:num <- copy 0\n]\n").front();
% Routines.push_back(new routine(f1));  // f1 meant to run
% Routines.push_back(new routine(f2));
% Routines.back()->state = COMPLETED;  // f2 not meant to run
# must have at least one routine without escaping
def f3 [
  3:num <- copy 0
]
# by interleaving '+' lines with '-' lines, we allow f1 and f3 to run in any order
+schedule: f1
+mem: storing 0 in location 1
-schedule: f2
-mem: storing 0 in location 2
+schedule: f3
+mem: storing 0 in location 3

:(scenario scheduler_starts_at_middle_of_routines)
% Routines.push_back(new routine(COPY));
% Routines.back()->state = COMPLETED;
def f1 [
  1:num <- copy 0
  2:num <- copy 0
]
+schedule: f1
-run: idle

//:: Errors in a routine cause it to terminate.

:(scenario scheduler_terminates_routines_after_errors)
% Hide_errors = true;
% Scheduling_interval = 2;
def f1 [
  start-running f2
  1:num <- copy 0
  2:num <- copy 0
]
def f2 [
  # divide by 0 twice
  3:num <- divide-with-remainder 4, 0
  4:num <- divide-with-remainder 4, 0
]
# f2 should stop after first divide by 0
+error: f2: divide by zero in '3:num <- divide-with-remainder 4, 0'
-error: f2: divide by zero in '4:num <- divide-with-remainder 4, 0'

:(after "operator<<(ostream& os, unused end)")
  if (Trace_stream && Trace_stream->curr_label == "error" && Current_routine) {
    Current_routine->state = COMPLETED;
  }

//:: Routines are marked completed when their parent completes.

:(scenario scheduler_kills_orphans)
def main [
  start-running f1
  # f1 never actually runs because its parent completes without waiting for it
]
def f1 [
  1:num <- copy 0
]
-schedule: f1

:(before "End Scheduler Cleanup")
for (int i = 0;  i < SIZE(Routines);  ++i) {
  if (Routines.at(i)->state == COMPLETED) continue;
  if (Routines.at(i)->parent_index < 0) continue;  // root thread
  // structured concurrency: http://250bpm.com/blog:71
  if (has_completed_parent(i)) {
    Routines.at(i)->state = COMPLETED;
  }
}

:(code)
bool has_completed_parent(int routine_index) {
  for (int j = routine_index;  j >= 0;  j = Routines.at(j)->parent_index) {
    if (Routines.at(j)->state == COMPLETED)
      return true;
  }
  return false;
}

//:: 'routine-state' can tell if a given routine id is running

:(scenario routine_state_test)
% Scheduling_interval = 2;
def f1 [
  1:num/child-id <- start-running f2
  12:num <- copy 0  # race condition since we don't care about location 12
  # thanks to Scheduling_interval, f2's one instruction runs in between here and completes
  2:num/state <- routine-state 1:num/child-id
]
def f2 [
  12:num <- copy 0
  # trying to run a second instruction marks routine as completed
]
# recipe f2 should be in state COMPLETED
+mem: storing 1 in location 2

:(before "End Primitive Recipe Declarations")
ROUTINE_STATE,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "routine-state", ROUTINE_STATE);
:(before "End Primitive Recipe Checks")
case ROUTINE_STATE: {
  if (SIZE(inst.ingredients) != 1) {
    raise << maybe(get(Recipe, r).name) << "'routine-state' requires exactly one ingredient, but got '" << inst.original_string << "'\n" << end();
    break;
  }
  if (!is_mu_number(inst.ingredients.at(0))) {
    raise << maybe(get(Recipe, r).name) << "first ingredient of 'routine-state' should be a routine id generated by 'start-running', but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case ROUTINE_STATE: {
  int id = ingredients.at(0).at(0);
  int result = -1;
  for (int i = 0;  i < SIZE(Routines);  ++i) {
    if (Routines.at(i)->id == id) {
      result = Routines.at(i)->state;
      break;
    }
  }
  products.resize(1);
  products.at(0).push_back(result);
  break;
}

//:: miscellaneous helpers

:(before "End Primitive Recipe Declarations")
STOP,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "stop", STOP);
:(before "End Primitive Recipe Checks")
case STOP: {
  if (SIZE(inst.ingredients) != 1) {
    raise << maybe(get(Recipe, r).name) << "'stop' requires exactly one ingredient, but got '" << inst.original_string << "'\n" << end();
    break;
  }
  if (!is_mu_number(inst.ingredients.at(0))) {
    raise << maybe(get(Recipe, r).name) << "first ingredient of 'stop' should be a routine id generated by 'start-running', but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case STOP: {
  int id = ingredients.at(0).at(0);
  for (int i = 0;  i < SIZE(Routines);  ++i) {
    if (Routines.at(i)->id == id) {
      Routines.at(i)->state = COMPLETED;
      break;
    }
  }
  break;
}

:(before "End Primitive Recipe Declarations")
_DUMP_ROUTINES,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "$dump-routines", _DUMP_ROUTINES);
:(before "End Primitive Recipe Checks")
case _DUMP_ROUTINES: {
  break;
}
:(before "End Primitive Recipe Implementations")
case _DUMP_ROUTINES: {
  for (int i = 0;  i < SIZE(Routines);  ++i) {
    cerr << i << ": " << Routines.at(i)->id << ' ' << Routines.at(i)->state << ' ' << Routines.at(i)->parent_index << '\n';
  }
  break;
}

//: support for stopping routines after some number of cycles

:(scenario routine_discontinues_past_limit)
% Scheduling_interval = 2;
def f1 [
  1:num/child-id <- start-running f2
  limit-time 1:num/child-id, 10
  # padding loop just to make sure f2 has time to completed
  2:num <- copy 20
  2:num <- subtract 2:num, 1
  jump-if 2:num, -2:offset
]
def f2 [
  jump -1:offset  # run forever
  $print [should never get here], 10/newline
]
# f2 terminates
+schedule: discontinuing routine 2

:(before "End routine States")
DISCONTINUED,
:(before "End Scheduler State Transitions")
if (Current_routine->limit >= 0) {
  if (Current_routine->limit <= Scheduling_interval) {
    trace(9999, "schedule") << "discontinuing routine " << Current_routine->id << end();
    Current_routine->state = DISCONTINUED;
    Current_routine->limit = 0;
  }
  else {
    Current_routine->limit -= Scheduling_interval;
  }
}

:(before "End Test Teardown")
if (Passed && any_routines_with_error()) {
  Passed = false;
  raise << "some routines died with errors\n" << end();
}
:(before "End Mu Test Teardown")
if (Passed && any_routines_with_error()) {
  Passed = false;
  raise << Current_scenario->name << ": some routines died with errors\n" << end();
}

:(code)
bool any_routines_with_error() {
  for (int i = 0;  i < SIZE(Routines);  ++i) {
    if (Routines.at(i)->state == DISCONTINUED)
      return true;
  }
  return false;
}

:(before "End routine Fields")
int limit;
:(before "End routine Constructor")
limit = -1;  /* no limit */

:(before "End Primitive Recipe Declarations")
LIMIT_TIME,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "limit-time", LIMIT_TIME);
:(before "End Primitive Recipe Checks")
case LIMIT_TIME: {
  if (SIZE(inst.ingredients) != 2) {
    raise << maybe(get(Recipe, r).name) << "'limit-time' requires exactly two ingredient, but got '" << inst.original_string << "'\n" << end();
    break;
  }
  if (!is_mu_number(inst.ingredients.at(0))) {
    raise << maybe(get(Recipe, r).name) << "first ingredient of 'limit-time' should be a routine id generated by 'start-running', but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
    break;
  }
  if (!is_mu_number(inst.ingredients.at(1))) {
    raise << maybe(get(Recipe, r).name) << "second ingredient of 'limit-time' should be a number (of instructions to run for), but got '" << inst.ingredients.at(1).original_string << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case LIMIT_TIME: {
  int id = ingredients.at(0).at(0);
  for (int i = 0;  i < SIZE(Routines);  ++i) {
    if (Routines.at(i)->id == id) {
      Routines.at(i)->limit = ingredients.at(1).at(0);
      break;
    }
  }
  break;
}

:(before "End routine Fields")
int instructions_run;
:(before "End routine Constructor")
instructions_run = 0;
:(before "Reset instructions_run_this_scheduling_slice")
Current_routine->instructions_run += Current_routine->instructions_run_this_scheduling_slice;
:(before "End Primitive Recipe Declarations")
NUMBER_OF_INSTRUCTIONS,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "number-of-instructions", NUMBER_OF_INSTRUCTIONS);
:(before "End Primitive Recipe Checks")
case NUMBER_OF_INSTRUCTIONS: {
  if (SIZE(inst.ingredients) != 1) {
    raise << maybe(get(Recipe, r).name) << "'number-of-instructions' requires exactly one ingredient, but got '" << inst.original_string << "'\n" << end();
    break;
  }
  if (!is_mu_number(inst.ingredients.at(0))) {
    raise << maybe(get(Recipe, r).name) << "first ingredient of 'number-of-instructions' should be a routine id generated by 'start-running', but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case NUMBER_OF_INSTRUCTIONS: {
  int id = ingredients.at(0).at(0);
  int result = -1;
  for (int i = 0;  i < SIZE(Routines);  ++i) {
    if (Routines.at(i)->id == id) {
      result = Routines.at(i)->instructions_run;
      break;
    }
  }
  products.resize(1);
  products.at(0).push_back(result);
  break;
}

:(scenario number_of_instructions)
def f1 [
  10:num/child-id <- start-running f2
  {
    loop-unless 20:num
  }
  11:num <- number-of-instructions 10:num
]
def f2 [
  # 2 instructions worth of work
  1:num <- copy 34
  20:num <- copy 1
]
# f2 runs an extra instruction for the implicit return added by the
# fill_in_reply_ingredients transform
+mem: storing 3 in location 11

:(scenario number_of_instructions_across_multiple_scheduling_intervals)
% Scheduling_interval = 1;
def f1 [
  10:num/child-id <- start-running f2
  {
    loop-unless 20:num
  }
  11:num <- number-of-instructions 10:num
]
def f2 [
  # 4 instructions worth of work
  1:num <- copy 34
  2:num <- copy 1
  2:num <- copy 3
  20:num <- copy 1
]
# f2 runs an extra instruction for the implicit return added by the
# fill_in_reply_ingredients transform
+mem: storing 5 in location 11

//:: make sure that each routine gets a different alloc to start

:(scenario new_concurrent)
def f1 [
  start-running f2
  1:&:num/raw <- new number:type
  # wait for f2 to complete
  {
    loop-unless 4:num/raw
  }
]
def f2 [
  2:&:num/raw <- new number:type
  # hack: assumes scheduler implementation
  3:bool/raw <- equal 1:&:num/raw, 2:&:num/raw
  # signal f2 complete
  4:num/raw <- copy 1
]
+mem: storing 0 in location 3