mu/046check_type_by_name.cc

211 lines
6.6 KiB
C++
Raw Normal View History

2015-07-28 22:26:40 +00:00
//: Some simple sanity checks for types, and also attempts to guess them where
//: they aren't provided.
2015-07-29 22:55:05 +00:00
//:
//: You still have to provide the full type the first time you mention a
//: variable in a recipe. You have to explicitly name :offset and :variant
//: every single time. You can't use the same name with multiple types in a
//: single recipe.
2015-07-28 22:26:40 +00:00
:(scenario transform_fails_on_reusing_name_with_different_type)
% Hide_errors = true;
def main [
x:num <- copy 1
2016-09-17 07:46:03 +00:00
x:bool <- copy 1
2015-07-28 22:26:40 +00:00
]
+error: main: 'x' used with multiple types
2015-07-28 22:26:40 +00:00
//: we need surrounding-space info for type-checking variables in other spaces
:(after "Transform.push_back(collect_surrounding_spaces)")
2015-11-29 07:19:45 +00:00
Transform.push_back(check_or_set_types_by_name); // idempotent
2015-07-28 22:26:40 +00:00
// Keep the name->type mapping for all recipes around for the entire
// transformation phase.
:(before "End Globals")
map<recipe_ordinal, set<reagent, name_lt> > Types_by_space; // internal to transform; no need to snapshot
:(before "End Reset")
Types_by_space.clear();
:(before "End transform_all")
Types_by_space.clear();
:(before "End Types")
struct name_lt {
bool operator()(const reagent& a, const reagent& b) const { return a.name < b.name; }
};
2015-07-28 22:26:40 +00:00
:(code)
2015-11-29 07:19:45 +00:00
void check_or_set_types_by_name(const recipe_ordinal r) {
recipe& caller = get(Recipe, r);
trace(9991, "transform") << "--- deduce types for recipe " << caller.name << end();
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller.steps); ++i) {
instruction& inst = caller.steps.at(i);
for (int in = 0; in < SIZE(inst.ingredients); ++in)
check_or_set_type(inst.ingredients.at(in), caller);
for (int out = 0; out < SIZE(inst.products); ++out)
check_or_set_type(inst.products.at(out), caller);
2015-07-28 22:26:40 +00:00
}
}
void check_or_set_type(reagent& curr, const recipe& caller) {
if (is_literal(curr)) return;
if (is_integer(curr.name)) return; // no type-checking for raw locations
set<reagent, name_lt>& known_types = Types_by_space[owning_recipe(curr, caller.ordinal)];
deduce_missing_type(known_types, curr, caller);
check_type(known_types, curr, caller);
}
void deduce_missing_type(set<reagent, name_lt>& known_types, reagent& x, const recipe& caller) {
// Deduce Missing Type(x, caller)
if (x.type) return;
if (is_jump_target(x.name)) {
x.type = new type_tree("label");
return;
}
if (known_types.find(x) == known_types.end()) return;
const reagent& exemplar = *known_types.find(x);
x.type = new type_tree(*exemplar.type);
trace(9992, "transform") << x.name << " <= " << names_to_string(x.type) << end();
// spaces are special; their type includes their /names property
if (is_mu_space(x) && !has_property(x, "names")) {
if (!has_property(exemplar, "names")) {
raise << maybe(caller.name) << "missing /names property for space variable '" << exemplar.name << "'\n" << end();
return;
}
x.properties.push_back(pair<string, string_tree*>("names", new string_tree(*property(exemplar, "names"))));
}
}
void check_type(set<reagent, name_lt>& known_types, const reagent& x, const recipe& caller) {
2015-07-28 22:26:40 +00:00
if (is_literal(x)) return;
2016-01-14 07:20:30 +00:00
if (!x.type) return; // might get filled in by other logic later
if (is_jump_target(x.name)) {
if (!x.type->atom || x.type->name != "label")
raise << maybe(caller.name) << "non-label '" << x.name << "' must begin with a letter\n" << end();
return;
}
if (known_types.find(x) == known_types.end()) {
trace(9992, "transform") << x.name << " => " << names_to_string(x.type) << end();
known_types.insert(x);
}
if (!types_strictly_match(known_types.find(x)->type, x.type)) {
raise << maybe(caller.name) << "'" << x.name << "' used with multiple types\n" << end();
2018-06-25 21:13:19 +00:00
raise << " " << to_string(known_types.find(x)->type) << " vs " << to_string(x.type) << '\n' << end();
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 (is_mu_array(x)) {
if (!x.type->right) {
raise << maybe(caller.name) << "'" << x.name << ": can't be just an array. What is it an array of?\n" << end();
return;
}
if (!x.type->right->right) {
raise << caller.name << " can't determine the size of array variable '" << x.name << "'. Either allocate it separately and make the type of '" << x.name << "' an address, or specify the length of the array in the type of '" << x.name << "'.\n" << end();
return;
}
}
2015-07-28 22:26:40 +00:00
}
recipe_ordinal owning_recipe(const reagent& x, recipe_ordinal r) {
for (int s = space_index(x); s > 0; --s) {
if (!contains_key(Surrounding_space, r)) break; // error raised elsewhere
r = Surrounding_space[r];
}
return r;
}
2015-09-29 04:24:14 +00:00
:(scenario transform_fills_in_missing_types)
def main [
x:num <- copy 11
y:num <- add x, 1
]
# x is in location 2, y in location 3
+mem: storing 12 in location 3
2015-09-29 04:24:14 +00:00
:(scenario transform_fills_in_missing_types_in_product)
def main [
x:num <- copy 11
x <- copy 12
]
# x is in location 2
+mem: storing 12 in location 2
2015-09-29 04:24:14 +00:00
:(scenario transform_fills_in_missing_types_in_product_and_ingredient)
def main [
x:num <- copy 11
x <- add x, 1
]
# x is in location 2
+mem: storing 12 in location 2
:(scenario transform_fills_in_missing_label_type)
def main [
jump +target
1:num <- copy 0
+target
]
-mem: storing 0 in location 1
:(scenario transform_fails_on_missing_types_in_first_mention)
% Hide_errors = true;
def main [
x <- copy 1
x:num <- copy 2
]
+error: main: missing type for 'x' in 'x <- copy 1'
:(scenario transform_fails_on_wrong_type_for_label)
% Hide_errors = true;
def main [
+foo:num <- copy 34
]
+error: main: non-label '+foo' must begin with a letter
:(scenario typo_in_address_type_fails)
% Hide_errors = true;
def main [
2016-09-17 19:55:10 +00:00
y:&:charcter <- new character:type
*y <- copy 67
]
2016-09-17 19:55:10 +00:00
+error: main: unknown type charcter in 'y:&:charcter <- new character:type'
:(scenario array_type_without_size_fails)
% Hide_errors = true;
def main [
2016-09-17 20:00:39 +00:00
x:@:num <- merge 2, 12, 13
]
+error: main can't determine the size of array variable 'x'. Either allocate it separately and make the type of 'x' an address, or specify the length of the array in the type of 'x'.
:(scenarios transform)
:(scenario transform_checks_types_of_identical_reagents_in_multiple_spaces)
def foo [ # dummy
]
def main [
local-scope
2018-06-17 18:20:53 +00:00
0:space/names:foo <- copy null # specify surrounding space
x:bool <- copy true
x:num/space:1 <- copy 34
x/space:1 <- copy 35
]
$error: 0
:(scenario transform_handles_empty_reagents)
% Hide_errors = true;
def main [
add *
]
+error: illegal name '*'
# no crash
:(scenario transform_checks_types_in_surrounding_spaces)
% Hide_errors = true;
# 'x' is a bool in foo's space
def foo [
local-scope
x:bool <- copy false
return default-space/names:foo
]
# try to read 'x' as a num in foo's space
def main [
local-scope
0:space/names:foo <- foo
x:num/space:1 <- copy 34
]
error: foo: 'x' used with multiple types