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)))
277   ¦ ¦ load_file_or_directory(dir+'/'+curr_file);
278   ¦ free(files[i]);
279   ¦ files[i] = NULL;
280   }
281   free(files);
282 }
283 :(before "End Includes")
284 #include <dirent.h>
285 #include <sys/stat.h>
286 
287 //:: Reading from memory, writing to memory.
288 
289 :(code)
290 vector<double> read_memory(reagent/*copy*/ x) {
291   // Begin Preprocess read_memory(x)
292   vector<double> result;
293   if (is_literal(x)) {
294   ¦ result.push_back(x.value);
295   ¦ return result;
296   }
297   // End Preprocess read_memory(x)
298   int size = size_of(x);
299   for (int offset = 0;  offset < size;  ++offset) {
300   ¦ double val = get_or_insert(Memory, x.value+offset);
301   ¦ trace("mem") << "location " << x.value+offset << " is " << no_scientific(val) << end();
302   ¦ result.push_back(val);
303   }
304   return result;
305 }
306 
307 void write_memory(reagent/*copy*/ x, const vector<double>& data) {
308   assert(Current_routine);  // run-time only
309   // Begin Preprocess write_memory(x, data)
310   if (!x.type) {
311   ¦ raise << "can't write to '" << to_string(x) << "'; no type\n" << end();
312   ¦ return;
313   }
314   if (is_dummy(x)) return;
315   if (is_literal(x)) return;
316   // End Preprocess write_memory(x, data)
317   if (x.value == 0) {
318   ¦ raise << "can't write to location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
319   ¦ return;
320   }
321   if (size_mismatch(x, data)) {
322   ¦ 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();
323   ¦ return;
324   }
325   // End write_memory(x) Special-cases
326   for (int offset = 0;  offset < SIZE(data);  ++offset) {
327   ¦ assert(x.value+offset > 0);
328   ¦ trace("mem") << "storing " << no_scientific(data.at(offset)) << " in location " << x.value+offset << end();
329 //?     if (Foo) cerr << "mem: storing " << no_scientific(data.at(offset)) << " in location " << x.value+offset << '\n';
330   ¦ put(Memory, x.value+offset, data.at(offset));
331   }
332 }
333 
334 :(code)
335 int size_of(const reagent& r) {
336   if (!r.type) return 0;
337   // End size_of(reagent r) Special-cases
338   return size_of(r.type);
339 }
340 int size_of(const type_tree* type) {
341   if (!type) return 0;
342   if (type->atom) {
343   ¦ if (type->value == -1) return 1;  // error value, but we'll raise it elsewhere
344   ¦ if (type->value == 0) return 1;
345   ¦ // End size_of(type) Atom Special-cases
346   }
347   else {
348   ¦ if (!type->left->atom) {
349   ¦ ¦ raise << "invalid type " << to_string(type) << '\n' << end();
350   ¦ ¦ return 0;
351   ¦ }
352   ¦ if (type->left->value == get(Type_ordinal, "address")) return 1;
353   ¦ // End size_of(type) Non-atom Special-cases
354   }
355   // End size_of(type) Special-cases
356   return 1;
357 }
358 
359 bool size_mismatch(const reagent& x, const vector<double>& data) {
360   if (!x.type) return true;
361   // End size_mismatch(x) Special-cases
362 //?   if (size_of(x) != SIZE(data)) cerr << size_of(x) << " vs " << SIZE(data) << '\n';
363   return size_of(x) != SIZE(data);
364 }
365 
366 bool is_literal(const reagent& r) {
367   return is_literal(r.type);
368 }
369 bool is_literal(const type_tree* type) {
370   if (!type) return false;
371   if (!type->atom) return false;
372   return type->value == 0;
373 }
374 
375 bool scalar(const vector<int>& x) {
376   return SIZE(x) == 1;
377 }
378 bool scalar(const vector<double>& x) {
379   return SIZE(x) == 1;
380 }
381 
382 // helper for tests
383 void run(const string& form) {
384   vector<recipe_ordinal> tmp = load(form);
385   transform_all();
386   if (tmp.empty()) return;
387   if (trace_contains_errors()) {
388   ¦ if (Start_tracing && Trace_stream) Trace_stream->dump();
389   ¦ return;
390   }
391   // if a test defines main, it probably wants to start there regardless of
392   // definition order
393   if (contains_key(Recipe, get(Recipe_ordinal, "main")))
394   ¦ run(get(Recipe_ordinal, "main"));
395   else
396   ¦ run(tmp.front());
397 }
398 
399 :(scenario run_label)
400 def main [
401   +foo
402   1:num <- copy 23
403   2:num <- copy 1:num
404 ]
405 +run: {1: "number"} <- copy {23: "literal"}
406 +run: {2: "number"} <- copy {1: "number"}
407 -run: +foo
408 
409 :(scenario run_dummy)
410 def main [
411   _ <- copy 0
412 ]
413 +run: _ <- copy {0: "literal"}
414 
415 :(scenario write_to_0_disallowed)
416 % Hide_errors = true;
417 def main [
418   0:num <- copy 34
419 ]
420 -mem: storing 34 in location 0
421 
422 //: Mu is robust to various combinations of commas and spaces. You just have
423 //: to put spaces around the '<-'.
424 
425 :(scenario comma_without_space)
426 def main [
427   1:num, 2:num <- copy 2,2
428 ]
429 +mem: storing 2 in location 1
430 
431 :(scenario space_without_comma)
432 def main [
433   1:num, 2:num <- copy 2 2
434 ]
435 +mem: storing 2 in location 1
436 
437 :(scenario comma_before_space)
438 def main [
439   1:num, 2:num <- copy 2, 2
440 ]
441 +mem: storing 2 in location 1
442 
443 :(scenario comma_after_space)
444 def main [
445   1:num, 2:num <- copy 2 ,2
446 ]
447 +mem: storing 2 in location 1
448 
449 //:: Counters for trying to understand where Mu programs are spending their
450 //:: time.
451 
452 :(before "End Globals")
453 bool Run_profiler = false;
454 // We'll key profile information by recipe_ordinal rather than name because
455 // it's more efficient, and because later layers will show more than just the
456 // name of a recipe.
457 //
458 // One drawback: if you're clearing recipes your profile will be inaccurate.
459 // So far that happens in tests, and in 'run-sandboxed' in a later layer.
460 map<recipe_ordinal, int> Instructions_running;
461 :(before "End Commandline Options(*arg)")
462 else if (is_equal(*arg, "--profile")) {
463   Run_profiler = true;
464 }
465 :(after "Running One Instruction")
466 if (Run_profiler) Instructions_running[currently_running_recipe()]++;
467 :(before "End One-time Setup")
468 atexit(dump_profile);
469 :(code)
470 void dump_profile() {
471   if (!Run_profiler) return;
472   if (Run_tests) {
473   ¦ 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";
474   ¦ return;
475   }
476   ofstream fout;
477   fout.open("profile.instructions");
478   if (fout) {
479   ¦ for (map<recipe_ordinal, int>::iterator p = Instructions_running.begin();  p != Instructions_running.end();  ++p) {
480   ¦ ¦ fout << std::setw(9) << p->second << ' ' << header_label(p->first) << '\n';
481   ¦ }
482   }
483   fout.close();
484   // End dump_profile
485 }
486 
487 // overridden in a later layer
488 string header_label(const recipe_ordinal r) {
489   return get(Recipe, r).name;
490 }