1 //: Exclusive containers contain exactly one of a fixed number of 'variants'
  2 //: of different types.
  3 //:
  4 //: They also implicitly contain a tag describing precisely which variant is
  5 //: currently stored in them.
  6 
  7 :(before "End Mu Types Initialization")
  8 //: We'll use this container as a running example, with two number elements.
  9 {
 10 type_ordinal tmp = put(Type_ordinal, "number-or-point", Next_type_ordinal++);
 11 get_or_insert(Type, tmp);  // initialize
 12 get(Type, tmp).kind = EXCLUSIVE_CONTAINER;
 13 get(Type, tmp).name = "number-or-point";
 14 get(Type, tmp).elements.push_back(reagent("i:number"));
 15 get(Type, tmp).elements.push_back(reagent("p:point"));
 16 }
 17 
 18 //: Tests in this layer often explicitly set up memory before reading it as an
 19 //: array. Don't do this in general. I'm tagging exceptions with /raw to keep
 20 //: checks in future layers from flagging them.
 21 :(scenario copy_exclusive_container)
 22 # Copying exclusive containers copies all their contents and an extra location for the tag.
 23 def main [
 24   1:num <- copy 1  # 'point' variant
 25   2:num <- copy 34
 26   3:num <- copy 35
 27   4:number-or-point <- copy 1:number-or-point/unsafe
 28 ]
 29 +mem: storing 1 in location 4
 30 +mem: storing 34 in location 5
 31 +mem: storing 35 in location 6
 32 
 33 :(before "End size_of(type) Special-cases")
 34 if (t.kind == EXCLUSIVE_CONTAINER) {
 35   // Compute size_of Exclusive Container
 36   return get(Container_metadata, type).size;
 37 }
 38 :(before "End compute_container_sizes Atom Special-cases")
 39 if (info.kind == EXCLUSIVE_CONTAINER) {
 40   compute_exclusive_container_sizes(info, type, pending_metadata, location_for_error_messages);
 41 }
 42 
 43 :(code)
 44 void compute_exclusive_container_sizes(const type_info& exclusive_container_info, const type_tree* full_type, set<type_tree>& pending_metadata, const string& location_for_error_messages) {
 45   // size of an exclusive container is the size of its largest variant
 46   // (So, like containers, it can only contain arrays if they're static and
 47   // include their length in the type.)
 48   container_metadata metadata;
 49   for (int i = 0;  i < SIZE(exclusive_container_info.elements);  ++i) {
 50   ¦ reagent/*copy*/ element = exclusive_container_info.elements.at(i);
 51   ¦ // Compute Exclusive Container Size(element, full_type)
 52   ¦ compute_container_sizes(element.type, pending_metadata, location_for_error_messages);
 53   ¦ int variant_size = size_of(element);
 54   ¦ if (variant_size > metadata.size) metadata.size = variant_size;
 55   }
 56   // ...+1 for its tag.
 57   ++metadata.size;
 58   Container_metadata.push_back(pair<type_tree*, container_metadata>(new type_tree(*full_type), metadata));
 59 }
 60 
 61 //:: To access variants of an exclusive container, use 'maybe-convert'.
 62 //: It always returns an address (so that you can modify it) or null (to
 63 //: signal that the conversion failed (because the container contains a
 64 //: different variant).
 65 
 66 //: 'maybe-convert' requires a literal in ingredient 1. We'll use a synonym
 67 //: called 'variant'.
 68 :(before "End Mu Types Initialization")
 69 put(Type_ordinal, "variant", 0);
 70 
 71 :(scenario maybe_convert)
 72 def main [
 73   12:num <- copy 1
 74   13:num <- copy 35
 75   14:num <- copy 36
 76   20:point, 22:bool <- maybe-convert 12:number-or-point/unsafe, 1:variant
 77 ]
 78 # boolean
 79 +mem: storing 1 in location 22
 80 # point
 81 +mem: storing 35 in location 20
 82 +mem: storing 36 in location 21
 83 
 84 :(scenario maybe_convert_fail)
 85 def main [
 86   12:num <- copy 1
 87   13:num <- copy 35
 88   14:num <- copy 36
 89   20:num, 21:bool <- maybe-convert 12:number-or-point/unsafe, 0:variant
 90 ]
 91 # boolean
 92 +mem: storing 0 in location 21
 93 # number: no write
 94 
 95 :(before "End Primitive Recipe Declarations")
 96 MAYBE_CONVERT,
 97 :(before "End Primitive Recipe Numbers")
 98 put(Recipe_ordinal, "maybe-convert", MAYBE_CONVERT);
 99 :(before "End Primitive Recipe Checks")
