mu/042name.cc

344 lines
12 KiB
C++
Raw Normal View History

2015-03-19 05:44:04 +00:00
//: A big convenience high-level languages provide is the ability to name memory
2016-10-22 23:56:07 +00:00
//: locations. In Mu, a transform called 'transform_names' provides this
2015-03-19 05:44:04 +00:00
//: convenience.
2015-07-28 22:31:01 +00:00
:(scenario transform_names)
def main [
x:num <- copy 0
2015-03-19 05:44:04 +00:00
]
+name: assign x 2
+mem: storing 0 in location 2
2015-03-19 05:44:04 +00:00
:(scenarios transform)
:(scenario transform_names_fails_on_use_before_define)
% Hide_errors = true;
def main [
x:num <- copy y:num
2015-04-04 16:39:35 +00:00
]
+error: main: tried to read ingredient 'y' in 'x:num <- copy y:num' but it hasn't been written to yet
# todo: detect conditional defines
2015-04-04 16:39:35 +00:00
:(after "End Type Modifying Transforms")
Transform.push_back(transform_names); // idempotent
2015-03-19 05:44:04 +00:00
:(before "End Globals")
map<recipe_ordinal, map<string, int> > Name;
//: the Name map is a global, so save it before tests and reset it for every
//: test, just to be safe.
:(before "End Globals")
map<recipe_ordinal, map<string, int> > Name_snapshot;
:(before "End save_snapshots")
Name_snapshot = Name;
:(before "End restore_snapshots")
Name = Name_snapshot;
2015-03-19 05:44:04 +00:00
:(code)
void transform_names(const recipe_ordinal r) {
2015-11-29 07:58:43 +00:00
recipe& caller = get(Recipe, r);
trace(9991, "transform") << "--- transform names for recipe " << caller.name << end();
bool names_used = false;
bool numeric_locations_used = false;
map<string, int>& names = Name[r];
2018-06-25 17:59:20 +00:00
// record the indices 'used' so far in the map
int& curr_idx = names[""];
2018-06-25 17:59:20 +00:00
// reserve indices 0 and 1 for the chaining slot in a later layer.
// transform_names may get called multiple times in later layers, so
// curr_idx may already be set.
if (curr_idx < 2) curr_idx = 2;
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(caller.steps); ++i) {
2015-11-29 07:58:43 +00:00
instruction& inst = caller.steps.at(i);
2015-10-29 18:56:10 +00:00
// End transform_names(inst) Special-cases
2015-03-27 17:20:17 +00:00
// map names to addresses
2016-10-20 05:10:35 +00:00
for (int in = 0; in < SIZE(inst.ingredients); ++in) {
2016-08-25 17:11:04 +00:00
reagent& ingredient = inst.ingredients.at(in);
if (is_disqualified(ingredient, inst, caller.name)) continue;
if (is_numeric_location(ingredient)) numeric_locations_used = true;
if (is_named_location(ingredient)) names_used = true;
if (is_integer(ingredient.name)) continue;
if (!already_transformed(ingredient, names)) {
raise << maybe(caller.name) << "tried to read ingredient '" << ingredient.name << "' in '" << to_original_string(inst) << "' but it hasn't been written to yet\n" << end();
// use-before-set Error
2016-07-03 18:12:48 +00:00
return;
2015-03-19 05:44:04 +00:00
}
2016-08-25 17:11:04 +00:00
int v = lookup_name(ingredient, r);
if (v >= 0) {
2016-08-25 17:11:04 +00:00
ingredient.set_value(v);
// Done Placing Ingredient(ingredient, inst, caller)
}
else {
2016-08-25 17:11:04 +00:00
raise << maybe(caller.name) << "can't find a place to store '" << ingredient.name << "'\n" << end();
return;
}
2015-03-19 05:44:04 +00:00
}
2016-10-20 05:10:35 +00:00
for (int out = 0; out < SIZE(inst.products); ++out) {
2016-08-25 17:11:04 +00:00
reagent& product = inst.products.at(out);
if (is_disqualified(product, inst, caller.name)) continue;
if (is_numeric_location(product)) numeric_locations_used = true;
if (is_named_location(product)) names_used = true;
if (is_integer(product.name)) continue;
if (names.find(product.name) == names.end()) {
trace(9993, "name") << "assign " << product.name << " " << curr_idx << end();
names[product.name] = curr_idx;
curr_idx += size_of(product);
2015-03-19 05:44:04 +00:00
}
2016-08-25 17:11:04 +00:00
int v = lookup_name(product, r);
if (v >= 0) {
2016-08-25 17:11:04 +00:00
product.set_value(v);
// Done Placing Product(product, inst, caller)
}
else {
2016-08-25 17:11:04 +00:00
raise << maybe(caller.name) << "can't find a place to store '" << product.name << "'\n" << end();
return;
}
2015-03-19 05:44:04 +00:00
}
}
2015-08-16 05:27:47 +00:00
if (names_used && numeric_locations_used)
2016-02-26 21:04:55 +00:00
raise << maybe(caller.name) << "mixing variable names and numeric addresses\n" << end();
}
2016-01-30 05:58:00 +00:00
bool is_disqualified(/*mutable*/ reagent& x, const instruction& inst, const string& recipe_name) {
if (!x.type) {
2017-05-26 23:43:18 +00:00
raise << maybe(recipe_name) << "missing type for '" << x.original_string << "' in '" << to_original_string(inst) << "'\n" << end();
// missing-type Error 1
2015-07-24 04:48:06 +00:00
return true;
}
if (is_raw(x)) return true;
2015-06-17 19:39:09 +00:00
if (is_literal(x)) return true;
// End is_disqualified Special-cases
if (x.initialized) return true;
return false;
2015-03-19 05:44:04 +00:00
}
2015-03-21 03:27:01 +00:00
bool already_transformed(const reagent& r, const map<string, int>& names) {
return contains_key(names, r.name);
}
int lookup_name(const reagent& r, const recipe_ordinal default_recipe) {
return Name[default_recipe][r.name];
}
type_ordinal skip_addresses(type_tree* type) {
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
while (type && is_compound_type_starting_with(type, "address"))
type = type->right;
if (!type) return -1; // error handled elsewhere
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->atom) return type->value;
const type_tree* base_type = type;
// Update base_type in skip_addresses
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 (base_type->atom)
return base_type->value;
assert(base_type->left->atom);
return base_type->left->value;
}
bool is_compound_type_starting_with(const type_tree* type, const string& expected_name) {
if (!type) return false;
if (type->atom) return false;
if (!type->left->atom) return false;
return type->left->value == get(Type_ordinal, expected_name);
}
int find_element_offset(const type_ordinal t, const string& name, const string& recipe_name) {
const type_info& container = get(Type, t);
2016-10-20 05:10:35 +00:00
for (int i = 0; i < SIZE(container.elements); ++i)
if (container.elements.at(i).name == name) return i;
raise << maybe(recipe_name) << "unknown element '" << name << "' in container '" << get(Type, t).name << "'\n" << end();
return -1;
}
int find_element_location(int base_address, const string& name, const type_tree* type, const string& recipe_name) {
int offset = find_element_offset(get_base_type(type)->value, name, recipe_name);
if (offset == -1) return offset;
int result = base_address;
for (int i = 0; i < offset; ++i)
result += size_of(element_type(type, i));
return result;
}
bool is_numeric_location(const reagent& x) {
2015-06-17 19:39:09 +00:00
if (is_literal(x)) return false;
if (is_raw(x)) return false;
if (x.name == "0") return false; // used for chaining lexical scopes
2015-05-17 04:24:21 +00:00
return is_integer(x.name);
}
bool is_named_location(const reagent& x) {
2015-06-17 19:39:09 +00:00
if (is_literal(x)) return false;
if (is_raw(x)) return false;
if (is_special_name(x.name)) return false;
2015-05-17 04:24:21 +00:00
return !is_integer(x.name);
}
2016-05-27 16:50:39 +00:00
// all names here should either be disqualified or also in bind_special_scenario_names
bool is_special_name(const string& s) {
if (s == "_") return true;
if (s == "0") return true;
// End is_special_name Special-cases
return false;
}
bool is_raw(const reagent& r) {
return has_property(r, "raw");
}
:(scenario transform_names_supports_containers)
def main [
x:point <- merge 34, 35
y:num <- copy 3
]
+name: assign x 2
# skip location 2 because x occupies two locations
+name: assign y 4
:(scenario transform_names_supports_static_arrays)
def main [
2016-09-17 20:00:39 +00:00
x:@:num:3 <- create-array
y:num <- copy 3
]
+name: assign x 2
# skip locations 2, 3, 4 because x occupies four locations
+name: assign y 6
2015-07-28 22:31:01 +00:00
:(scenario transform_names_passes_dummy)
2015-03-21 03:27:01 +00:00
# _ is just a dummy result that never gets consumed
def main [
_, x:num <- copy 0, 1
2015-03-21 03:27:01 +00:00
]
+name: assign x 2
-name: assign _ 2
2015-03-21 03:33:16 +00:00
//: an escape hatch to suppress name conversion that we'll use later
:(scenarios run)
2015-07-28 22:31:01 +00:00
:(scenario transform_names_passes_raw)
% Hide_errors = true;
def main [
x:num/raw <- copy 0
]
-name: assign x 2
+error: can't write to location 0 in 'x:num/raw <- copy 0'
:(scenarios transform)
:(scenario transform_names_fails_when_mixing_names_and_numeric_locations)
% Hide_errors = true;
def main [
x:num <- copy 1:num
]
+error: main: mixing variable names and numeric addresses
:(scenario transform_names_fails_when_mixing_names_and_numeric_locations_2)
% Hide_errors = true;
def main [
x:num <- copy 1
1:num <- copy x:num
]
+error: main: mixing variable names and numeric addresses
:(scenario transform_names_does_not_fail_when_mixing_names_and_raw_locations)
def main [
x:num <- copy 1:num/raw
]
-error: main: mixing variable names and numeric addresses
$error: 0
:(scenario transform_names_does_not_fail_when_mixing_names_and_literals)
def main [
x:num <- copy 1
]
-error: main: mixing variable names and numeric addresses
$error: 0
//:: Support element names for containers in 'get' and 'get-location' and 'put'.
//: (get-location is implemented later)
:(before "End update GET offset_value in Check")
else {
if (!offset.initialized) {
2017-05-26 23:43:18 +00:00
raise << maybe(get(Recipe, r).name) << "uninitialized offset '" << offset.name << "' in '" << to_original_string(inst) << "'\n" << end();
break;
}
offset_value = offset.value;
}
2015-07-28 22:31:01 +00:00
:(scenario transform_names_transforms_container_elements)
def main [
2018-06-17 18:20:53 +00:00
p:&:point <- copy null
2016-09-17 19:55:10 +00:00
a:num <- get *p:&:point, y:offset
b:num <- get *p:&:point, x:offset
]
+name: element y of type point is at offset 1
+name: element x of type point is at offset 0
2015-03-21 04:33:32 +00:00
2015-10-29 18:56:10 +00:00
:(before "End transform_names(inst) Special-cases")
// replace element names of containers with offsets
if (inst.name == "get" || inst.name == "get-location" || inst.name == "put") {
//: avoid raising any errors here; later layers will support overloading new
//: instructions with the same names (static dispatch), which could lead to
//: spurious errors
if (SIZE(inst.ingredients) < 2)
break; // error raised elsewhere
2015-06-25 07:19:37 +00:00
if (!is_literal(inst.ingredients.at(1)))
break; // error raised elsewhere
if (inst.ingredients.at(1).name.find_first_not_of("0123456789") != string::npos) {
// since first non-address in base type must be a container, we don't have to canonize
type_ordinal base_type = skip_addresses(inst.ingredients.at(0).type);
2015-11-17 19:25:00 +00:00
if (contains_key(Type, base_type)) { // otherwise we'll raise an error elsewhere
inst.ingredients.at(1).set_value(find_element_offset(base_type, inst.ingredients.at(1).name, get(Recipe, r).name));
2015-11-17 19:25:00 +00:00
trace(9993, "name") << "element " << inst.ingredients.at(1).name << " of type " << get(Type, base_type).name << " is at offset " << no_scientific(inst.ingredients.at(1).value) << end();
}
}
2015-03-27 17:20:17 +00:00
}
:(scenario missing_type_in_get)
% Hide_errors = true;
def main [
get a, x:offset
]
+error: main: missing type for 'a' in 'get a, x:offset'
2015-07-28 22:31:01 +00:00
:(scenario transform_names_handles_containers)
def main [
a:point <- merge 0, 0
b:num <- copy 0
2015-03-21 04:33:32 +00:00
]
+name: assign a 2
+name: assign b 4
//:: Support variant names for exclusive containers in 'maybe-convert'.
:(scenarios run)
2015-07-28 22:31:01 +00:00
:(scenario transform_names_handles_exclusive_containers)
def main [
12:num <- copy 1
13:num <- copy 35
14:num <- copy 36
2016-09-17 07:46:03 +00:00
20:point, 22:bool <- maybe-convert 12:number-or-point/unsafe, p:variant
]
+name: variant p of type number-or-point has tag 1
+mem: storing 1 in location 22
+mem: storing 35 in location 20
+mem: storing 36 in location 21
2015-10-29 18:56:10 +00:00
:(before "End transform_names(inst) Special-cases")
// convert variant names of exclusive containers
if (inst.name == "maybe-convert") {
if (SIZE(inst.ingredients) != 2) {
2017-05-26 23:43:18 +00:00
raise << maybe(get(Recipe, r).name) << "exactly 2 ingredients expected in '" << to_original_string(inst) << "'\n" << end();
break;
}
2015-06-17 19:39:09 +00:00
assert(is_literal(inst.ingredients.at(1)));
if (inst.ingredients.at(1).name.find_first_not_of("0123456789") != string::npos) {
// since first non-address in base type must be an exclusive container, we don't have to canonize
type_ordinal base_type = skip_addresses(inst.ingredients.at(0).type);
2015-11-17 19:25:00 +00:00
if (contains_key(Type, base_type)) { // otherwise we'll raise an error elsewhere
inst.ingredients.at(1).set_value(find_element_offset(base_type, inst.ingredients.at(1).name, get(Recipe, r).name));
2015-11-17 19:25:00 +00:00
trace(9993, "name") << "variant " << inst.ingredients.at(1).name << " of type " << get(Type, base_type).name << " has tag " << no_scientific(inst.ingredients.at(1).value) << end();
}
}
}
:(scenario missing_type_in_maybe_convert)
% Hide_errors = true;
def main [
maybe-convert a, x:variant
]
+error: main: missing type for 'a' in 'maybe-convert a, x:variant'