//: So far the recipes we define can't run each other. Let's fix that. :(scenario calling_recipe) recipe main [ f ] recipe f [ 3:integer <- add 2:literal, 2:literal ] +mem: storing 4 in location 3 :(scenario return_on_fallthrough) recipe main [ f 1:integer <- copy 34:literal 2:integer <- copy 34:literal 3:integer <- copy 34:literal ] recipe f [ 4:integer <- copy 34:literal 5:integer <- copy 34:literal ] +run: instruction main/0 +run: instruction f/0 +run: instruction f/1 +run: instruction main/1 +run: instruction main/2 +run: instruction main/3 :(before "struct routine {") // Everytime a recipe runs another, we interrupt it and start running the new // recipe. When that finishes, we continue this one where we left off. // This requires maintaining a 'stack' of interrupted recipes or 'calls'. struct call { recipe_number running_recipe; size_t pc; // End call Fields call(recipe_number r) :running_recipe(r), pc(0) {} }; typedef stack call_stack; :(replace{} "struct routine") struct routine { call_stack calls; // End routine Fields routine(recipe_number r); bool completed() const; }; :(code) routine::routine(recipe_number r) { calls.push(call(r)); } //:: now update routine's helpers :(replace{} "inline size_t& running_at()") inline size_t& running_at() { return Current_routine->calls.top().pc; } :(replace{} "inline string recipe_name()") inline string recipe_name() { return Recipe[Current_routine->calls.top().running_recipe].name; } :(replace{} "inline vector& steps()") inline vector& steps() { return Recipe[Current_routine->calls.top().running_recipe].steps; } :(replace{} "default:" following "End Primitive Recipe Implementations") default: { // not a primitive; try to look up the book of recipes if (Recipe.find(instructions[pc].operation) == Recipe.end()) { raise << "undefined operation " << instructions[pc].operation << ": " << instructions[pc].name << '\n'; break; } Current_routine->calls.push(call(instructions[pc].operation)); continue; // not done with caller; don't increment pc } //:: finally, we need to fix the termination conditions for the run loop :(replace{} "inline bool routine::completed() const") inline bool routine::completed() const { return calls.empty(); } :(before "Running One Instruction") // when we reach the end of one call, we may reach the end of the one below // it, and the one below that, and so on //? trace("foo") << "0: " << pc << " " << &pc; //? 1 while (running_at() >= steps().size()) { //? trace("foo") << "pop"; //? 1 Current_routine->calls.pop(); if (Current_routine->calls.empty()) return; // todo: no results returned warning ++running_at(); } //? trace("foo") << "1: " << pc << " " << &pc; //? 1 :(before "End Includes") #include using std::stack;