100 case MAYBE_CONVERT: {
101   const recipe& caller = get(Recipe, r);
102   if (SIZE(inst.ingredients) != 2) {
103   ¦ raise << maybe(caller.name) << "'maybe-convert' expects exactly 2 ingredients in '" << to_original_string(inst) << "'\n" << end();
104   ¦ break;
105   }
106   reagent/*copy*/ base = inst.ingredients.at(0);
107   // Update MAYBE_CONVERT base in Check
108   if (!base.type) {
109   ¦ raise << maybe(caller.name) << "first ingredient of 'maybe-convert' should be an exclusive-container, but got '" << base.original_string << "'\n" << end();
110   ¦ break;
111   }
112   const type_tree* base_type = base.type;
113   // Update MAYBE_CONVERT base_type in Check
114   if (!base_type->atom || base_type->value == 0 || !contains_key(Type, base_type->value) || get(Type, base_type->value).kind != EXCLUSIVE_CONTAINER) {
115   ¦ raise << maybe(caller.name) << "first ingredient of 'maybe-convert' should be an exclusive-container, but got '" << base.original_string << "'\n" << end();
116   ¦ break;
117   }
118   if (!is_literal(inst.ingredients.at(1))) {
119   ¦ raise << maybe(caller.name) << "second ingredient of 'maybe-convert' should have type 'variant', but got '" << inst.ingredients.at(1).original_string << "'\n" << end();
120   ¦ break;
121   }
122   if (inst.products.empty()) break;
123   if (SIZE(inst.products) != 2) {
124   ¦ raise << maybe(caller.name) << "'maybe-convert' expects exactly 2 products in '" << to_original_string(inst) << "'\n" << end();
125   ¦ break;
126   }
127   reagent/*copy*/ product = inst.products.at(0);
128   // Update MAYBE_CONVERT product in Check
129   reagent& offset = inst.ingredients.at(1);
130   populate_value(offset);
131   if (offset.value >= SIZE(get(Type, base_type->value).elements)) {
132   ¦ raise << maybe(caller.name) << "invalid tag " << offset.value << " in '" << to_original_string(inst) << '\n' << end();
133   ¦ break;
134   }
135   const reagent& variant = variant_type(base, offset.value);
136   if (!types_coercible(product, variant)) {
137   ¦ raise << maybe(caller.name) << "'maybe-convert " << base.original_string << ", " << inst.ingredients.at(1).original_string << "' should write to " << to_string(variant.type) << " but '" << product.name << "' has type " << to_string(product.type) << '\n' << end();
138   ¦ break;
139   }
140   reagent/*copy*/ status = inst.products.at(1);
141   // Update MAYBE_CONVERT status in Check
142   if (!is_mu_boolean(status)) {
143   ¦ raise << maybe(get(Recipe, r).name) << "second product yielded by 'maybe-convert' should be a boolean, but tried to write to '" << inst.products.at(1).original_string << "'\n" << end();
144   ¦ break;
145   }
146   break;
147 }
148 :(before "End Primitive Recipe Implementations")
149 case MAYBE_CONVERT: {
150   reagent/*copy*/ base = current_instruction().ingredients.at(0);
151   // Update MAYBE_CONVERT base in Run
152   int base_address = base.value;
153   if (base_address == 0) {
154   ¦ raise << maybe(current_recipe_name()) << "tried to access location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
155   ¦ break;
156   }
157   int tag = current_instruction().ingredients.at(1).value;
158   reagent/*copy*/ product = current_instruction().products.at(0);
159   // Update MAYBE_CONVERT product in Run
160   reagent/*copy*/ status = current_instruction().products.at(1);
161   // Update MAYBE_CONVERT status in Run
162   // optimization: directly write results to only update first product when necessary
163   write_products = false;
164   if (tag == static_cast<int>(get_or_insert(Memory, base_address))) {
165   ¦ const reagent& variant = variant_type(base, tag);
166   ¦ trace("mem") << "storing 1 in location " << status.value << end();
167   ¦ put(Memory, status.value, 1);
168   ¦ if (!is_dummy(product)) {
169   ¦ ¦ // Write Memory in Successful MAYBE_CONVERT in Run
170   ¦ ¦ for (int i = 0;  i < size_of(variant);  ++i) {
171   ¦ ¦ ¦ double val = get_or_insert(Memory, base_address+/*skip tag*/1+i);
172   ¦ ¦ ¦ trace("mem") << "storing " << no_scientific(val) << " in location " << product.value+i << end();
173   ¦ ¦ ¦ put(Memory, product.value+i, val);
174   ¦ ¦ }
175   ¦ }
176   }
177   else {
178   ¦ trace("mem") << "storing 0 in location " << status.value << end();
179   ¦ put(Memory, status.value, 0);
180   }
181   break;
182 }
183 
184 :(code)
185 const reagent variant_type(const reagent& base, int tag) {
186   return variant_type(base.type, tag);
187 }
188 
189 const reagent variant_type(const type_tree* type, int tag) {
190   assert(tag >= 0);
191   const type_tree* root_type = type->atom ? type : type->left;
192   assert(contains_key(Type, root_type->value));
193   assert(!get(Type, root_type->value).name.empty());
194   const type_info& info = get(Type, root_type->value);
195   assert(info.kind == EXCLUSIVE_CONTAINER);
196   reagent/*copy*/ element = info.elements.at(tag);
197   // End variant_type Special-cases
198   return element;
199 }
200 
201 :(scenario maybe_convert_product_type_mismatch)
202 % Hide_errors = true;
203 def main [
204   12:num <- copy 1
205   13:num <- copy 35
206   14:num <- copy 36
207   20:num, 21:bool <- maybe-convert 12:number-or-point/unsafe, 1:variant
208 ]
209 +error: main: 'maybe-convert 12:number-or-point/unsafe, 1:variant' should write to point but '20' has type number
210 
211 :(scenario maybe_convert_dummy_product)
212 def main [
213   12:num <- copy 1
214   13:num <- copy 35
215   14:num <- copy 36
216   _, 21:bool <- maybe-convert 12:number-or-point/unsafe, 1:variant
217 ]
218 $error: 0
219 
220 //:: Allow exclusive containers to be defined in Mu code.
221 
222 :(scenario exclusive_container)
223 exclusive-container foo [
224   x:num
225   y:num
226 ]
227 +parse: --- defining exclusive-container foo
228 +parse: element: {x: "number"}
229 +parse: element: {y: "number"}
230 
231 :(before "End Command Handlers")
232 else if (command == "exclusive-container") {
233   insert_container(command, EXCLUSIVE_CONTAINER, in);
234 }
235 
236 //: arrays are disallowed inside exclusive containers unless their length is
237 //: fixed in advance
238 
239 :(scenario exclusive_container_contains_array)
240 exclusive-container foo [
241   x:array:num:3
242 ]
243 $error: 0
244 
245 :(scenario exclusive_container_disallows_dynamic_array_element)
246 % Hide_errors = true;
247 exclusive-container foo [
248   x:array:num
249 ]
250 +error: container 'foo' cannot determine size of element 'x'
251 
252 //:: To construct exclusive containers out of variant types, use 'merge'.
253 :(scenario lift_to_exclusive_container)
254 exclusive-container foo [
255   x:num
256   y:num
257 ]
258 def main [
259   1:num <- copy 34
260   2:foo <- merge 0/x, 1:num  # tag must be a literal when merging exclusive containers
261   4:foo <- merge 1/y, 1:num
262 ]
263 +mem: storing 0 in location 2
264 +mem: storing 34 in location 3
265 +mem: storing 1 in location 4
266 +mem: storing 34 in location 5
267 
268 //: type-checking for 'merge' on exclusive containers
269 
270 :(scenario merge_handles_exclusive_container)
271 exclusive-container foo [
272   x:num
273   y:bar
274 ]
275 container bar [
276   z:num
277 ]
278 def main [
279   1:foo <- merge 0/x, 34
280 ]
281 +mem: storing 0 in location 1
282 +mem: storing 34 in location 2
283 $error: 0
284 
285 :(scenario merge_requires_literal_tag_for_exclusive_container)
286 % Hide_errors = true;
287 exclusive-container foo [
288   x:num
289   y:bar
290 ]
291 container bar [
292   z:num
293 ]
294 def main [
295   1:num <- copy 0
296   2:foo <- merge 1:num, 34
297 ]
298 +error: main: ingredient 0 of 'merge' should be a literal, for the tag of exclusive-container 'foo' in '2:foo <- merge 1:num, 34'
299 
300 :(scenario merge_handles_exclusive_container_inside_exclusive_container)
301 exclusive-container foo [
302   x:num
303   y:bar
304 ]
305 exclusive-container bar [
306   a:num
307   b:num
308 ]
309 def main [
310   1:num <- copy 0
311   2:bar <- merge 0/a, 34
312   4:foo <- merge 1/y, 2:bar
313 ]
314 +mem: storing 0 in location 5
315 +mem: storing 34 in location 6
316 $error: 0
317 
318 :(before "End check_merge_call Special-cases")
319 case EXCLUSIVE_CONTAINER: {
320   assert(state.data.top().container_element_index == 0);
321   trace("transform") << "checking exclusive container " << to_string(container) << " vs ingredient " << ingredient_index << end();
322   // easy case: exact match
323   if (types_strictly_match(container, inst.ingredients.at(ingredient_index)))
324   ¦ return;
325   if (!is_literal(ingredients.at(ingredient_index))) {
326   ¦ raise << maybe(caller.name) << "ingredient " << ingredient_index << " of 'merge' should be a literal, for the tag of exclusive-container '" << container_info.name << "' in '" << to_original_string(inst) << "'\n" << end();
327   ¦ return;
328   }
329   reagent/*copy*/ ingredient = ingredients.at(ingredient_index);  // unnecessary copy just to keep this function from modifying caller
330   populate_value(ingredient);
331   if (ingredient.value >= SIZE(container_info.elements)) {
332   ¦ raise << maybe(caller.name) << "invalid tag at " << ingredient_index << " for '" << container_info.name << "' in '" << to_original_string(inst) << "'\n" << end();
333   ¦ return;
334   }
335   const reagent& variant = variant_type(container, ingredient.value);
336   trace("transform") << "tag: " << ingredient.value << end();
337   // replace union with its variant
338   state.data.pop();
339   state.data.push(merge_check_point(variant, 0));
340   ++ingredient_index;
341   break;
342 }
343 
344 :(scenario merge_check_container_containing_exclusive_container)
345 container foo [
346   x:num
347   y:bar
348 ]
349 exclusive-container bar [
350   x:num
351   y:num
352 ]
353 def main [
354   1:foo <- merge 23, 1/y, 34
355 ]
356 +mem: storing 23 in location 1
357 +mem: storing 1 in location 2
358 +mem: storing 34 in location 3
359 $error: 0
360 
361 :(scenario merge_check_container_containing_exclusive_container_2)
362 % Hide_errors = true;
363 container foo [
364   x:num
365   y:bar
366 ]
367 exclusive-container bar [
368   x:num
369   y:num
370 ]
371 def main [
372   1:foo <- merge 23, 1/y, 34, 35
373 ]
374 +error: main: too many ingredients in '1:foo <- merge 23, 1/y, 34, 35'
375 
376 :(scenario merge_check_exclusive_container_containing_container)
377 exclusive-container foo [
378   x:num
379   y:bar
380 ]
381 container bar [
382   x:num
383   y:num
384 ]
385 def main [
386   1:foo <- merge 1/y, 23, 34
387 ]
388 +mem: storing 1 in location 1
389 +mem: storing 23 in location 2
390 +mem: storing 34 in location 3
391 $error: 0
392 
393 :(scenario merge_check_exclusive_container_containing_container_2)
394 exclusive-container foo [
395   x:num
396   y:bar
397 ]
398 container bar [
399   x:num
400   y:num
401 ]
402 def main [
403   1:foo <- merge 0/x, 23
404 ]
405 $error: 0
406 
407 :(scenario merge_check_exclusive_container_containing_container_3)
408 % Hide_errors = true;
409 exclusive-container foo [
410   x:num
411   y:bar
412 ]
413 container bar [
414   x:num
415   y:num
416 ]
417 def main [
418   1:foo <- merge 1/y, 23
419 ]
420 +error: main: too few ingredients in '1:foo <- merge 1/y, 23'
421 
422 :(scenario merge_check_exclusive_container_containing_container_4)
423 exclusive-container foo [
424   x:num
425   y:bar
426 ]
427 container bar [
428   a:num
429   b:num
430 ]
431 def main [
432   1:bar <- merge 23, 24
433   3:foo <- merge 1/y, 1:bar
434 ]
435 $error: 0
436 
437 //: Since the different variants of an exclusive-container might have
438 //: different sizes, relax the size mismatch check for 'merge' instructions.
439 :(before "End size_mismatch(x) Special-cases")
440 if (current_step_index() < SIZE(Current_routine->steps())
441   ¦ && current_instruction().operation == MERGE
442   ¦ && !current_instruction().products.empty()
443   ¦ && current_instruction().products.at(0).type) {
444   reagent/*copy*/ x = current_instruction().products.at(0);
445   // Update size_mismatch Check for MERGE(x)
446   const type_tree* root_type = x.type->atom ? x.type : x.type->left;
447   assert(root_type->atom);
448   if (get(Type, root_type->value).kind == EXCLUSIVE_CONTAINER)
449   ¦ return size_of(x) < SIZE(data);
450 }
451 
452 :(scenario merge_exclusive_container_with_mismatched_sizes)
453 container foo [
454   x:num
455   y:num
456 ]
457 exclusive-container bar [
458   x:num
459   y:foo
460 ]
461 def main [
462   1:num <- copy 34
463   2:num <- copy 35
464   3:bar <- merge 0/x, 1:num
465   6:bar <- merge 1/foo, 1:num, 2:num
466 ]
467 +mem: storing 0 in location 3
468 +mem: storing 34 in location 4
469 # bar is always 3 large so location 5 is skipped
470 +mem: storing 1 in location 6
471 +mem: storing 34 in location 7
472 +mem: storing 35 in location 8