1 //: Phase 3: Start running a loaded and transformed recipe.
  2 //:
  3 //:   The process of running Mu code:
  4 //:     load -> transform -> run
  5 //:
  6 //: So far we've seen recipes as lists of instructions, and instructions point
  7 //: at other recipes. To kick things off Mu needs to know how to run certain
  8 //: 'primitive' recipes. That will then give the ability to run recipes
  9 //: containing these primitives.
 10 //:
 11 //: This layer defines a skeleton with just two primitive recipes: IDLE which
 12 //: does nothing, and COPY, which can copy numbers from one memory location to
 13 //: another. Later layers will add more primitives.
 14 
 15 :(scenario copy_literal)
 16 def main [
 17   1:num <- copy 23
 18 ]
 19 +run: {1: "number"} <- copy {23: "literal"}
 20 +mem: storing 23 in location 1
 21 
 22 :(scenario copy)
 23 def main [
 24   1:num <- copy 23
 25   2:num <- copy 1:num
 26 ]
 27 +run: {2: "number"} <- copy {1: "number"}
 28 +mem: location 1 is 23
 29 +mem: storing 23 in location 2
 30 
 31 :(scenario copy_multiple)
 32 def main [
 33   1:num, 2:num <- copy 23, 24
 34 ]
 35 +mem: storing 23 in location 1
 36 +mem: storing 24 in location 2
 37 
 38 :(before "End Types")
 39 // Book-keeping while running a recipe.
 40 //: Later layers will replace this to support running multiple routines at once.
 41 struct routine {
 42   recipe_ordinal running_recipe;
 43   int running_step_index;
 44   routine(recipe_ordinal r) :running_recipe(r), running_step_index(0) {}
 45   bool completed() const;
 46   const vector<instruction>& steps() const;
 47 };
 48 
 49 :(before "End Globals")
 50 routine* Current_routine = NULL;
 51 :(before "End Reset")
 52 Current_routine = NULL;
 53 
 54 :(code)
 55 void run(const recipe_ordinal r) {
 56   routine rr(r);
 57   Current_routine = &rr;
 58   run_current_routine();
 59   Current_routine = NULL;
 60 }
 61 
 62 void run_current_routine() {
 63   while (should_continue_running(Current_routine)) {  // beware: may modify Current_routine
 64     // Running One Instruction
 65     if (current_instruction().is_label) { ++current_step_index();  continue; }
 66     trace(Initial_callstack_depth + Trace_stream->callstack_depth, "run") << to_string(current_instruction()) << end();
 67 //?     if (Foo) cerr << "run: " << to_string(current_instruction()) << '\n';
 68     if (get_or_insert(Memory, 0) != 0) {
 69       raise << "something wrote to location 0; this should never happen\n" << end();
 70       put(Memory, 0, 0);
 71     }
 72     // read all ingredients from memory, each potentially spanning multiple locations
 73     vector<vector<double> > ingredients;
 74     if (should_copy_ingredients()) {
 75       for (int i = 0;  i < SIZE(current_instruction().ingredients);  ++i)
 76         ingredients.push_back(read_memory(current_instruction().ingredients.at(i)));
 77     }
 78     // instructions below will write to 'products'
 79     vector<vector<double> > products;
 80     //: This will be a large switch that later layers will often insert cases
 81     //: into. Never call 'continue' within it. Instead, we'll explicitly
 82     //: control which of the following stages after the switch we run for each
 83     //: instruction.
 84     bool write_products = true;
 85     bool fall_through_to_next_instruction = true;
 86     switch (current_instruction().operation) {
 87       // Primitive Recipe Implementations
 88       case COPY: {
 89         copy(ingredients.begin(), ingredients.end(), inserter(products, products.begin()));
 90         break;
 91       }
 92       // End Primitive Recipe Implementations
 93       default: {
 94         cout << "not a primitive op: " << current_instruction().operation << '\n';
 95       }
 96     }
 97     //: used by a later layer
 98     if (write_products) {
 99       if (SIZE(products) < SIZE(current_instruction().products)) {
100         raise << SIZE(products) << " vs " << SIZE(current_instruction().products) << ": failed to write to all products in '" << to_original_string(current_instruction()) << "'\n" << end();
101       }
102       else {
103         for (int i = 0;  i < SIZE(current_instruction().products);  ++i) {
104           // Writing Instruction Product(i)
105           write_memory(current_instruction().products.at(i), products.at(i));
106         }
107       }
108     }
109     // End Running One Instruction
110     if (fall_through_to_next_instruction)
111       ++current_step_index();
112   }
113   stop_running_current_routine:;
114 }
115 
116 :(code)
117 //: hook replaced in a later layer
118 bool should_continue_running(const routine* current_routine) {
119   assert(current_routine == Current_routine);  // argument passed in just to make caller readable above
120   return !Current_routine->completed();
121 }
122 
123 bool should_copy_ingredients() {
124   // End should_copy_ingredients Special-cases
125   return true;
126 }
127 
128 //: Some helpers.
129 //: Important that they return references into the current routine.
130 
131 //: hook replaced in a later layer
132 int& current_step_index() {
133   return Current_routine->running_step_index;
134 }
135 
136 //: hook replaced in a later layer
137 recipe_ordinal currently_running_recipe() {
138   return Current_routine->running_recipe;
139 }
140 
141 //: hook replaced in a later layer
142 const string& current_recipe_name() {
143   return get(Recipe, Current_routine->running_recipe).name;
144 }
145 
146 //: hook replaced in a later layer
147 const recipe& current_recipe() {
148   return get(Recipe, Current_routine->running_recipe);
149 }
150 
151 //: hook replaced in a later layer
152 const instruction& current_instruction() {
153   return get(Recipe, Current_routine->running_recipe).steps.at(Current_routine->running_step_index);
154 }
155 
156 //: hook replaced in a later layer
157 bool routine::completed() const {
158   return running_step_index >= SIZE(get(Recipe, running_recipe).steps);
159 }
160 
161 //: hook replaced in a later layer
162 const vector<instruction>& routine::steps() const {
163   return get(Recipe, running_recipe).steps;
164 }
165 
166 //:: Startup flow
167 
168 //: Step 1: load all .mu files with numeric prefixes (in order)
169 :(before "End Load Recipes")
170 // Load Mu Prelude
171 //? Save_trace = true;
172 //? START_TRACING_UNTIL_END_OF_SCOPE;
173 load_file_or_directory("core.mu");
174 //? DUMP("");
175 //? exit(0);
176 
177 //: Step 2: load any .mu files provided at the commandline
178 :(before "End Commandline Parsing")
179 // Check For .mu Files
180 //? START_TRACING_UNTIL_END_OF_SCOPE
181 //? Dump_trace = true;
182 if (argc > 1) {
183   // skip argv[0]
184   ++argv;
185   --argc;
186   while (argc > 0) {
187     // ignore argv past '--'; that's commandline args for 'main'
188     if (string(*argv) == "--") break;
189     if (starts_with(*argv, "--"))
190       cerr << "treating " << *argv << " as a file rather than an option\n";
191     load_file_or_directory(*argv);
192     --argc;
193     ++argv;
194   }
195   if (Run_tests) Recipe.erase(get(Recipe_ordinal, "main"));
196 }
197 transform_all();
198 //? cerr << to_original_string(get(Type_ordinal, "editor")) << '\n';
199 //? cerr << to_original_string(get(Recipe, get(Recipe_ordinal, "event-loop"))) << '\n';
200 //? DUMP("");
201 //? exit(0);
202 if (trace_contains_errors()) {
203   if (Start_tracing && Trace_stream) Trace_stream->dump();
204   return 1;
205 }
206 save_snapshots();
207 
208 //: Step 3: if we aren't running tests, locate a recipe called 'main' and
209 //: start running it.
210 :(before "End Main")
211 if (!Run_tests && contains_key(Recipe_ordinal, "main") && contains_key(Recipe, get(Recipe_ordinal, "main"))) {
212   // Running Main
213   reset();
214   if (Start_tracing && Trace_stream == NULL) {
215     Trace_stream = new trace_stream;
216     Save_trace = true;
217   }
218   trace(2, "run") << "=== Starting to run" << end();
219   assert(Num_calls_to_transform_all == 1);
220   run_main(argc, argv);
221   if (Start_tracing && Trace_stream) Trace_stream->dump();
222 }
223 :(code)
224 void run_main(int argc, char* argv[]) {
225   recipe_ordinal r = get(Recipe_ordinal, "main");
226   if (r) run(r);
227 }
228 
229 //: By default we don't maintain the trace while running main because its
230 //: overheads can grow rapidly. However, it's useful when debugging.
231 :(before "End Globals")
232 bool Start_tracing = false;
233 :(before "End Commandline Options(*arg)")
234 else if (is_equal(*arg, "--trace")) {
235   Start_tracing = true;
236 }
237 
238 :(code)
239 void cleanup_main() {
240   if (!Trace_stream) return;
241   if (Save_trace)
242     Trace_stream->dump();
243   delete Trace_stream;
244   Trace_stream = NULL;
245 }
246 :(before "End One-time Setup")
247 atexit(cleanup_main);
248 
249 :(code)
250 void load_file_or_directory(string filename) {
251   if (is_directory(filename)) {
252     load_all(filename);
253     return;
254   }
255   ifstream fin(filename.c_str());
256   if (!fin) {
257     cerr << "no such file '" << filename << "'\n" << end();  // don't raise, just warn. just in case it's just a name for a scenario to run.
258     return;
259   }
260   trace(9990, "load") << "=== " << filename << end();
261   load(fin);
262   fin.close();
263 }
264 
265 bool is_directory(string path) {
266   struct stat info;
267   if (stat(path.c_str(), &info)) return false;  // error
268   return info.st_mode & S_IFDIR;
269 }
270 
271 void load_all(string dir) {
272   dirent** files;
273   int num_files = scandir(dir.c_str(), &files, NULL, alphasort);
274   for (int i = 0;  i < num_files;  ++i) {
275     string curr_file = files[i]->d_name;
276     if (isdigit(curr_file.at(0)) && ends_with(curr_file, ".mu"))
277       load_file_or_directory(dir+'/'+curr_file);
278     free(files[i]);
279     files[i] = NULL;
280   }
281   free(files);
282 }
283 
284 bool ends_with(const string& s, const string& pat) {
285   for (string::const_reverse_iterator p = s.rbegin(), q = pat.rbegin();  q != pat.rend();  ++p, ++q) {
286     if (p == s.rend()) return false;  // pat too long
287     if (*p != *q) return false;
288   }
289   return true;
290 }
291 
292 :(before "End Includes")
293 #include <dirent.h>
294 #include <sys/stat.h>
295 
296 //:: Reading from memory, writing to memory.
297 
298 :(code)
299 vector<double> read_memory(reagent/*copy*/ x) {
300   // Begin Preprocess read_memory(x)
301   vector<double> result;
302   if (is_literal(x)) {
303     result.push_back(x.value);
304     return result;
305   }
306   // End Preprocess read_memory(x)
307   int size = size_of(x);
308   for (int offset = 0;  offset < size;  ++offset) {
309     double val = get_or_insert(Memory, x.value+offset);
310     trace("mem") << "location " << x.value+offset << " is " << no_scientific(val) << end();
311     result.push_back(val);
312   }
313   return result;
314 }
315 
316 void write_memory(reagent/*copy*/ x, const vector<double>& data) {
317   assert(Current_routine);  // run-time only
318   // Begin Preprocess write_memory(x, data)
319   if (!x.type) {
320     raise << "can't write to '" << to_string(x) << "'; no type\n" << end();
321     return;
322   }
323   if (is_dummy(x)) return;
324   if (is_literal(x)) return;
325   // End Preprocess write_memory(x, data)
326   if (x.value == 0) {
327     raise << "can't write to location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
328     return;
329   }
330   if (size_mismatch(x, data)) {
331     raise << maybe(current_recipe_name()) << "size mismatch in storing to '" << x.original_string << "' (" << size_of(x) << " vs " << SIZE(data) << ") at '" << to_original_string(current_instruction()) << "'\n" << end();
332     return;
333   }
334   // End write_memory(x) Special-cases
335   for (int offset = 0;  offset < SIZE(data);  ++offset) {
336     assert(x.value+offset > 0);
337     trace("mem") << "storing " << no_scientific(data.at(offset)) << " in location " << x.value+offset << end();
338 //?     if (Foo) cerr << "mem: storing " << no_scientific(data.at(offset)) << " in location " << x.value+offset << '\n';
339     put(Memory, x.value+offset, data.at(offset));
340   }
341 }
342 
343 :(code)
344 int size_of(const reagent& r) {
345   if (!r.type) return 0;
346   // End size_of(reagent r) Special-cases
347   return size_of(r.type);
348 }
349 int size_of(const type_tree* type) {
350   if (!type) return 0;
351   if (type->atom) {
352     if (type->value == -1) return 1;  // error value, but we'll raise it elsewhere
353     if (type->value == 0) return 1;
354     // End size_of(type) Atom Special-cases
355   }
356   else {
357     if (!type->left->atom) {
358       raise << "invalid type " << to_string(type) << '\n' << end();
359       return 0;
360     }
361     if (type->left->value == Address_type_ordinal) return 1;
362     // End size_of(type) Non-atom Special-cases
363   }
364   // End size_of(type) Special-cases
365   return 1;
366 }
367 
368 bool size_mismatch(const reagent& x, const vector<double>& data) {
369   if (!x.type) return true;
370   // End size_mismatch(x) Special-cases
371 //?   if (size_of(x) != SIZE(data)) cerr << size_of(x) << " vs " << SIZE(data) << '\n';
372   return size_of(x) != SIZE(data);
373 }
374 
375 bool is_literal(const reagent& r) {
376   return is_literal(r.type);
377 }
378 bool is_literal(const type_tree* type) {
379   if (!type) return false;
380   if (!type->atom) return false;
381   return type->value == 0;
382 }
383 
384 bool scalar(const vector<int>& x) {
385   return SIZE(x) == 1;
386 }
387 bool scalar(const vector<double>& x) {
388   return SIZE(x) == 1;
389 }
390 
391 // helper for tests
392 void run(const string& form) {
393   vector<recipe_ordinal> tmp = load(form);
394   transform_all();
395   if (tmp.empty()) return;
396   if (trace_contains_errors()) {
397     if (Start_tracing && Trace_stream) Trace_stream->dump();
398     return;
399   }
400   // if a test defines main, it probably wants to start there regardless of
401   // definition order
402   if (contains_key(Recipe, get(Recipe_ordinal, "main")))
403     run(get(Recipe_ordinal, "main"));
404   else
405     run(tmp.front());
406 }
407 
408 :(scenario run_label)
409 def main [
410   +foo
411   1:num <- copy 23
412   2:num <- copy 1:num
413 ]
414 +run: {1: "number"} <- copy {23: "literal"}
415 +run: {2: "number"} <- copy {1: "number"}
416 -run: +foo
417 
418 :(scenario run_dummy)
419 def main [
420   _ <- copy 0
421 ]
422 +run: _ <- copy {0: "literal"}
423 
424 :(scenario write_to_0_disallowed)
425 % Hide_errors = true;
426 def main [
427   0:num <- copy 34
428 ]
429 -mem: storing 34 in location 0
430 
431 //: Mu is robust to various combinations of commas and spaces. You just have
432 //: to put spaces around the '<-'.
433 
434 :(scenario comma_without_space)
435 def main [
436   1:num, 2:num <- copy 2,2
437 ]
438 +mem: storing 2 in location 1
439 
440 :(scenario space_without_comma)
441 def main [
442   1:num, 2:num <- copy 2 2
443 ]
444 +mem: storing 2 in location 1
445 
446 :(scenario comma_before_space)
447 def main [
448   1:num, 2:num <- copy 2, 2
449 ]
450 +mem: storing 2 in location 1
451 
452 :(scenario comma_after_space)
453 def main [
454   1:num, 2:num <- copy 2 ,2
455 ]
456 +mem: storing 2 in location 1
457 
458 //:: Counters for trying to understand where Mu programs are spending their
459 //:: time.
460 
461 :(before "End Globals")
462 bool Run_profiler = false;
463 // We'll key profile information by recipe_ordinal rather than name because
464 // it's more efficient, and because later layers will show more than just the
465 // name of a recipe.
466 //
467 // One drawback: if you're clearing recipes your profile will be inaccurate.
468 // So far that happens in tests, and in 'run-sandboxed' in a later layer.
469 map<recipe_ordinal, int> Instructions_running;
470 :(before "End Commandline Options(*arg)")
471 else if (is_equal(*arg, "--profile")) {
472   Run_profiler = true;
473 }
474 :(after "Running One Instruction")
475 if (Run_profiler) Instructions_running[currently_running_recipe()]++;
476 :(before "End One-time Setup")
477 atexit(dump_profile);
478 :(code)
479 void dump_profile() {
480   if (!Run_profiler) return;
481   if (Run_tests) {
482     cerr << "It's not a good idea to profile a run with tests, since tests can create conflicting recipes and mislead you. To try it anyway, comment out this check in the code.\n";
483     return;
484   }
485   ofstream fout;
486   fout.open("profile.instructions");
487   if (fout) {
488     for (map<recipe_ordinal, int>::iterator p = Instructions_running.begin();  p != Instructions_running.end();  ++p) {
489       fout << std::setw(9) << p->second << ' ' << header_label(p->first) << '\n';
490     }
491   }
492   fout.close();
493   // End dump_profile
494 }
495 
496 // overridden in a later layer
497 string header_label(const recipe_ordinal r) {
498   return get(Recipe, r).name;
499 }