mu/cpp/021call

78 lines
2.2 KiB
Plaintext
Raw Normal View History

//: So far the recipes we define can't run each other. Let's change that.
2015-03-14 00:39:32 +00:00
:(scenario "calling_recipe")
recipe main [
f
]
recipe f [
3:integer <- add 2:literal, 2:literal
]
2015-03-24 06:59:59 +00:00
+mem: storing 4 in location 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> call_stack;
:(replace{} "struct routine")
struct routine {
call_stack calls;
2015-03-27 17:51:27 +00:00
// End Routine Fields
routine(recipe_number r);
};
:(code)
routine::routine(recipe_number r) {
calls.push(call(r));
}
//: now update routine's helpers
:(replace{} "inline size_t& running_at(routine& rr)")
inline size_t& running_at(routine& rr) {
return rr.calls.top().pc;
}
:(replace{} "inline string recipe_name(routine& rr)")
inline string recipe_name(routine& rr) {
return Recipe[rr.calls.top().running_recipe].name;
}
:(replace{} "inline vector<instruction>& steps(routine& rr)")
inline vector<instruction>& steps(routine& rr) {
return Recipe[rr.calls.top().running_recipe].steps;
}
2015-03-15 05:25:06 +00:00
2015-03-15 15:41:23 +00:00
:(replace{} "default:" following "End Primitive Recipe Implementations.")
2015-03-15 00:10:33 +00:00
default: {
2015-03-15 05:25:06 +00:00
// not a primitive; try to look for a matching recipe
2015-03-15 00:10:33 +00:00
if (Recipe.find(instructions[pc].operation) == Recipe.end()) {
2015-03-17 06:41:01 +00:00
raise << "undefined operation " << instructions[pc].operation << ": " << instructions[pc].name << '\n';
2015-03-15 00:10:33 +00:00
break;
}
rr.calls.push(call(instructions[pc].operation));
2015-03-15 00:10:33 +00:00
continue; // not done with caller; don't increment pc
}
2015-03-17 03:41:12 +00:00
//: finally, we need to fix the termination conditions for the run loop
:(replace{} "inline bool done(routine& rr)")
inline bool done(routine& rr) {
return rr.calls.empty();
}
2015-03-14 08:09:20 +00:00
:(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
while (running_at(rr) >= steps(rr).size()) {
2015-03-14 08:09:20 +00:00
rr.calls.pop();
if (rr.calls.empty()) return;
// todo: no results returned warning
++running_at(rr);
2015-03-14 08:09:20 +00:00
}
2015-04-06 19:21:18 +00:00
:(before "End Includes")
#include <stack>
using std::stack;