1 //: The goal of layers is to make programs more easy to understand and more
  2 //: malleable, easy to rewrite in radical ways without accidentally breaking
  3 //: some corner case. Tests further both goals. They help understandability by
  4 //: letting one make small changes and get feedback. What if I wrote this line
  5 //: like so? What if I removed this function call, is it really necessary?
  6 //: Just try it, see if the tests pass. Want to explore rewriting this bit in
  7 //: this way? Tests put many refactorings on a firmer footing.
  8 //:
  9 //: But the usual way we write tests seems incomplete. Refactorings tend to
 10 //: work in the small, but don't help with changes to function boundaries. If
 11 //: you want to extract a new function you have to manually test-drive it to
 12 //: create tests for it. If you want to inline a function its tests are no
 13 //: longer valid. In both cases you end up having to reorganize code as well as
 14 //: tests, an error-prone activity.
 15 //:
 16 //: In response, this layer introduces the notion of *domain-driven* testing.
 17 //: We focus on the domain of inputs the whole program needs to handle rather
 18 //: than the correctness of individual functions. All tests invoke the program
 19 //: in a single way: by calling run() with some input. As the program operates
 20 //: on the input, it traces out a list of _facts_ deduced about the domain:
 21 //:   trace("label") << "fact 1: " << val;
 22 //:
 23 //: Tests can now check these facts:
 24 //:   :(scenario foo)
 25 //:   34  # call run() with this input
 26 //:   +label: fact 1: 34  # 'run' should have deduced this fact
 27 //:   -label: fact 1: 35  # the trace should not contain such a fact
 28 //:
 29 //: Since we never call anything but the run() function directly, we never have
 30 //: to rewrite the tests when we reorganize the internals of the program. We
 31 //: just have to make sure our rewrite deduces the same facts about the domain,
 32 //: and that's something we're going to have to do anyway.
 33 //:
 34 //: To avoid the combinatorial explosion of integration tests, each layer
 35 //: mainly logs facts to the trace with a common *label*. All tests in a layer
 36 //: tend to check facts with this label. Validating the facts logged with a
 37 //: specific label is like calling functions of that layer directly.
 38 //:
 39 //: To build robust tests, trace facts about your domain rather than details of
 40 //: how you computed them.
 41 //:
 42 //: More details: http://akkartik.name/blog/tracing-tests
 43 //:
 44 //: ---
 45 //:
 46 //: Between layers and domain-driven testing, programming starts to look like a
 47 //: fundamentally different activity. Instead of a) superficial, b) local rules
 48 //: on c) code [like say http://blog.bbv.ch/2013/06/05/clean-code-cheat-sheet],
 49 //: we allow programmers to engage with the a) deep, b) global structure of the
 50 //: c) domain. If you can systematically track discontinuities in the domain,
 51 //: you don't care if the code used gotos as long as it passed the tests. If
 52 //: tests become more robust to run it becomes easier to try out radically
 53 //: different implementations for the same program. If code is super-easy to
 54 //: rewrite, it becomes less important what indentation style it uses, or that
 55 //: the objects are appropriately encapsulated, or that the functions are
 56 //: referentially transparent.
 57 //:
 58 //: Instead of plumbing, programming becomes building and gradually refining a
 59 //: map of the environment the program must operate under. Whether a program is
 60 //: 'correct' at a given point in time is a red herring; what matters is
 61 //: avoiding regression by monotonically nailing down the more 'eventful' parts
 62 //: of the terrain. It helps readers new and old, and rewards curiosity, to
 63 //: organize large programs in self-similar hierarchies of example scenarios
 64 //: colocated with the code that makes them work.
 65 //:
 66 //:   "Programming properly should be regarded as an activity by which
 67 //:   programmers form a mental model, rather than as production of a program."
 68 //:   -- Peter Naur (http://alistair.cockburn.us/ASD+book+extract%3A+%22Naur,+Ehn,+Musashi%22)
 69 
 70 :(before "End Types")
 71 struct trace_line {
 72   int depth;  // optional field just to help browse traces later
 73   string label;
 74   string contents;
 75   trace_line(string l, string c) :depth(0), label(l), contents(c) {}
 76   trace_line(int d, string l, string c) :depth(d), label(l), contents(c) {}
 77 };
 78 
 79 :(before "End Globals")
 80 bool Hide_errors = false;  // if set, don't print even error trace lines to screen
 81 bool Dump_trace = false;  // if set, print trace lines to screen
 82 string Dump_label = "";  // if set, print trace lines matching a single label to screen
 83 :(before "End Reset")
 84 Hide_errors = false;
 85 Dump_trace = false;
 86 Dump_label = "";
 87 
 88 //: Support for tracing an entire run.
 89 //: Traces can have a lot of overhead, so only turn them on when asked.
 90 :(before "End Commandline Options(*arg)")
 91 else if (is_equal(*arg, "--trace")) {
 92   Save_trace = true;
 93 }
 94 :(before "End Commandline Parsing")
 95 if (Save_trace) {
 96   cerr << "initializing trace\n";
 97   Trace_stream = new trace_stream;
 98 }
 99 :(code)
