mu/archive/1.vm/028call_return.cc

198 lines
7.1 KiB
C++
Raw Permalink Normal View History

//: Calls can also generate products, using 'reply' or 'return'.
2015-04-17 18:22:59 +00:00
5001 - drop the :(scenario) DSL I've been saying for a while[1][2][3] that adding extra abstractions makes things harder for newcomers, and adding new notations doubly so. And then I notice this DSL in my own backyard. Makes me feel like a hypocrite. [1] https://news.ycombinator.com/item?id=13565743#13570092 [2] https://lobste.rs/s/to8wpr/configuration_files_are_canary_warning [3] https://lobste.rs/s/mdmcdi/little_languages_by_jon_bentley_1986#c_3miuf2 The implementation of the DSL was also highly hacky: a) It was happening in the tangle/ tool, but was utterly unrelated to tangling layers. b) There were several persnickety constraints on the different kinds of lines and the specific order they were expected in. I kept finding bugs where the translator would silently do the wrong thing. Or the error messages sucked, and readers may be stuck looking at the generated code to figure out what happened. Fixing error messages would require a lot more code, which is one of my arguments against DSLs in the first place: they may be easy to implement, but they're hard to design to go with the grain of the underlying platform. They require lots of iteration. Is that effort worth prioritizing in this project? On the other hand, the DSL did make at least some readers' life easier, the ones who weren't immediately put off by having to learn a strange syntax. There were fewer quotes to parse, fewer backslash escapes. Anyway, since there are also people who dislike having to put up with strange syntaxes, we'll call that consideration a wash and tear this DSL out. --- This commit was sheer drudgery. Hopefully it won't need to be redone with a new DSL because I grow sick of backslashes.
2019-03-13 01:56:55 +00:00
void test_return() {
run(
"def main [\n"
" 1:num, 2:num <- f 34\n"
"]\n"
"def f [\n"
" 12:num <- next-ingredient\n"
" 13:num <- add 1, 12:num\n"
" return 12:num, 13:num\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 1\n"
"mem: storing 35 in location 2\n"
);
}
5001 - drop the :(scenario) DSL I've been saying for a while[1][2][3] that adding extra abstractions makes things harder for newcomers, and adding new notations doubly so. And then I notice this DSL in my own backyard. Makes me feel like a hypocrite. [1] https://news.ycombinator.com/item?id=13565743#13570092 [2] https://lobste.rs/s/to8wpr/configuration_files_are_canary_warning [3] https://lobste.rs/s/mdmcdi/little_languages_by_jon_bentley_1986#c_3miuf2 The implementation of the DSL was also highly hacky: a) It was happening in the tangle/ tool, but was utterly unrelated to tangling layers. b) There were several persnickety constraints on the different kinds of lines and the specific order they were expected in. I kept finding bugs where the translator would silently do the wrong thing. Or the error messages sucked, and readers may be stuck looking at the generated code to figure out what happened. Fixing error messages would require a lot more code, which is one of my arguments against DSLs in the first place: they may be easy to implement, but they're hard to design to go with the grain of the underlying platform. They require lots of iteration. Is that effort worth prioritizing in this project? On the other hand, the DSL did make at least some readers' life easier, the ones who weren't immediately put off by having to learn a strange syntax. There were fewer quotes to parse, fewer backslash escapes. Anyway, since there are also people who dislike having to put up with strange syntaxes, we'll call that consideration a wash and tear this DSL out. --- This commit was sheer drudgery. Hopefully it won't need to be redone with a new DSL because I grow sick of backslashes.
2019-03-13 01:56:55 +00:00
void test_reply() {
run(
"def main [\n"
" 1:num, 2:num <- f 34\n"
"]\n"
"def f [\n"
" 12:num <- next-ingredient\n"
" 13:num <- add 1, 12:num\n"
" reply 12:num, 13:num\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 1\n"
"mem: storing 35 in location 2\n"
);
}
:(before "End Primitive Recipe Declarations")
RETURN,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "return", RETURN);
put(Recipe_ordinal, "reply", RETURN); // synonym while teaching
2017-12-04 07:25:40 +00:00
put(Recipe_ordinal, "output", RETURN); // experiment
2015-10-02 00:30:14 +00:00
:(before "End Primitive Recipe Checks")
case RETURN: {
break; // checks will be performed by a transform below
2015-10-02 00:30:14 +00:00
}
:(before "End Primitive Recipe Implementations")
case RETURN: {
4089 Clean up how we reclaim local scopes. It used to work like this (commit 3216): 1. Update refcounts of products after every instruction, EXCEPT: a) when instruction is a non-primitive and the callee starts with 'local-scope' (because it's already not decremented in 'return') OR: b) when instruction is primitive 'next-ingredient' or 'next-ingredient-without-typechecking', and its result is saved to a variable in the default space (because it's already incremented at the time of the call) 2. If a function starts with 'local-scope', force it to be reclaimed before each return. However, since locals may be returned, *very carefully* don't reclaim those. (See the logic in the old `escaping` and `should_update_refcount` functions.) However, this approach had issues. We needed two separate commands for 'local-scope' (reclaim locals on exit) and 'new-default-space' (programmer takes charge of reclaiming locals). The hard-coded reclamation duplicated refcounting logic. In addition to adding complexity, this implementation failed to work if a function overwrites default-space after setting up a local-scope (the old default-space is leaked). It also fails in the presence of continuations. Calling a continuation more than once was guaranteed to corrupt memory (commit 3986). After this commit, reclaiming local scopes now works like this: Update refcounts of products for every PRIMITIVE instruction. For non-primitive instructions, all the work happens in the `return` instruction: increment refcount of ingredients to `return` (unless -- one last bit of ugliness -- they aren't saved in the caller) decrement the refcount of the default-space use existing infrastructure for reclaiming as necessary if reclaiming default-space, first decrement refcount of each local again, use existing infrastructure for reclaiming as necessary This commit (finally!) completes the bulk[1] of step 2 of the plan in commit 3991. It was very hard until I gave up trying to tweak the existing implementation and just test-drove layer 43 from scratch. [1] There's still potential for memory corruption if we abuse `default-space`. I should probably try to add warnings about that at some point (todo in layer 45).
2017-10-23 06:14:19 +00:00
// Begin Return
trace(Callstack_depth+1, "trace") << current_instruction().name << ": decrementing callstack depth from " << Callstack_depth << end();
--Callstack_depth;
if (Callstack_depth < 0) {
Current_routine->calls.clear();
goto stop_running_current_routine;
}
Current_routine->calls.pop_front();
// just in case 'main' returns a value, drop it for now
if (Current_routine->calls.empty()) goto stop_running_current_routine;
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(ingredients); ++i)
trace(Callstack_depth+1, "run") << "result " << i << " is " << to_string(ingredients.at(i)) << end();
// make return products available to caller
copy(ingredients.begin(), ingredients.end(), inserter(products, products.begin()));
4089 Clean up how we reclaim local scopes. It used to work like this (commit 3216): 1. Update refcounts of products after every instruction, EXCEPT: a) when instruction is a non-primitive and the callee starts with 'local-scope' (because it's already not decremented in 'return') OR: b) when instruction is primitive 'next-ingredient' or 'next-ingredient-without-typechecking', and its result is saved to a variable in the default space (because it's already incremented at the time of the call) 2. If a function starts with 'local-scope', force it to be reclaimed before each return. However, since locals may be returned, *very carefully* don't reclaim those. (See the logic in the old `escaping` and `should_update_refcount` functions.) However, this approach had issues. We needed two separate commands for 'local-scope' (reclaim locals on exit) and 'new-default-space' (programmer takes charge of reclaiming locals). The hard-coded reclamation duplicated refcounting logic. In addition to adding complexity, this implementation failed to work if a function overwrites default-space after setting up a local-scope (the old default-space is leaked). It also fails in the presence of continuations. Calling a continuation more than once was guaranteed to corrupt memory (commit 3986). After this commit, reclaiming local scopes now works like this: Update refcounts of products for every PRIMITIVE instruction. For non-primitive instructions, all the work happens in the `return` instruction: increment refcount of ingredients to `return` (unless -- one last bit of ugliness -- they aren't saved in the caller) decrement the refcount of the default-space use existing infrastructure for reclaiming as necessary if reclaiming default-space, first decrement refcount of each local again, use existing infrastructure for reclaiming as necessary This commit (finally!) completes the bulk[1] of step 2 of the plan in commit 3991. It was very hard until I gave up trying to tweak the existing implementation and just test-drove layer 43 from scratch. [1] There's still potential for memory corruption if we abuse `default-space`. I should probably try to add warnings about that at some point (todo in layer 45).
2017-10-23 06:14:19 +00:00
// End Return
break; // continue to process rest of *caller* instruction
}
2015-03-31 17:56:01 +00:00
//: Types in return instructions are checked ahead of time.
:(before "End Checks")
Transform.push_back(check_types_of_return_instructions); // idempotent
:(code)
void check_types_of_return_instructions(const recipe_ordinal r) {
const recipe& caller = get(Recipe, r);
trace(9991, "transform") << "--- check types of return instructions in recipe " << caller.name << end();
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller.steps); ++i) {
const instruction& caller_instruction = caller.steps.at(i);
if (caller_instruction.is_label) continue;
if (caller_instruction.products.empty()) continue;
if (is_primitive(caller_instruction.operation)) continue;
const recipe& callee = get(Recipe, caller_instruction.operation);
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(callee.steps); ++i) {
const instruction& return_inst = callee.steps.at(i);
if (return_inst.operation != RETURN) continue;
// check types with the caller
if (SIZE(caller_instruction.products) > SIZE(return_inst.ingredients)) {
raise << maybe(caller.name) << "too few values returned from " << callee.name << '\n' << end();
break;
}
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller_instruction.products); ++i) {
reagent/*copy*/ lhs = return_inst.ingredients.at(i);
2016-05-06 07:46:39 +00:00
reagent/*copy*/ rhs = caller_instruction.products.at(i);
// End Check RETURN Copy(lhs, rhs)
2016-02-25 05:14:24 +00:00
if (!types_coercible(rhs, lhs)) {
raise << maybe(callee.name) << return_inst.name << " ingredient '" << lhs.original_string << "' can't be saved in '" << rhs.original_string << "'\n" << end();
2016-09-05 21:07:33 +00:00
raise << " ['" << to_string(lhs.type) << "' vs '" << to_string(rhs.type) << "']\n" << end();
goto finish_return_check;
}
}
// check that any return ingredients with /same-as-ingredient connect up
// the corresponding ingredient and product in the caller.
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller_instruction.products); ++i) {
if (has_property(return_inst.ingredients.at(i), "same-as-ingredient")) {
string_tree* tmp = property(return_inst.ingredients.at(i), "same-as-ingredient");
3309 Rip out everything to fix one failing unit test (commit 3290; type abbreviations). This commit does several things at once that I couldn't come up with a clean way to unpack: A. It moves to a new representation for type trees without changing the actual definition of the `type_tree` struct. B. It adds unit tests for our type metadata precomputation, so that errors there show up early and in a simpler setting rather than dying when we try to load Mu code. C. It fixes a bug, guarding against infinite loops when precomputing metadata for recursive shape-shifting containers. To do this it uses a dumb way of comparing type_trees, comparing their string representations instead. That is likely incredibly inefficient. Perhaps due to C, this commit has made Mu incredibly slow. Running all tests for the core and the edit/ app now takes 6.5 minutes rather than 3.5 minutes. == more notes and details I've been struggling for the past week now to back out of a bad design decision, a premature optimization from the early days: storing atoms directly in the 'value' slot of a cons cell rather than creating a special 'atom' cons cell and storing it on the 'left' slot. In other words, if a cons cell looks like this: o / | \ left val right ..then the type_tree (a b c) used to look like this (before this commit): o | \ a o | \ b o | \ c null ..rather than like this 'classic' approach to s-expressions which never mixes val and right (which is what we now have): o / \ o o | / \ a o o | / \ b o null | c The old approach made several operations more complicated, most recently the act of replacing a (possibly atom/leaf) sub-tree with another. That was the final straw that got me to realize the contortions I was going through to save a few type_tree nodes (cons cells). Switching to the new approach was hard partly because I've been using the old approach for so long and type_tree manipulations had pervaded everything. Another issue I ran into was the realization that my layers were not cleanly separated. Key parts of early layers (precomputing type metadata) existed purely for far later ones (shape-shifting types). Layers I got repeatedly stuck at: 1. the transform for precomputing type sizes (layer 30) 2. type-checks on merge instructions (layer 31) 3. the transform for precomputing address offsets in types (layer 36) 4. replace operations in supporting shape-shifting recipes (layer 55) After much thrashing I finally noticed that it wasn't the entirety of these layers that was giving me trouble, but just the type metadata precomputation, which had bugs that weren't manifesting until 30 layers later. Or, worse, when loading .mu files before any tests had had a chance to run. A common failure mode was running into types at run time that I hadn't precomputed metadata for at transform time. Digging into these bugs got me to realize that what I had before wasn't really very good, but a half-assed heuristic approach that did a whole lot of extra work precomputing metadata for utterly meaningless types like `((address number) 3)` which just happened to be part of a larger type like `(array (address number) 3)`. So, I redid it all. I switched the representation of types (because the old representation made unit tests difficult to retrofit) and added unit tests to the metadata precomputation. I also made layer 30 only do the minimal metadata precomputation it needs for the concepts introduced until then. In the process, I also made the precomputation more correct than before, and added hooks in the right place so that I could augment the logic when I introduced shape-shifting containers. == lessons learned There's several levels of hygiene when it comes to layers: 1. Every layer introduces precisely what it needs and in the simplest way possible. If I was building an app until just that layer, nothing would seem over-engineered. 2. Some layers are fore-shadowing features in future layers. Sometimes this is ok. For example, layer 10 foreshadows containers and arrays and so on without actually supporting them. That is a net win because it lets me lay out the core of Mu's data structures out in one place. But if the fore-shadowing gets too complex things get nasty. Not least because it can be hard to write unit tests for features before you provide the plumbing to visualize and manipulate them. 3. A layer is introducing features that are tested only in later layers. 4. A layer is introducing features with tests that are invalidated in later layers. (This I knew from early on to be an obviously horrendous idea.) Summary: avoid Level 2 (foreshadowing layers) as much as possible. Tolerate it indefinitely for small things where the code stays simple over time, but become strict again when things start to get more complex. Level 3 is mostly a net lose, but sometimes it can be expedient (a real case of the usually grossly over-applied term "technical debt"), and it's better than the conventional baseline of no layers and no scenarios. Just clean it up as soon as possible. Definitely avoid layer 4 at any time. == minor lessons Avoid unit tests for trivial things, write scenarios in context as much as possible. But within those margins unit tests are fine. Just introduce them before any scenarios (commit 3297). Reorganizing layers can be easy. Just merge layers for starters! Punt on resplitting them in some new way until you've gotten them to work. This is the wisdom of Refactoring: small steps. What made it hard was not wanting to merge *everything* between layer 30 and 55. The eventual insight was realizing I just need to move those two full-strength transforms and nothing else.
2016-09-10 01:32:52 +00:00
if (!tmp || !tmp->atom) {
2017-05-26 23:43:18 +00:00
raise << maybe(caller.name) << "'same-as-ingredient' metadata should take exactly one value in '" << to_original_string(return_inst) << "'\n" << end();
goto finish_return_check;
}
int ingredient_index = to_integer(tmp->value);
2016-01-25 02:41:26 +00:00
if (ingredient_index >= SIZE(caller_instruction.ingredients)) {
2017-05-26 23:43:18 +00:00
raise << maybe(caller.name) << "too few ingredients in '" << to_original_string(caller_instruction) << "'\n" << end();
goto finish_return_check;
2016-01-25 02:41:26 +00:00
}
if (!is_dummy(caller_instruction.products.at(i)) && !is_literal(caller_instruction.ingredients.at(ingredient_index)) && caller_instruction.products.at(i).name != caller_instruction.ingredients.at(ingredient_index).name) {
2017-05-26 23:43:18 +00:00
raise << maybe(caller.name) << "'" << to_original_string(caller_instruction) << "' should write to '" << caller_instruction.ingredients.at(ingredient_index).original_string << "' rather than '" << caller_instruction.products.at(i).original_string << "'\n" << end();
}
}
}
finish_return_check:;
}
}
}
bool is_primitive(recipe_ordinal r) {
return r < MAX_PRIMITIVE_RECIPES;
}
5001 - drop the :(scenario) DSL I've been saying for a while[1][2][3] that adding extra abstractions makes things harder for newcomers, and adding new notations doubly so. And then I notice this DSL in my own backyard. Makes me feel like a hypocrite. [1] https://news.ycombinator.com/item?id=13565743#13570092 [2] https://lobste.rs/s/to8wpr/configuration_files_are_canary_warning [3] https://lobste.rs/s/mdmcdi/little_languages_by_jon_bentley_1986#c_3miuf2 The implementation of the DSL was also highly hacky: a) It was happening in the tangle/ tool, but was utterly unrelated to tangling layers. b) There were several persnickety constraints on the different kinds of lines and the specific order they were expected in. I kept finding bugs where the translator would silently do the wrong thing. Or the error messages sucked, and readers may be stuck looking at the generated code to figure out what happened. Fixing error messages would require a lot more code, which is one of my arguments against DSLs in the first place: they may be easy to implement, but they're hard to design to go with the grain of the underlying platform. They require lots of iteration. Is that effort worth prioritizing in this project? On the other hand, the DSL did make at least some readers' life easier, the ones who weren't immediately put off by having to learn a strange syntax. There were fewer quotes to parse, fewer backslash escapes. Anyway, since there are also people who dislike having to put up with strange syntaxes, we'll call that consideration a wash and tear this DSL out. --- This commit was sheer drudgery. Hopefully it won't need to be redone with a new DSL because I grow sick of backslashes.
2019-03-13 01:56:55 +00:00
void test_return_type_mismatch() {
Hide_errors = true;
run(
"def main [\n"
" 3:num <- f 2\n"
"]\n"
"def f [\n"
" 12:num <- next-ingredient\n"
" 13:num <- copy 35\n"
" 14:point <- copy 12:point/raw\n"
" return 14:point\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"error: f: return ingredient '14:point' can't be saved in '3:num'\n"
);
}
2016-10-22 23:56:07 +00:00
//: In Mu we'd like to assume that any instruction doesn't modify its
//: ingredients unless they're also products. The /same-as-ingredient inside
//: the recipe's 'return' indicates that an ingredient is intended to be
2016-10-22 23:56:07 +00:00
//: modified in place, and will help catch accidental misuse of such
//: 'ingredient-products' (sometimes called in-out parameters in other
//: languages).
5001 - drop the :(scenario) DSL I've been saying for a while[1][2][3] that adding extra abstractions makes things harder for newcomers, and adding new notations doubly so. And then I notice this DSL in my own backyard. Makes me feel like a hypocrite. [1] https://news.ycombinator.com/item?id=13565743#13570092 [2] https://lobste.rs/s/to8wpr/configuration_files_are_canary_warning [3] https://lobste.rs/s/mdmcdi/little_languages_by_jon_bentley_1986#c_3miuf2 The implementation of the DSL was also highly hacky: a) It was happening in the tangle/ tool, but was utterly unrelated to tangling layers. b) There were several persnickety constraints on the different kinds of lines and the specific order they were expected in. I kept finding bugs where the translator would silently do the wrong thing. Or the error messages sucked, and readers may be stuck looking at the generated code to figure out what happened. Fixing error messages would require a lot more code, which is one of my arguments against DSLs in the first place: they may be easy to implement, but they're hard to design to go with the grain of the underlying platform. They require lots of iteration. Is that effort worth prioritizing in this project? On the other hand, the DSL did make at least some readers' life easier, the ones who weren't immediately put off by having to learn a strange syntax. There were fewer quotes to parse, fewer backslash escapes. Anyway, since there are also people who dislike having to put up with strange syntaxes, we'll call that consideration a wash and tear this DSL out. --- This commit was sheer drudgery. Hopefully it won't need to be redone with a new DSL because I grow sick of backslashes.
2019-03-13 01:56:55 +00:00
void test_return_same_as_ingredient() {
Hide_errors = true;
run(
"def main [\n"
" 1:num <- copy 0\n"
" 2:num <- test1 1:num # call with different ingredient and product\n"
"]\n"
"def test1 [\n"
" 10:num <- next-ingredient\n"
" return 10:num/same-as-ingredient:0\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"error: main: '2:num <- test1 1:num' should write to '1:num' rather than '2:num'\n"
);
}
5001 - drop the :(scenario) DSL I've been saying for a while[1][2][3] that adding extra abstractions makes things harder for newcomers, and adding new notations doubly so. And then I notice this DSL in my own backyard. Makes me feel like a hypocrite. [1] https://news.ycombinator.com/item?id=13565743#13570092 [2] https://lobste.rs/s/to8wpr/configuration_files_are_canary_warning [3] https://lobste.rs/s/mdmcdi/little_languages_by_jon_bentley_1986#c_3miuf2 The implementation of the DSL was also highly hacky: a) It was happening in the tangle/ tool, but was utterly unrelated to tangling layers. b) There were several persnickety constraints on the different kinds of lines and the specific order they were expected in. I kept finding bugs where the translator would silently do the wrong thing. Or the error messages sucked, and readers may be stuck looking at the generated code to figure out what happened. Fixing error messages would require a lot more code, which is one of my arguments against DSLs in the first place: they may be easy to implement, but they're hard to design to go with the grain of the underlying platform. They require lots of iteration. Is that effort worth prioritizing in this project? On the other hand, the DSL did make at least some readers' life easier, the ones who weren't immediately put off by having to learn a strange syntax. There were fewer quotes to parse, fewer backslash escapes. Anyway, since there are also people who dislike having to put up with strange syntaxes, we'll call that consideration a wash and tear this DSL out. --- This commit was sheer drudgery. Hopefully it won't need to be redone with a new DSL because I grow sick of backslashes.
2019-03-13 01:56:55 +00:00
void test_return_same_as_ingredient_dummy() {
run(
"def main [\n"
" 1:num <- copy 0\n"
" _ <- test1 1:num # call with different ingredient and product\n"
"]\n"
"def test1 [\n"
" 10:num <- next-ingredient\n"
" return 10:num/same-as-ingredient:0\n"
"]\n"
);
CHECK_TRACE_COUNT("error", 0);
}
string to_string(const vector<double>& in) {
2015-03-31 17:56:01 +00:00
if (in.empty()) return "[]";
ostringstream out;
2015-05-17 09:22:41 +00:00
if (SIZE(in) == 1) {
out << no_scientific(in.at(0));
2015-03-31 17:56:01 +00:00
return out.str();
}
out << "[";
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(in); ++i) {
2015-03-31 17:56:01 +00:00
if (i > 0) out << ", ";
out << no_scientific(in.at(i));
2015-03-31 17:56:01 +00:00
}
out << "]";
return out.str();
}