mu/archive/1.vm/056shape_shifting_recipe.cc

1308 lines
42 KiB
C++
Raw Normal View History

//:: Like container definitions, recipes too can contain type parameters.
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_shape_shifting_recipe() {
run(
"def main [\n"
" 10:point <- merge 14, 15\n"
" 12:point <- foo 10:point\n"
"]\n"
// non-matching variant
"def foo a:num -> result:num [\n"
" local-scope\n"
" load-ingredients\n"
" result <- copy 34\n"
"]\n"
// matching shape-shifting variant
"def foo a:_t -> result:_t [\n"
" local-scope\n"
" load-ingredients\n"
" result <- copy a\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 14 in location 12\n"
"mem: storing 15 in location 13\n"
);
}
//: Before anything else, disable transforms for shape-shifting recipes and
//: make sure we never try to actually run a shape-shifting recipe. We should
//: be rewriting such instructions to *specializations* with the type
//: ingredients filled in.
//: One exception (and this makes things very ugly): we need to expand type
//: abbreviations in shape-shifting recipes because we need them types for
//: deciding which variant to specialize.
:(before "End Transform Checks")
r.transformed_until = t;
if (Transform.at(t) != static_cast<transform_fn>(expand_type_abbreviations) && any_type_ingredient_in_header(/*recipe_ordinal*/p->first)) continue;
:(after "Running One Instruction")
if (Current_routine->calls.front().running_step_index == 0
&& any_type_ingredient_in_header(Current_routine->calls.front().running_recipe)) {
//? DUMP("");
2016-02-26 21:04:55 +00:00
raise << "ran into unspecialized shape-shifting recipe " << current_recipe_name() << '\n' << end();
2016-02-28 02:49:53 +00:00
//? exit(0);
}
//: Make sure we don't match up literals with type ingredients without
//: specialization.
:(before "End Matching Types For Literal(to)")
if (contains_type_ingredient_name(to)) return false;
:(after "Static Dispatch Phase 2")
candidates = strictly_matching_shape_shifting_variants(inst, variants);
if (!candidates.empty()) {
recipe_ordinal exemplar = best_shape_shifting_variant(inst, candidates);
trace(102, "transform") << "found variant to specialize: " << exemplar << ' ' << get(Recipe, exemplar).name << end();
string new_recipe_name = insert_new_variant(exemplar, inst, caller_recipe);
if (new_recipe_name != "") {
trace(102, "transform") << "new specialization: " << new_recipe_name << end();
return new_recipe_name;
}
}
2016-10-22 23:56:07 +00:00
//: before running Mu programs, make sure no unspecialized shape-shifting
//: recipes can be called
:(before "End Instruction Operation Checks")
if (contains_key(Recipe, inst.operation) && !is_primitive(inst.operation)
&& any_type_ingredient_in_header(inst.operation)) {
raise << maybe(caller.name) << "instruction '" << inst.name << "' has no valid specialization\n" << end();
return;
}
:(code)
2016-10-04 15:18:38 +00:00
// phase 3 of static dispatch
vector<recipe_ordinal> strictly_matching_shape_shifting_variants(const instruction& inst, const vector<recipe_ordinal>& variants) {
vector<recipe_ordinal> result;
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(variants); ++i) {
if (variants.at(i) == -1) continue;
if (!any_type_ingredient_in_header(variants.at(i))) continue;
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 (!all_concrete_header_reagents_strictly_match(inst, get(Recipe, variants.at(i)))) continue;
result.push_back(variants.at(i));
}
return result;
}
bool all_concrete_header_reagents_strictly_match(const instruction& inst, const recipe& variant) {
2016-10-20 05:10:35 +00:00
for (int i = 0; i < min(SIZE(inst.ingredients), SIZE(variant.ingredients)); ++i) {
if (!concrete_type_names_strictly_match(variant.ingredients.at(i), inst.ingredients.at(i))) {
trace(103, "transform") << "concrete-type match failed: ingredient " << i << end();
return false;
}
}
2017-12-08 00:01:43 +00:00
for (int i = 0; i < min(SIZE(inst.products), SIZE(variant.products)); ++i) {
if (is_dummy(inst.products.at(i))) continue;
if (!concrete_type_names_strictly_match(variant.products.at(i), inst.products.at(i))) {
trace(103, "transform") << "concrete-type match failed: product " << i << end();
return false;
}
}
return true;
}
// manual prototype
vector<recipe_ordinal> keep_max(const instruction&, const vector<recipe_ordinal>&,
int (*)(const instruction&, recipe_ordinal));
2016-10-04 15:18:38 +00:00
// tie-breaker for phase 3
2017-10-30 19:13:02 +00:00
recipe_ordinal best_shape_shifting_variant(const instruction& inst, const vector<recipe_ordinal>& candidates) {
assert(!candidates.empty());
if (SIZE(candidates) == 1) return candidates.at(0);
//? cerr << "A picking shape-shifting variant:\n";
vector<recipe_ordinal> result1 = keep_max(inst, candidates, number_of_concrete_type_names);
assert(!result1.empty());
if (SIZE(result1) == 1) return result1.at(0);
//? cerr << "B picking shape-shifting variant:\n";
vector<recipe_ordinal> result2 = keep_max(inst, result1, arity_fit);
assert(!result2.empty());
if (SIZE(result2) == 1) return result2.at(0);
//? cerr << "C picking shape-shifting variant:\n";
vector<recipe_ordinal> result3 = keep_max(inst, result2, number_of_type_ingredients);
if (SIZE(result3) > 1) {
raise << "\nCouldn't decide the best shape-shifting variant for instruction '" << to_original_string(inst) << "'\n" << end();
cerr << "This is a hole in Mu. Please copy the following candidates into an email to Kartik Agaram <mu@akkartik.com>\n";
for (int i = 0; i < SIZE(candidates); ++i)
cerr << " " << header_label(get(Recipe, candidates.at(i))) << '\n';
}
return result3.at(0);
}
vector<recipe_ordinal> keep_max(const instruction& inst, const vector<recipe_ordinal>& in,
int (*scorer)(const instruction&, recipe_ordinal)) {
assert(!in.empty());
vector<recipe_ordinal> out;
out.push_back(in.at(0));
int best_score = (*scorer)(inst, in.at(0));
//? cerr << best_score << " " << header_label(get(Recipe, in.at(0))) << '\n';
for (int i = 1; i < SIZE(in); ++i) {
int score = (*scorer)(inst, in.at(i));
//? cerr << score << " " << header_label(get(Recipe, in.at(i))) << '\n';
if (score == best_score) {
out.push_back(in.at(i));
}
else if (score > best_score) {
best_score = score;
out.clear();
out.push_back(in.at(i));
}
}
return out;
}
int arity_fit(const instruction& inst, recipe_ordinal candidate) {
2017-10-30 18:57:44 +00:00
const recipe& r = get(Recipe, candidate);
2017-10-30 19:15:00 +00:00
return (SIZE(inst.products) - SIZE(r.products))
+ (SIZE(r.ingredients) - SIZE(inst.ingredients));
2017-10-30 18:57:44 +00:00
}
bool any_type_ingredient_in_header(recipe_ordinal variant) {
const recipe& caller = get(Recipe, variant);
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller.ingredients); ++i) {
if (contains_type_ingredient_name(caller.ingredients.at(i)))
return true;
}
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller.products); ++i) {
if (contains_type_ingredient_name(caller.products.at(i)))
return true;
}
return false;
}
2016-05-06 07:46:39 +00:00
bool concrete_type_names_strictly_match(reagent/*copy*/ to, reagent/*copy*/ from) {
canonize_type(to);
canonize_type(from);
return concrete_type_names_strictly_match(to.type, from.type, from);
}
bool concrete_type_names_strictly_match(const type_tree* to, const type_tree* from, const reagent& rhs_reagent) {
if (!to) return !from;
if (!from) return !to;
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 (to->atom && is_type_ingredient_name(to->name)) return true; // type ingredient matches anything
3663 - fix a refcounting bug: '(type)' != 'type' This was a large commit, and most of it is a follow-up to commit 3309, undoing what is probably the final ill-considered optimization I added to s-expressions in Mu: I was always representing (a b c) as (a b . c), etc. That is now gone. Why did I need to take it out? The key problem was the error silently ignored in layer 30. That was causing size_of("(type)") to silently return garbage rather than loudly complain (assuming 'type' was a simple type). But to take it out I had to modify types_strictly_match (layer 21) to actually strictly match and not just do a prefix match. In the process of removing the prefix match, I had to make extracting recipe types from recipe headers more robust. So far it only matched the first element of each ingredient's type; these matched: (recipe address:number -> address:number) (recipe address -> address) I didn't notice because the dotted notation optimization was actually representing this as: (recipe address:number -> address number) --- One final little thing in this commit: I added an alias for 'assert' called 'assert_for_now', to indicate that I'm not sure something's really an invariant, that it might be triggered by (invalid) user programs, and so require more thought on error handling down the road. But this may well be an ill-posed distinction. It may be overwhelmingly uneconomic to continually distinguish between model invariants and error states for input. I'm starting to grow sympathetic to Google Analytics's recent approach of just banning assertions altogether. We'll see..
2016-11-11 05:39:02 +00:00
if (!to->atom && to->right == NULL && to->left != NULL && to->left->atom && is_type_ingredient_name(to->left->name)) return true;
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 (from->atom && is_mu_address(to))
2018-06-17 18:20:53 +00:00
return from->name == "literal-address" && rhs_reagent.name == "null";
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 (!from->atom && !to->atom)
return concrete_type_names_strictly_match(to->left, from->left, rhs_reagent)
&& concrete_type_names_strictly_match(to->right, from->right, rhs_reagent);
if (from->atom != to->atom) return false;
// both from and to are atoms
if (from->name == "literal")
return Literal_type_names.find(to->name) != Literal_type_names.end();
if (to->name == "literal")
return Literal_type_names.find(from->name) != Literal_type_names.end();
return to->name == from->name;
}
bool contains_type_ingredient_name(const reagent& x) {
return contains_type_ingredient_name(x.type);
}
bool contains_type_ingredient_name(const type_tree* type) {
if (!type) return false;
if (is_type_ingredient_name(type->name)) return true;
return contains_type_ingredient_name(type->left) || contains_type_ingredient_name(type->right);
}
int number_of_concrete_type_names(const instruction& /*unused*/, recipe_ordinal r) {
2016-11-10 22:30:31 +00:00
const recipe& caller = get(Recipe, r);
int result = 0;
for (int i = 0; i < SIZE(caller.ingredients); ++i)
2017-10-30 18:52:43 +00:00
result += number_of_concrete_type_names(caller.ingredients.at(i).type);
2016-11-10 22:30:31 +00:00
for (int i = 0; i < SIZE(caller.products); ++i)
2017-10-30 18:52:43 +00:00
result += number_of_concrete_type_names(caller.products.at(i).type);
2016-11-10 22:30:31 +00:00
return result;
}
int number_of_concrete_type_names(const type_tree* type) {
if (!type) return 0;
if (type->atom)
return is_type_ingredient_name(type->name) ? 0 : 1;
return number_of_concrete_type_names(type->left)
+ number_of_concrete_type_names(type->right);
}
int number_of_type_ingredients(const instruction& /*unused*/, recipe_ordinal r) {
const recipe& caller = get(Recipe, r);
int result = 0;
for (int i = 0; i < SIZE(caller.ingredients); ++i)
result += number_of_type_ingredients(caller.ingredients.at(i).type);
for (int i = 0; i < SIZE(caller.products); ++i)
result += number_of_type_ingredients(caller.products.at(i).type);
return result;
}
int number_of_type_ingredients(const type_tree* type) {
if (!type) return 0;
if (type->atom)
return is_type_ingredient_name(type->name) ? 1 : 0;
return number_of_type_ingredients(type->left)
+ number_of_type_ingredients(type->right);
}
// returns name of new variant
string insert_new_variant(recipe_ordinal exemplar, const instruction& inst, const recipe& caller_recipe) {
string new_name = next_unused_recipe_name(inst.name);
assert(!contains_key(Recipe_ordinal, new_name));
recipe_ordinal new_recipe_ordinal = put(Recipe_ordinal, new_name, Next_recipe_ordinal++);
// make a copy
assert(contains_key(Recipe, exemplar));
assert(!contains_key(Recipe, new_recipe_ordinal));
2017-12-07 10:01:39 +00:00
put(Recipe, new_recipe_ordinal, /*copy*/get(Recipe, exemplar));
recipe& new_recipe = get(Recipe, new_recipe_ordinal);
new_recipe.name = new_name;
2018-06-25 21:13:19 +00:00
new_recipe.ordinal = new_recipe_ordinal;
2016-05-27 16:50:39 +00:00
new_recipe.is_autogenerated = true;
trace(103, "transform") << "switching " << inst.name << " to specialized " << header_label(new_recipe) << end();
trace(102, "transform") << "transforming new specialization: " << new_recipe.name << end();
trace(102, "transform") << new_recipe.name << ": performing transforms until check_or_set_types_by_name" << end();
2017-12-07 10:01:39 +00:00
int transform_index = 0;
for (transform_index = 0; transform_index < SIZE(Transform); ++transform_index) {
if (Transform.at(transform_index) == check_or_set_types_by_name) break;
(*Transform.at(transform_index))(new_recipe_ordinal);
}
new_recipe.transformed_until = transform_index-1;
trace(102, "transform") << new_recipe.name << ": performing type-ingredient-aware version of transform check_or_set_types_by_name" << end();
compute_type_names(new_recipe);
2017-12-07 10:01:39 +00:00
new_recipe.transformed_until++;
trace(102, "transform") << new_recipe.name << ": replacing type ingredients" << end();
2015-11-10 07:02:23 +00:00
{
map<string, const type_tree*> mappings;
bool error = false;
compute_type_ingredient_mappings(get(Recipe, exemplar), inst, mappings, caller_recipe, &error);
if (!error) error = (SIZE(mappings) != type_ingredient_count_in_header(exemplar));
if (!error) replace_type_ingredients(new_recipe, mappings);
2016-10-20 05:10:35 +00:00
for (map<string, const type_tree*>::iterator p = mappings.begin(); p != mappings.end(); ++p)
2015-11-10 07:02:23 +00:00
delete p->second;
if (error) return "";
2015-11-10 07:02:23 +00:00
}
ensure_all_concrete_types(new_recipe, get(Recipe, exemplar));
2017-12-07 10:01:39 +00:00
trace(102, "transform") << new_recipe.name << ": recording the new variant before recursively calling resolve_ambiguous_calls" << end();
get(Recipe_variants, inst.name).push_back(new_recipe_ordinal);
trace(102, "transform") << new_recipe.name << ": performing remaining transforms (including resolve_ambiguous_calls)" << end();
2017-12-07 10:01:39 +00:00
for (/*nada*/; transform_index < SIZE(Transform); ++transform_index)
(*Transform.at(transform_index))(new_recipe_ordinal);
new_recipe.transformed_until = SIZE(Transform)-1;
return new_recipe.name;
}
void compute_type_names(recipe& variant) {
trace(103, "transform") << "-- compute type names: " << variant.name << end();
map<string, type_tree*> type_names;
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(variant.ingredients); ++i)
2016-06-10 01:14:27 +00:00
save_or_deduce_type_name(variant.ingredients.at(i), type_names, variant, "");
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(variant.products); ++i)
2016-06-10 01:14:27 +00:00
save_or_deduce_type_name(variant.products.at(i), type_names, variant, "");
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(variant.steps); ++i) {
instruction& inst = variant.steps.at(i);
trace(103, "transform") << " instruction: " << to_string(inst) << end();
2016-10-20 05:10:35 +00:00
for (int in = 0; in < SIZE(inst.ingredients); ++in)
2017-05-26 23:43:18 +00:00
save_or_deduce_type_name(inst.ingredients.at(in), type_names, variant, " in '" + to_original_string(inst) + "'");
2016-10-20 05:10:35 +00:00
for (int out = 0; out < SIZE(inst.products); ++out)
2017-05-26 23:43:18 +00:00
save_or_deduce_type_name(inst.products.at(out), type_names, variant, " in '" + to_original_string(inst) + "'");
}
}
2016-06-10 01:14:27 +00:00
void save_or_deduce_type_name(reagent& x, map<string, type_tree*>& type, const recipe& variant, const string& context) {
trace(104, "transform") << " checking " << to_string(x) << ": " << names_to_string(x.type) << end();
if (!x.type && contains_key(type, x.name)) {
2016-05-17 22:43:07 +00:00
x.type = new type_tree(*get(type, x.name));
trace(104, "transform") << " deducing type to " << names_to_string(x.type) << end();
return;
}
// Type Check in Type-ingredient-aware check_or_set_types_by_name
2017-12-07 10:01:39 +00:00
// This is different from check_or_set_types_by_name.
// We've found it useful in the past for tracking down bugs in
// specialization.
if (!x.type) {
2016-06-10 01:14:27 +00:00
raise << maybe(variant.original_name) << "unknown type for '" << x.original_string << "'" << context << " (check the name for typos)\n" << end();
return;
}
if (contains_key(type, x.name)) return;
if (x.type->name == "offset" || x.type->name == "variant") return; // special-case for container-access instructions
put(type, x.name, x.type);
trace(103, "transform") << "type of '" << x.name << "' is " << names_to_string(x.type) << end();
}
void compute_type_ingredient_mappings(const recipe& exemplar, const instruction& inst, map<string, const type_tree*>& mappings, const recipe& caller_recipe, bool* error) {
int limit = min(SIZE(inst.ingredients), SIZE(exemplar.ingredients));
2016-10-20 05:10:35 +00:00
for (int i = 0; i < limit; ++i) {
2015-11-11 04:14:50 +00:00
const reagent& exemplar_reagent = exemplar.ingredients.at(i);
2016-05-06 07:46:39 +00:00
reagent/*copy*/ ingredient = inst.ingredients.at(i);
canonize_type(ingredient);
2018-06-17 18:20:53 +00:00
if (is_mu_address(exemplar_reagent) && ingredient.name == "null") continue; // assume it matches
2015-11-11 04:14:50 +00:00
accumulate_type_ingredients(exemplar_reagent, ingredient, mappings, exemplar, inst, caller_recipe, error);
}
limit = min(SIZE(inst.products), SIZE(exemplar.products));
2016-10-20 05:10:35 +00:00
for (int i = 0; i < limit; ++i) {
2015-11-11 04:14:50 +00:00
const reagent& exemplar_reagent = exemplar.products.at(i);
2016-05-06 07:46:39 +00:00
reagent/*copy*/ product = inst.products.at(i);
if (is_dummy(product)) continue;
canonize_type(product);
2015-11-11 04:14:50 +00:00
accumulate_type_ingredients(exemplar_reagent, product, mappings, exemplar, inst, caller_recipe, error);
}
}
void accumulate_type_ingredients(const reagent& exemplar_reagent, reagent& refinement, map<string, const type_tree*>& mappings, const recipe& exemplar, const instruction& call_instruction, const recipe& caller_recipe, bool* error) {
assert(refinement.type);
accumulate_type_ingredients(exemplar_reagent.type, refinement.type, mappings, exemplar, exemplar_reagent, call_instruction, caller_recipe, error);
}
void accumulate_type_ingredients(const type_tree* exemplar_type, const type_tree* refinement_type, map<string, const type_tree*>& mappings, const recipe& exemplar, const reagent& exemplar_reagent, const instruction& call_instruction, const recipe& caller_recipe, bool* error) {
2015-11-11 04:14:50 +00:00
if (!exemplar_type) return;
if (!refinement_type) {
2016-10-24 06:10:49 +00:00
// probably a bug in mu
2016-02-25 16:24:14 +00:00
// todo: make this smarter; only flag an error if exemplar_type contains some *new* type ingredient
raise << maybe(exemplar.name) << "missing type ingredient for " << exemplar_reagent.original_string << '\n' << end();
2017-05-26 23:43:18 +00:00
raise << " (called from '" << to_original_string(call_instruction) << "')\n" << end();
2015-11-05 08:57:23 +00:00
return;
}
3663 - fix a refcounting bug: '(type)' != 'type' This was a large commit, and most of it is a follow-up to commit 3309, undoing what is probably the final ill-considered optimization I added to s-expressions in Mu: I was always representing (a b c) as (a b . c), etc. That is now gone. Why did I need to take it out? The key problem was the error silently ignored in layer 30. That was causing size_of("(type)") to silently return garbage rather than loudly complain (assuming 'type' was a simple type). But to take it out I had to modify types_strictly_match (layer 21) to actually strictly match and not just do a prefix match. In the process of removing the prefix match, I had to make extracting recipe types from recipe headers more robust. So far it only matched the first element of each ingredient's type; these matched: (recipe address:number -> address:number) (recipe address -> address) I didn't notice because the dotted notation optimization was actually representing this as: (recipe address:number -> address number) --- One final little thing in this commit: I added an alias for 'assert' called 'assert_for_now', to indicate that I'm not sure something's really an invariant, that it might be triggered by (invalid) user programs, and so require more thought on error handling down the road. But this may well be an ill-posed distinction. It may be overwhelmingly uneconomic to continually distinguish between model invariants and error states for input. I'm starting to grow sympathetic to Google Analytics's recent approach of just banning assertions altogether. We'll see..
2016-11-11 05:39:02 +00:00
if (!exemplar_type->atom && exemplar_type->right == NULL && !refinement_type->atom && refinement_type->right != NULL) {
exemplar_type = exemplar_type->left;
assert_for_now(exemplar_type->atom);
}
if (exemplar_type->atom) {
if (is_type_ingredient_name(exemplar_type->name)) {
const type_tree* curr_refinement_type = NULL; // temporary heap allocation; must always be deleted before it goes out of scope
if (exemplar_type->atom)
curr_refinement_type = new type_tree(*refinement_type);
else {
assert(!refinement_type->atom);
curr_refinement_type = new type_tree(*refinement_type->left);
}
if (!contains_key(mappings, exemplar_type->name)) {
trace(103, "transform") << "adding mapping from " << exemplar_type->name << " to " << to_string(curr_refinement_type) << end();
2016-02-28 02:49:53 +00:00
put(mappings, exemplar_type->name, new type_tree(*curr_refinement_type));
}
else {
if (!deeply_equal_type_names(get(mappings, exemplar_type->name), curr_refinement_type)) {
2017-05-26 23:43:18 +00:00
raise << maybe(caller_recipe.name) << "no call found for '" << to_original_string(call_instruction) << "'\n" << end();
*error = true;
delete curr_refinement_type;
return;
}
if (get(mappings, exemplar_type->name)->name == "literal") {
delete get(mappings, exemplar_type->name);
put(mappings, exemplar_type->name, new type_tree(*curr_refinement_type));
}
}
delete curr_refinement_type;
}
}
else {
2015-11-11 04:14:50 +00:00
accumulate_type_ingredients(exemplar_type->left, refinement_type->left, mappings, exemplar, exemplar_reagent, call_instruction, caller_recipe, error);
accumulate_type_ingredients(exemplar_type->right, refinement_type->right, mappings, exemplar, exemplar_reagent, call_instruction, caller_recipe, error);
}
}
void replace_type_ingredients(recipe& new_recipe, const map<string, const type_tree*>& mappings) {
// update its header
if (mappings.empty()) return;
trace(103, "transform") << "replacing in recipe header ingredients" << end();
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(new_recipe.ingredients); ++i)
replace_type_ingredients(new_recipe.ingredients.at(i), mappings, new_recipe);
trace(103, "transform") << "replacing in recipe header products" << end();
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(new_recipe.products); ++i)
replace_type_ingredients(new_recipe.products.at(i), mappings, new_recipe);
// update its body
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(new_recipe.steps); ++i) {
instruction& inst = new_recipe.steps.at(i);
trace(103, "transform") << "replacing in instruction '" << to_string(inst) << "'" << end();
2016-10-20 05:10:35 +00:00
for (int j = 0; j < SIZE(inst.ingredients); ++j)
replace_type_ingredients(inst.ingredients.at(j), mappings, new_recipe);
2016-10-20 05:10:35 +00:00
for (int j = 0; j < SIZE(inst.products); ++j)
replace_type_ingredients(inst.products.at(j), mappings, new_recipe);
// special-case for new: replace type ingredient in first ingredient *value*
if (inst.name == "new" && inst.ingredients.at(0).type->name != "literal-string") {
type_tree* type = parse_type_tree(inst.ingredients.at(0).name);
replace_type_ingredients(type, mappings);
inst.ingredients.at(0).name = inspect(type);
delete type;
}
}
}
void replace_type_ingredients(reagent& x, const map<string, const type_tree*>& mappings, const recipe& caller) {
string before = to_string(x);
trace(103, "transform") << "replacing in ingredient " << x.original_string << end();
if (!x.type) {
raise << "specializing " << caller.original_name << ": missing type for '" << x.original_string << "'\n" << end();
return;
}
replace_type_ingredients(x.type, mappings);
}
void replace_type_ingredients(type_tree* type, const map<string, const type_tree*>& mappings) {
if (!type) return;
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 (!type->atom) {
3663 - fix a refcounting bug: '(type)' != 'type' This was a large commit, and most of it is a follow-up to commit 3309, undoing what is probably the final ill-considered optimization I added to s-expressions in Mu: I was always representing (a b c) as (a b . c), etc. That is now gone. Why did I need to take it out? The key problem was the error silently ignored in layer 30. That was causing size_of("(type)") to silently return garbage rather than loudly complain (assuming 'type' was a simple type). But to take it out I had to modify types_strictly_match (layer 21) to actually strictly match and not just do a prefix match. In the process of removing the prefix match, I had to make extracting recipe types from recipe headers more robust. So far it only matched the first element of each ingredient's type; these matched: (recipe address:number -> address:number) (recipe address -> address) I didn't notice because the dotted notation optimization was actually representing this as: (recipe address:number -> address number) --- One final little thing in this commit: I added an alias for 'assert' called 'assert_for_now', to indicate that I'm not sure something's really an invariant, that it might be triggered by (invalid) user programs, and so require more thought on error handling down the road. But this may well be an ill-posed distinction. It may be overwhelmingly uneconomic to continually distinguish between model invariants and error states for input. I'm starting to grow sympathetic to Google Analytics's recent approach of just banning assertions altogether. We'll see..
2016-11-11 05:39:02 +00:00
if (type->right == NULL && type->left != NULL && type->left->atom && contains_key(mappings, type->left->name) && !get(mappings, type->left->name)->atom && get(mappings, type->left->name)->right != NULL) {
*type = *get(mappings, type->left->name);
return;
}
2016-02-28 02:49:53 +00:00
replace_type_ingredients(type->left, mappings);
replace_type_ingredients(type->right, mappings);
return;
}
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 (contains_key(Type_ordinal, type->name)) // todo: ugly side effect
type->value = get(Type_ordinal, type->name);
if (!contains_key(mappings, type->name))
return;
2016-02-28 02:49:53 +00:00
const type_tree* replacement = get(mappings, type->name);
trace(103, "transform") << type->name << " => " << names_to_string(replacement) << end();
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 (replacement->atom) {
if (!contains_key(Type_ordinal, replacement->name)) {
// error in program; should be reported elsewhere
return;
}
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
type->name = (replacement->name == "literal") ? "number" : replacement->name;
type->value = get(Type_ordinal, type->name);
2016-02-28 02:49:53 +00:00
}
else {
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
*type = *replacement;
}
}
2015-11-01 00:18:59 +00:00
int type_ingredient_count_in_header(recipe_ordinal variant) {
const recipe& caller = get(Recipe, variant);
set<string> type_ingredients;
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller.ingredients); ++i)
accumulate_type_ingredients(caller.ingredients.at(i).type, type_ingredients);
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller.products); ++i)
accumulate_type_ingredients(caller.products.at(i).type, type_ingredients);
return SIZE(type_ingredients);
}
void accumulate_type_ingredients(const type_tree* type, set<string>& out) {
if (!type) return;
if (is_type_ingredient_name(type->name)) out.insert(type->name);
accumulate_type_ingredients(type->left, out);
accumulate_type_ingredients(type->right, out);
}
type_tree* parse_type_tree(const string& s) {
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
string_tree* s2 = parse_string_tree(s);
type_tree* result = new_type_tree(s2);
delete s2;
return result;
}
string inspect(const type_tree* x) {
2016-02-21 04:44:59 +00:00
ostringstream out;
dump_inspect(x, out);
return out.str();
}
void dump_inspect(const type_tree* x, ostream& out) {
2016-02-21 04:44:59 +00:00
if (!x->left && !x->right) {
out << x->name;
2016-02-21 04:44:59 +00:00
return;
}
out << '(';
2016-10-20 05:10:35 +00:00
for (const type_tree* curr = x; curr; curr = curr->right) {
2016-02-21 04:44:59 +00:00
if (curr != x) out << ' ';
if (curr->left)
dump_inspect(curr->left, out);
else
out << curr->name;
2016-02-21 04:44:59 +00:00
}
out << ')';
}
void ensure_all_concrete_types(/*const*/ recipe& new_recipe, const recipe& exemplar) {
trace(103, "transform") << "-- ensure all concrete types in recipe " << new_recipe.name << end();
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(new_recipe.ingredients); ++i)
ensure_all_concrete_types(new_recipe.ingredients.at(i), exemplar);
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(new_recipe.products); ++i)
ensure_all_concrete_types(new_recipe.products.at(i), exemplar);
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(new_recipe.steps); ++i) {
instruction& inst = new_recipe.steps.at(i);
2016-10-20 05:10:35 +00:00
for (int j = 0; j < SIZE(inst.ingredients); ++j)
ensure_all_concrete_types(inst.ingredients.at(j), exemplar);
2016-10-20 05:10:35 +00:00
for (int j = 0; j < SIZE(inst.products); ++j)
ensure_all_concrete_types(inst.products.at(j), exemplar);
}
}
void ensure_all_concrete_types(/*const*/ reagent& x, const recipe& exemplar) {
2016-02-22 04:40:14 +00:00
if (!x.type || contains_type_ingredient_name(x.type)) {
2016-02-26 21:04:55 +00:00
raise << maybe(exemplar.name) << "failed to map a type to " << x.original_string << '\n' << end();
2017-12-07 10:01:39 +00:00
if (!x.type) x.type = new type_tree("added_by_ensure_all_concrete_types", 0); // just to prevent crashes later
return;
}
if (x.type->value == -1) {
2016-02-26 21:04:55 +00:00
raise << maybe(exemplar.name) << "failed to map a type to the unknown " << x.original_string << '\n' << end();
return;
}
}
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_shape_shifting_recipe_2() {
run(
"def main [\n"
" 10:point <- merge 14, 15\n"
" 12:point <- foo 10:point\n"
"]\n"
// non-matching shape-shifting variant
"def foo a:_t, b:_t -> result:num [\n"
" local-scope\n"
" load-ingredients\n"
" result <- copy 34\n"
"]\n"
// matching shape-shifting variant
"def foo a:_t -> result:_t [\n"
" local-scope\n"
" load-ingredients\n"
" result <- copy a\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 14 in location 12\n"
"mem: storing 15 in location 13\n"
);
}
void test_shape_shifting_recipe_nonroot() {
run(
"def main [\n"
" 10:foo:point <- merge 14, 15, 16\n"
" 20:point <- bar 10:foo:point\n"
"]\n"
// shape-shifting recipe with type ingredient following some other type
"def bar a:foo:_t -> result:_t [\n"
" local-scope\n"
" load-ingredients\n"
" result <- get a, x:offset\n"
"]\n"
"container foo:_t [\n"
" x:_t\n"
" y:num\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 14 in location 20\n"
"mem: storing 15 in location 21\n"
);
}
void test_shape_shifting_recipe_nested() {
run(
"container c:_a:_b [\n"
" a:_a\n"
" b:_b\n"
"]\n"
"def main [\n"
" s:text <- new [abc]\n"
" {x: (c (address array character) number)} <- merge s, 34\n"
" foo x\n"
"]\n"
"def foo x:c:_bar:_baz [\n"
" local-scope\n"
" load-ingredients\n"
"]\n"
);
// no errors
}
void test_shape_shifting_recipe_type_deduction_ignores_offsets() {
run(
"def main [\n"
" 10:foo:point <- merge 14, 15, 16\n"
" 20:point <- bar 10:foo:point\n"
"]\n"
"def bar a:foo:_t -> result:_t [\n"
" local-scope\n"
" load-ingredients\n"
" x:num <- copy 1\n"
" result <- get a, x:offset # shouldn't collide with other variable\n"
"]\n"
"container foo:_t [\n"
" x:_t\n"
" y:num\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 14 in location 20\n"
"mem: storing 15 in location 21\n"
);
}
void test_shape_shifting_recipe_empty() {
run(
"def main [\n"
" foo 1\n"
"]\n"
// shape-shifting recipe with no body
"def foo a:_t [\n"
"]\n"
);
// shouldn't crash
}
void test_shape_shifting_recipe_handles_shape_shifting_new_ingredient() {
run(
"def main [\n"
" 1:&:foo:point <- bar 3\n"
" 11:foo:point <- copy *1:&:foo:point\n"
"]\n"
"container foo:_t [\n"
" x:_t\n"
" y:num\n"
"]\n"
"def bar x:num -> result:&:foo:_t [\n"
" local-scope\n"
" load-ingredients\n"
// new refers to _t in its ingredient *value*
" result <- new {(foo _t) : type}\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 0 in location 11\n"
"mem: storing 0 in location 12\n"
"mem: storing 0 in location 13\n"
);
}
void test_shape_shifting_recipe_handles_shape_shifting_new_ingredient_2() {
run(
"def main [\n"
" 1:&:foo:point <- bar 3\n"
" 11:foo:point <- copy *1:&:foo:point\n"
"]\n"
"def bar x:num -> result:&:foo:_t [\n"
" local-scope\n"
" load-ingredients\n"
// new refers to _t in its ingredient *value*
" result <- new {(foo _t) : type}\n"
"]\n"
// container defined after use
"container foo:_t [\n"
" x:_t\n"
" y:num\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 0 in location 11\n"
"mem: storing 0 in location 12\n"
"mem: storing 0 in location 13\n"
);
}
void test_shape_shifting_recipe_called_with_dummy() {
run(
"def main [\n"
" _ <- bar 34\n"
"]\n"
"def bar x:_t -> result:&:_t [\n"
" local-scope\n"
" load-ingredients\n"
" result <- copy null\n"
"]\n"
);
CHECK_TRACE_COUNT("error", 0);
}
// this one needs a little more fine-grained control
void test_shape_shifting_new_ingredient_does_not_pollute_global_namespace() {
// if you specialize a shape-shifting recipe that allocates a type-ingredient..
transform("def barz x:_elem [\n"
" local-scope\n"
" load-ingredients\n"
2016-09-17 19:55:10 +00:00
" y:&:num <- new _elem:type\n"
"]\n"
"def fooz [\n"
" local-scope\n"
" barz 34\n"
"]\n");
// ..and if you then try to load a new shape-shifting container with that
// type-ingredient
run("container foo:_elem [\n"
" x:_elem\n"
2016-09-17 17:28:25 +00:00
" y:num\n"
"]\n");
// then it should work as usual
reagent callsite("x:foo:point");
2016-04-30 17:09:38 +00:00
reagent element = element_type(callsite.type, 0);
CHECK_EQ(element.name, "x");
CHECK_EQ(element.type->name, "point");
CHECK(!element.type->right);
}
3663 - fix a refcounting bug: '(type)' != 'type' This was a large commit, and most of it is a follow-up to commit 3309, undoing what is probably the final ill-considered optimization I added to s-expressions in Mu: I was always representing (a b c) as (a b . c), etc. That is now gone. Why did I need to take it out? The key problem was the error silently ignored in layer 30. That was causing size_of("(type)") to silently return garbage rather than loudly complain (assuming 'type' was a simple type). But to take it out I had to modify types_strictly_match (layer 21) to actually strictly match and not just do a prefix match. In the process of removing the prefix match, I had to make extracting recipe types from recipe headers more robust. So far it only matched the first element of each ingredient's type; these matched: (recipe address:number -> address:number) (recipe address -> address) I didn't notice because the dotted notation optimization was actually representing this as: (recipe address:number -> address number) --- One final little thing in this commit: I added an alias for 'assert' called 'assert_for_now', to indicate that I'm not sure something's really an invariant, that it might be triggered by (invalid) user programs, and so require more thought on error handling down the road. But this may well be an ill-posed distinction. It may be overwhelmingly uneconomic to continually distinguish between model invariants and error states for input. I'm starting to grow sympathetic to Google Analytics's recent approach of just banning assertions altogether. We'll see..
2016-11-11 05:39:02 +00:00
//: specializing a type ingredient with a compound type
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_shape_shifting_recipe_supports_compound_types() {
run(
"def main [\n"
" 1:&:point <- new point:type\n"
" *1:&:point <- put *1:&:point, y:offset, 34\n"
" 3:&:point <- bar 1:&:point # specialize _t to address:point\n"
" 5:point <- copy *3:&:point\n"
"]\n"
"def bar a:_t -> result:_t [\n"
" local-scope\n"
" load-ingredients\n"
" result <- copy a\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 6\n"
);
}
3663 - fix a refcounting bug: '(type)' != 'type' This was a large commit, and most of it is a follow-up to commit 3309, undoing what is probably the final ill-considered optimization I added to s-expressions in Mu: I was always representing (a b c) as (a b . c), etc. That is now gone. Why did I need to take it out? The key problem was the error silently ignored in layer 30. That was causing size_of("(type)") to silently return garbage rather than loudly complain (assuming 'type' was a simple type). But to take it out I had to modify types_strictly_match (layer 21) to actually strictly match and not just do a prefix match. In the process of removing the prefix match, I had to make extracting recipe types from recipe headers more robust. So far it only matched the first element of each ingredient's type; these matched: (recipe address:number -> address:number) (recipe address -> address) I didn't notice because the dotted notation optimization was actually representing this as: (recipe address:number -> address number) --- One final little thing in this commit: I added an alias for 'assert' called 'assert_for_now', to indicate that I'm not sure something's really an invariant, that it might be triggered by (invalid) user programs, and so require more thought on error handling down the road. But this may well be an ill-posed distinction. It may be overwhelmingly uneconomic to continually distinguish between model invariants and error states for input. I'm starting to grow sympathetic to Google Analytics's recent approach of just banning assertions altogether. We'll see..
2016-11-11 05:39:02 +00:00
//: specializing a type ingredient with a compound type -- while *inside* another compound type
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_shape_shifting_recipe_supports_compound_types_2() {
run(
"container foo:_t [\n"
" value:_t\n"
"]\n"
"def bar x:&:foo:_t -> result:_t [\n"
" local-scope\n"
" load-ingredients\n"
" result <- get *x, value:offset\n"
"]\n"
"def main [\n"
" 1:&:foo:&:point <- new {(foo address point): type}\n"
" 2:&:point <- bar 1:&:foo:&:point\n"
"]\n"
);
// no errors; call to 'bar' successfully specialized
}
void test_shape_shifting_recipe_error() {
Hide_errors = true;
run(
"def main [\n"
" a:num <- copy 3\n"
" b:&:num <- foo a\n"
"]\n"
"def foo a:_t -> b:_t [\n"
" load-ingredients\n"
" b <- copy a\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"error: main: no call found for 'b:&:num <- foo a'\n"
);
}
void test_specialize_inside_recipe_without_header() {
run(
"def main [\n"
" foo 3\n"
"]\n"
"def foo [\n"
" local-scope\n"
" x:num <- next-ingredient # ensure no header\n"
" 1:num/raw <- bar x # call a shape-shifting recipe\n"
"]\n"
"def bar x:_elem -> y:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" y <- add x, 1\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 4 in location 1\n"
);
}
void test_specialize_with_literal() {
run(
"def main [\n"
" local-scope\n"
// permit literal to map to number
" 1:num/raw <- foo 3\n"
"]\n"
"def foo x:_elem -> y:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" y <- add x, 1\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 4 in location 1\n"
);
}
void test_specialize_with_literal_2() {
run(
"def main [\n"
" local-scope\n"
// permit literal to map to character
" 1:char/raw <- foo 3\n"
"]\n"
"def foo x:_elem -> y:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" y <- add x, 1\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 4 in location 1\n"
);
}
void test_specialize_with_literal_3() {
run(
"def main [\n"
" local-scope\n"
// permit '0' to map to address to shape-shifting type-ingredient
" 1:&:char/raw <- foo null\n"
"]\n"
"def foo x:&:_elem -> y:&:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" y <- copy x\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 0 in location 1\n"
);
CHECK_TRACE_COUNT("error", 0);
}
void test_specialize_with_literal_4() {
Hide_errors = true;
run(
"def main [\n"
" local-scope\n"
// ambiguous call: what's the type of its ingredient?!
" foo 0\n"
"]\n"
"def foo x:&:_elem -> y:&:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" y <- copy x\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"error: main: instruction 'foo' has no valid specialization\n"
);
}
void test_specialize_with_literal_5() {
run(
"def main [\n"
" foo 3, 4\n" // recipe mapping two variables to literals
"]\n"
"def foo x:_elem, y:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" 1:num/raw <- add x, y\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 7 in location 1\n"
);
}
void test_multiple_shape_shifting_variants() {
run(
// try to call two different shape-shifting recipes with the same name
"def main [\n"
" e1:d1:num <- merge 3\n"
" e2:d2:num <- merge 4, 5\n"
" 1:num/raw <- foo e1\n"
" 2:num/raw <- foo e2\n"
"]\n"
// the two shape-shifting definitions
"def foo a:d1:_elem -> b:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 34\n"
"]\n"
"def foo a:d2:_elem -> b:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 35\n"
"]\n"
// the shape-shifting containers they use
"container d1:_elem [\n"
" x:_elem\n"
"]\n"
"container d2:_elem [\n"
" x:num\n"
" y:_elem\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 1\n"
"mem: storing 35 in location 2\n"
);
}
void test_multiple_shape_shifting_variants_2() {
run(
// static dispatch between shape-shifting variants, _including pointer lookups_
"def main [\n"
" e1:d1:num <- merge 3\n"
" e2:&:d2:num <- new {(d2 number): type}\n"
" 1:num/raw <- foo e1\n"
" 2:num/raw <- foo *e2\n" // different from previous scenario
"]\n"
"def foo a:d1:_elem -> b:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 34\n"
"]\n"
"def foo a:d2:_elem -> b:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 35\n"
"]\n"
"container d1:_elem [\n"
" x:_elem\n"
"]\n"
"container d2:_elem [\n"
" x:num\n"
" y:_elem\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 1\n"
"mem: storing 35 in location 2\n"
);
}
void test_missing_type_in_shape_shifting_recipe() {
Hide_errors = true;
run(
"def main [\n"
" a:d1:num <- merge 3\n"
" foo a\n"
"]\n"
"def foo a:d1:_elem -> b:num [\n"
" local-scope\n"
" load-ingredients\n"
" copy e\n" // no such variable
" return 34\n"
"]\n"
"container d1:_elem [\n"
" x:_elem\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"error: foo: unknown type for 'e' in 'copy e' (check the name for typos)\n"
"error: specializing foo: missing type for 'e'\n"
);
// and it doesn't crash
}
void test_missing_type_in_shape_shifting_recipe_2() {
Hide_errors = true;
run(
"def main [\n"
" a:d1:num <- merge 3\n"
" foo a\n"
"]\n"
"def foo a:d1:_elem -> b:num [\n"
" local-scope\n"
" load-ingredients\n"
" get e, x:offset\n" // unknown variable in a 'get', which does some extra checking
" return 34\n"
"]\n"
"container d1:_elem [\n"
" x:_elem\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"error: foo: unknown type for 'e' in 'get e, x:offset' (check the name for typos)\n"
"error: specializing foo: missing type for 'e'\n"
);
// and it doesn't crash
}
void test_specialize_recursive_shape_shifting_recipe() {
transform(
"def main [\n"
" 1:num <- copy 34\n"
" 2:num <- foo 1:num\n"
"]\n"
"def foo x:_elem -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" {\n"
" break\n"
" y:num <- foo x\n"
" }\n"
" return y\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"transform: new specialization: foo_2\n"
);
// transform terminates
}
void test_specialize_most_similar_variant() {
run(
"def main [\n"
" 1:&:num <- new number:type\n"
" 10:num <- foo 1:&:num\n"
"]\n"
"def foo x:_elem -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 34\n"
"]\n"
"def foo x:&:_elem -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 35\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 35 in location 10\n"
);
}
void test_specialize_most_similar_variant_2() {
run(
// version with headers padded with lots of unrelated concrete types
"def main [\n"
" 1:num <- copy 23\n"
" 2:&:@:num <- copy null\n"
" 4:num <- foo 2:&:@:num, 1:num\n"
"]\n"
// variant with concrete type
"def foo dummy:&:@:num, x:num -> y:num, dummy:&:@:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 34\n"
"]\n"
// shape-shifting variant
"def foo dummy:&:@:num, x:_elem -> y:num, dummy:&:@:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 35\n"
"]\n"
);
// prefer the concrete variant
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 4\n"
);
}
void test_specialize_most_similar_variant_3() {
run(
"def main [\n"
" 1:text <- new [abc]\n"
" foo 1:text\n"
"]\n"
"def foo x:text [\n"
" 10:num <- copy 34\n"
"]\n"
"def foo x:&:_elem [\n"
" 10:num <- copy 35\n"
"]\n"
);
// make sure the more precise version was used
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 10\n"
);
}
void test_specialize_literal_as_number() {
run(
"def main [\n"
" 1:num <- foo 23\n"
"]\n"
"def foo x:_elem -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 34\n"
"]\n"
"def foo x:char -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 35\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 1\n"
);
}
void test_specialize_literal_as_number_2() {
run(
// version calling with literal
"def main [\n"
" 1:num <- foo 0\n"
"]\n"
// variant with concrete type
"def foo x:num -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 34\n"
"]\n"
// shape-shifting variant
"def foo x:&:_elem -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 35\n"
"]\n"
);
// prefer the concrete variant, ignore concrete types in scoring the shape-shifting variant
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 1\n"
);
}
void test_specialize_literal_as_address() {
run(
"def main [\n"
" 1:num <- foo null\n"
"]\n"
// variant with concrete address type
"def foo x:&:num -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 34\n"
"]\n"
// shape-shifting variant
"def foo x:&:_elem -> y:num [\n"
" local-scope\n"
" load-ingredients\n"
" return 35\n"
"]\n"
);
// prefer the concrete variant, ignore concrete types in scoring the shape-shifting variant
CHECK_TRACE_CONTENTS(
"mem: storing 34 in location 1\n"
);
}
void test_missing_type_during_specialization() {
Hide_errors = true;
run(
// define a shape-shifting recipe
"def foo a:_elem [\n"
"]\n"
// define a container with field 'z'
"container foo2 [\n"
" z:num\n"
"]\n"
"def main [\n"
" local-scope\n"
" x:foo2 <- merge 34\n"
" y:num <- get x, z:offse # typo in 'offset'\n"
// define a variable with the same name 'z'
" z:num <- copy 34\n"
" foo z\n"
"]\n"
);
// shouldn't crash
}
void test_missing_type_during_specialization2() {
Hide_errors = true;
run(
// define a shape-shifting recipe
"def foo a:_elem [\n"
"]\n"
// define a container with field 'z'
"container foo2 [\n"
" z:num\n"
"]\n"
"def main [\n"
" local-scope\n"
" x:foo2 <- merge 34\n"
" y:num <- get x, z:offse # typo in 'offset'\n"
// define a variable with the same name 'z'
" z:&:num <- copy 34\n"
// trigger specialization of the shape-shifting recipe
" foo *z\n"
"]\n"
);
// shouldn't crash
}
void test_tangle_shape_shifting_recipe() {
run(
// shape-shifting recipe
"def foo a:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" <label1>\n"
"]\n"
// tangle some code that refers to the type ingredient
"after <label1> [\n"
" b:_elem <- copy a\n"
"]\n"
// trigger specialization
"def main [\n"
" local-scope\n"
" foo 34\n"
"]\n"
);
CHECK_TRACE_COUNT("error", 0);
}
void test_tangle_shape_shifting_recipe_with_type_abbreviation() {
run(
// shape-shifting recipe
"def foo a:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" <label1>\n"
"]\n"
// tangle some code that refers to the type ingredient
"after <label1> [\n"
" b:bool <- copy false\n" // type abbreviation
"]\n"
// trigger specialization
"def main [\n"
" local-scope\n"
" foo 34\n"
"]\n"
);
CHECK_TRACE_COUNT("error", 0);
}
void test_shape_shifting_recipe_coexists_with_primitive() {
run(
// recipe overloading a primitive with a generic type
"def add a:&:foo:_elem [\n"
" assert 0, [should not get here]\n"
"]\n"
"def main [\n"
// call primitive add with literal 0
" add 0, 0\n"
"]\n"
);
CHECK_TRACE_COUNT("error", 0);
}
void test_specialization_heuristic_test_1() {
run(
// modeled on the 'buffer' container in text.mu
"container foo_buffer:_elem [\n"
" x:num\n"
"]\n"
"def main [\n"
" append 1:&:foo_buffer:char/raw, 2:text/raw\n"
"]\n"
"def append buf:&:foo_buffer:_elem, x:_elem -> buf:&:foo_buffer:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" stash 34\n"
"]\n"
"def append buf:&:foo_buffer:char, x:_elem -> buf:&:foo_buffer:char [\n"
" local-scope\n"
" load-ingredients\n"
" stash 35\n"
"]\n"
"def append buf:&:foo_buffer:_elem, x:&:@:_elem -> buf:&:foo_buffer:_elem [\n"
" local-scope\n"
" load-ingredients\n"
" stash 36\n"
"]\n"
);
CHECK_TRACE_CONTENTS(
"app: 36\n"
);
}