100 void cleanup_main() {
101   if (!Trace_stream) return;
102   if (Save_trace)
103     Trace_stream->save();
104   delete Trace_stream;
105   Trace_stream = NULL;
106 }
107 :(before "End One-time Setup")
108 atexit(cleanup_main);
109 
110 :(before "End Types")
111 // Pre-define some global constants that trace_stream needs to know about.
112 // Since they're in the Types section, they'll be included in any cleaved
113 // compilation units. So no extern linkage.
114 const int Max_depth = 9999;
115 const int Error_depth = 0;  // definitely always print errors
116 
117 struct trace_stream {
118   vector<trace_line> past_lines;
119   // accumulator for current line
120   ostringstream* curr_stream;
121   string curr_label;
122   int curr_depth;
123   int callstack_depth;
124   int collect_depth;
125   ofstream null_stream;  // never opens a file, so writes silently fail
126   trace_stream() :curr_stream(NULL), curr_depth(Max_depth), callstack_depth(0), collect_depth(Max_depth) {}
127   ~trace_stream() { if (curr_stream) delete curr_stream; }
128 
129   ostream& stream(string label) {
130     return stream(Max_depth, label);
131   }
132 
133   ostream& stream(int depth, string label) {
134     if (depth > collect_depth) return null_stream;
135     curr_stream = new ostringstream;
136     curr_label = label;
137     curr_depth = depth;
138     return *curr_stream;
139   }
140 
141   void save() {
142     cerr << "saving trace to 'last_run'\n";
143     ofstream fout("last_run");
144     fout << readable_contents("");
145     fout.close();
146   }
147 
148   // be sure to call this before messing with curr_stream or curr_label
149   void newline();
150   // useful for debugging
151   string readable_contents(string label);  // empty label = show everything
152 };
153 
154 :(code)
155 void trace_stream::newline() {
156   if (!curr_stream) return;
157   string curr_contents = curr_stream->str();
158   if (!curr_contents.empty()) {
159     past_lines.push_back(trace_line(curr_depth, trim(curr_label), curr_contents));  // preserve indent in contents
160     if ((!Hide_errors && curr_label == "error")
161         || Dump_trace
162         || (!Dump_label.empty() && curr_label == Dump_label))
163       cerr << curr_label << ": " << curr_contents << '\n';
164   }
165   delete curr_stream;
166   curr_stream = NULL;
167   curr_label.clear();
168   curr_depth = Max_depth;
169 }
170 
171 string trace_stream::readable_contents(string label) {
172   ostringstream output;
173   label = trim(label);
174   for (vector<trace_line>::iterator p = past_lines.begin();  p != past_lines.end();  ++p)
175     if (label.empty() || label == p->label) {
176       output << std::setw(4) << p->depth << ' ' << p->label << ": " << p->contents << '\n';
177     }
178   return output.str();
179 }
180 
181 :(before "End Globals")
182 trace_stream* Trace_stream = NULL;
183 int Trace_errors = 0;  // used only when Trace_stream is NULL
184 
185 :(before "End Includes")
186 #define CLEAR_TRACE  delete Trace_stream, Trace_stream = new trace_stream;
187 
188 // Top-level helper. IMPORTANT: can't nest
189 #define trace(...)  !Trace_stream ? cerr /*print nothing*/ : Trace_stream->stream(__VA_ARGS__)
190 
191 // Just for debugging; 'git log' should never show any calls to 'dbg'.
192 #define dbg trace(0, "a")
193 #define DUMP(label)  if (Trace_stream) cerr << Trace_stream->readable_contents(label);
194 
195 // Errors are a special layer.
196 #define raise  (!Trace_stream ? (++Trace_errors,cerr) /*do print*/ : Trace_stream->stream(Error_depth, "error"))
197 // If we aren't yet sure how to deal with some corner case, use assert_for_now
198 // to indicate that it isn't an inviolable invariant.
199 #define assert_for_now assert
200 
201 // Inside tests, fail any tests that displayed (unexpected) errors.
202 // Expected errors in tests should always be hidden and silently checked for.
203 :(before "End Test Teardown")
204 if (Passed && !Hide_errors && trace_contains_errors()) {
205   Passed = false;
206 }
207 :(code)
208 bool trace_contains_errors() {
209   return Trace_errors > 0 || trace_count("error") > 0;
210 }
211 
212 :(before "End Types")
213 struct end {};
214 :(code)
215 ostream& operator<<(ostream& os, end /*unused*/) {
216   if (Trace_stream) Trace_stream->newline();
217   return os;
218 }
219 
220 :(before "End Globals")
221 bool Save_trace = false;  // if set, write out trace to disk
222 
223 // Trace_stream is a resource, lease_tracer uses RAII to manage it.
224 :(before "End Types")
225 struct lease_tracer {
226   lease_tracer();
227   ~lease_tracer();
228 };
229 :(code)
230 lease_tracer::lease_tracer() { Trace_stream = new trace_stream; }
231 lease_tracer::~lease_tracer() {
232   if (Save_trace) Trace_stream->save();
233   delete Trace_stream, Trace_stream = NULL;
234 }
235 :(before "End Includes")
236 #define START_TRACING_UNTIL_END_OF_SCOPE  lease_tracer leased_tracer;
237 :(before "End Test Setup")
238 START_TRACING_UNTIL_END_OF_SCOPE
239 
240 :(before "End Includes")
241 #define CHECK_TRACE_CONTENTS(...)  check_trace_contents(__FUNCTION__, __FILE__, __LINE__, __VA_ARGS__)
242 
243 #define CHECK_TRACE_CONTAINS_ERRORS()  CHECK(trace_contains_errors())
244 #define CHECK_TRACE_DOESNT_CONTAIN_ERRORS() \
245   if (Passed && trace_contains_errors()) { \
246     cerr << "\nF - " << __FUNCTION__ << "(" << __FILE__ << ":" << __LINE__ << "): unexpected errors\n"; \
247     DUMP("error"); \
248     Passed = false; \
249     return; \
250   }
251 
252 #define CHECK_TRACE_COUNT(label, count) \
253   if (Passed && trace_count(label) != (count)) { \
254     cerr << "\nF - " << __FUNCTION__ << "(" << __FILE__ << ":" << __LINE__ << "): trace_count of " << label << " should be " << count << '\n'; \
255     cerr << "  got " << trace_count(label) << '\n';  /* multiple eval */ \
256     DUMP(label); \
257     Passed = false; \
258     return;  /* Currently we stop at the very first failure. */ \
259   }
260 
261 #define CHECK_TRACE_DOESNT_CONTAIN(...)  CHECK(trace_doesnt_contain(__VA_ARGS__))
262 
263 :(code)
264 bool check_trace_contents(string FUNCTION, string FILE, int LINE, string expected) {
265   if (!Passed) return false;
266   if (!Trace_stream) return false;
267   vector<string> expected_lines = split(expected, "^D");
268   int curr_expected_line = 0;
269   while (curr_expected_line < SIZE(expected_lines) && expected_lines.at(curr_expected_line).empty())
270     ++curr_expected_line;
271   if (curr_expected_line == SIZE(expected_lines)) return true;
272   string label, contents;
273   split_label_contents(expected_lines.at(curr_expected_line), &label, &contents);
274   for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
275     if (label != p->label) continue;
276     if (contents != trim(p->contents)) continue;
277     ++curr_expected_line;
278     while (curr_expected_line < SIZE(expected_lines) && expected_lines.at(curr_expected_line).empty())
279       ++curr_expected_line;
280     if (curr_expected_line == SIZE(expected_lines)) return true;
281     split_label_contents(expected_lines.at(curr_expected_line), &label, &contents);
282   }
283 
284   if (line_exists_anywhere(label, contents)) {
285     cerr << "\nF - " << FUNCTION << "(" << FILE << ":" << LINE << "): line [" << label << ": " << contents << "] out of order in trace:\n";
286     DUMP("");
287   }
288   else {
289     cerr << "\nF - " << FUNCTION << "(" << FILE << ":" << LINE << "): missing [" << contents << "] in trace:\n";
290     DUMP(label);
291   }
292   Passed = false;
293   return false;
294 }
295 
296 void split_label_contents(const string& s, string* label, string* contents) {
297   static const string delim(": ");
298   size_t pos = s.find(delim);
299   if (pos == string::npos) {
300     *label = "";
301     *contents = trim(s);
302   }
303   else {
304     *label = trim(s.substr(0, pos));
305     *contents = trim(s.substr(pos+SIZE(delim)));
306   }
307 }
308 
309 bool line_exists_anywhere(const string& label, const string& contents) {
310   for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
311     if (label != p->label) continue;
312     if (contents == trim(p->contents)) return true;
313   }
314   return false;
315 }
316 
317 int trace_count(string label) {
318   return trace_count(label, "");
319 }
320 
321 int trace_count(string label, string line) {
322   if (!Trace_stream) return 0;
323   long result = 0;
324   for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
325     if (label == p->label) {
326       if (line == "" || trim(line) == trim(p->contents))
327         ++result;
328     }
329   }
330   return result;
331 }
332 
333 int trace_count_prefix(string label, string prefix) {
334   if (!Trace_stream) return 0;
335   long result = 0;
336   for (vector<trace_line>::iterator p = Trace_stream->past_lines.begin();  p != Trace_stream->past_lines.end();  ++p) {
337     if (label == p->label) {
338       if (starts_with(trim(p->contents), trim(prefix)))
339         ++result;
340     }
341   }
342   return result;
343 }
344 
345 bool trace_doesnt_contain(string label, string line) {
346   return trace_count(label, line) == 0;
347 }
348 
349 bool trace_doesnt_contain(string expected) {
350   vector<string> tmp = split_first(expected, ": ");
351   return trace_doesnt_contain(tmp.at(0), tmp.at(1));
352 }
353 
354 vector<string> split(string s, string delim) {
355   vector<string> result;
356   size_t begin=0, end=s.find(delim);
357   while (true) {
358     if (end == string::npos) {
359       result.push_back(string(s, begin, string::npos));
360       break;
361     }
362     result.push_back(string(s, begin, end-begin));
363     begin = end+SIZE(delim);
364     end = s.find(delim, begin);
365   }
366   return result;
367 }
368 
369 vector<string> split_first(string s, string delim) {
370   vector<string> result;
371   size_t end=s.find(delim);
372   result.push_back(string(s, 0, end));
373   if (end != string::npos)
374     result.push_back(string(s, end+SIZE(delim), string::npos));
375   return result;
376 }
377 
378 string trim(const string& s) {
379   string::const_iterator first = s.begin();
380   while (first != s.end() && isspace(*first))
381     ++first;
382   if (first == s.end()) return "";
383 
384   string::const_iterator last = --s.end();
385   while (last != s.begin() && isspace(*last))
386     --last;
387   ++last;
388   return string(first, last);
389 }
390 
391 :(before "End Includes")
392 #include <vector>
393 using std::vector;
394 #include <list>
395 using std::list;
396 #include <set>
397 using std::set;
398 
399 #include <sstream>
400 using std::istringstream;
401 using std::ostringstream;
402 
403 #include <fstream>
404 using std::ifstream;
405 using std::ofstream;
406 
407 :(before "End Globals")
408 //: In future layers we'll use the depth field as follows:
409 //:
410 //: Errors will be depth 0.
411 //: Mu 'applications' will be able to use depths 1-100 as they like.
412 //: Primitive statements will occupy 101-9989
413 extern const int Initial_callstack_depth = 101;
414 extern const int Max_callstack_depth = 9989;
415 //: Finally, details of primitive Mu statements will occupy depth 9990-9999
416 //: (more on that later as well)
417 //:
418 //: This framework should help us hide some details at each level, mixing
419 //: static ideas like layers with the dynamic notion of call-stack depth.