1 //: Containers contain a fixed number of elements of different types.
  2 
  3 :(before "End Mu Types Initialization")
  4 //: We'll use this container as a running example in scenarios below.
  5 type_ordinal point = put(Type_ordinal, "point", Next_type_ordinal++);
  6 get_or_insert(Type, point);  // initialize
  7 get(Type, point).kind = CONTAINER;
  8 get(Type, point).name = "point";
  9 get(Type, point).elements.push_back(reagent("x:number"));
 10 get(Type, point).elements.push_back(reagent("y:number"));
 11 
 12 //: Containers can be copied around with a single instruction just like
 13 //: numbers, no matter how large they are.
 14 
 15 //: Tests in this layer often explicitly set up memory before reading it as a
 16 //: container. Don't do this in general. I'm tagging exceptions with /unsafe to
 17 //: skip later checks.
 18 :(scenario copy_multiple_locations)
 19 def main [
 20   1:num <- copy 34
 21   2:num <- copy 35
 22   3:point <- copy 1:point/unsafe
 23 ]
 24 +mem: storing 34 in location 3
 25 +mem: storing 35 in location 4
 26 
 27 //: trying to copy to a differently-typed destination will fail
 28 :(scenario copy_checks_size)
 29 % Hide_errors = true;
 30 def main [
 31   2:point <- copy 1:num
 32 ]
 33 +error: main: can't copy '1:num' to '2:point'; types don't match
 34 
 35 :(before "End Mu Types Initialization")
 36 // A more complex example container, containing another container as one of
 37 // its elements.
 38 type_ordinal point_number = put(Type_ordinal, "point-number", Next_type_ordinal++);
 39 get_or_insert(Type, point_number);  // initialize
 40 get(Type, point_number).kind = CONTAINER;
 41 get(Type, point_number).name = "point-number";
 42 get(Type, point_number).elements.push_back(reagent("xy:point"));
 43 get(Type, point_number).elements.push_back(reagent("z:number"));
 44 
 45 :(scenario copy_handles_nested_container_elements)
 46 def main [
 47   12:num <- copy 34
 48   13:num <- copy 35
 49   14:num <- copy 36
 50   15:point-number <- copy 12:point-number/unsafe
 51 ]
 52 +mem: storing 36 in location 17
 53 
 54 //: products of recipes can include containers
 55 :(scenario return_container)
 56 def main [
 57   3:point <- f 2
 58 ]
 59 def f [
 60   12:num <- next-ingredient
 61   13:num <- copy 35
 62   return 12:point/raw
 63 ]
 64 +run: result 0 is [2, 35]
 65 +mem: storing 2 in location 3
 66 +mem: storing 35 in location 4
 67 
 68 //: Containers can be checked for equality with a single instruction just like
 69 //: numbers, no matter how large they are.
 70 
 71 :(scenario compare_multiple_locations)
 72 def main [
 73   1:num <- copy 34  # first
 74   2:num <- copy 35
 75   3:num <- copy 36
 76   4:num <- copy 34  # second
 77   5:num <- copy 35
 78   6:num <- copy 36
 79   7:bool <- equal 1:point-number/raw, 4:point-number/unsafe
 80 ]
 81 +mem: storing 1 in location 7
 82 
 83 :(scenario compare_multiple_locations_2)
 84 def main [
 85   1:num <- copy 34  # first
 86   2:num <- copy 35
 87   3:num <- copy 36
 88   4:num <- copy 34  # second
 89   5:num <- copy 35
 90   6:num <- copy 37  # different
 91   7:bool <- equal 1:point-number/raw, 4:point-number/unsafe
 92 ]
 93 +mem: storing 0 in location 7
 94 
 95 //: Can't put this in type_info because later layers will add support for more
 96 //: complex type trees where metadata depends on *combinations* of types.
 97 :(before "struct reagent")
 98 struct container_metadata {
 99   int size;
100   vector<int> offset;  // not used by exclusive containers
101   // End container_metadata Fields
102   container_metadata() :size(0) {
103     // End container_metadata Constructor
104   }
105 };
106 :(before "End reagent Fields")
107 container_metadata metadata;  // can't be a pointer into Container_metadata because we keep changing the base storage when we save/restore snapshots
108 :(before "End reagent Copy Operator")
109 metadata = other.metadata;
110 :(before "End reagent Copy Constructor")
111 metadata = other.metadata;
112 
113 :(before "End Globals")
114 // todo: switch to map after figuring out how to consistently compare type trees
115 vector<pair<type_tree*, container_metadata> > Container_metadata, Container_metadata_snapshot;
116 :(before "End save_snapshots")
117 Container_metadata_snapshot = Container_metadata;
118 :(before "End restore_snapshots")
119 restore_container_metadata();
120 :(before "End One-time Setup")
121 atexit(clear_container_metadata);
122 :(code)
123 // invariant: Container_metadata always contains a superset of Container_metadata_snapshot
124 void restore_container_metadata() {
125   for (int i = 0;  i < SIZE(Container_metadata);  ++i) {
126     assert(Container_metadata.at(i).first);
127     if (i < SIZE(Container_metadata_snapshot)) {
128       assert(Container_metadata.at(i).first == Container_metadata_snapshot.at(i).first);
129       continue;
130     }
131     delete Container_metadata.at(i).first;
132     Container_metadata.at(i).first = NULL;
133   }
134   Container_metadata.resize(SIZE(Container_metadata_snapshot));
135 }
136 void clear_container_metadata() {
137   Container_metadata_snapshot.clear();
138   for (int i = 0;  i < SIZE(Container_metadata);  ++i) {
139     delete Container_metadata.at(i).first;
140     Container_metadata.at(i).first = NULL;
141   }
142   Container_metadata.clear();
143 }
144 
145 //: do no work in size_of, simply lookup Container_metadata
146 
147 :(before "End size_of(reagent r) Special-cases")
148 if (r.metadata.size) return r.metadata.size;
149 
150 :(before "End size_of(type) Special-cases")
151 const type_tree* base_type = type;
152 // Update base_type in size_of(type)
153 if (!contains_key(Type, base_type->value)) {
154   raise << "no such type " << base_type->value << '\n' << end();
155   return 0;
156 }
157 type_info t = get(Type, base_type->value);
158 if (t.kind == CONTAINER) {
159   // Compute size_of Container
160   if (!contains_key(Container_metadata, type)) {
161     raise << "unknown size for container type '" << to_string(type) << "'\n" << end();
162 //?     DUMP("");
163     return 0;
164   }
165   return get(Container_metadata, type).size;
166 }
167 
168 //: precompute Container_metadata before we need size_of
169 //: also store a copy in each reagent in each instruction in each recipe
170 
171 :(after "End Type Modifying Transforms")
172 Transform.push_back(compute_container_sizes);  // idempotent
173 :(code)
174 void compute_container_sizes(const recipe_ordinal r) {
175   recipe& caller = get(Recipe, r);
176   trace(9992, "transform") << "--- compute container sizes for " << caller.name << end();
177   for (int i = 0;  i < SIZE(caller.steps);  ++i) {
178     instruction& inst = caller.steps.at(i);
179     trace(9993, "transform") << "- compute container sizes for " << to_string(inst) << end();
180     for (int i = 0;  i < SIZE(inst.ingredients);  ++i)
181       compute_container_sizes(inst.ingredients.at(i), " in '"+to_original_string(inst)+"'");
182     for (int i = 0;  i < SIZE(inst.products);  ++i)
183       compute_container_sizes(inst.products.at(i), " in '"+to_original_string(inst)+"'");
184   }
185 }
186 
187 void compute_container_sizes(reagent& r, const string& location_for_error_messages) {
188   expand_type_abbreviations(r.type);
189   if (is_literal(r) || is_dummy(r)) return;
190   reagent rcopy = r;
191   // Compute Container Size(reagent rcopy)
192   set<type_tree> pending_metadata;  // might actually be faster to just convert to string rather than compare type_tree directly; so far the difference is negligible
193   compute_container_sizes(rcopy.type, pending_metadata, location_for_error_messages);
194   if (contains_key(Container_metadata, rcopy.type))
195     r.metadata = get(Container_metadata, rcopy.type);
196 }
197 
198 void compute_container_sizes(const type_tree* type, set<type_tree>& pending_metadata, const string& location_for_error_messages) {
199   if (!type) return;
200   trace(9993, "transform") << "compute container sizes for " << to_string(type) << end();
201   if (contains_key(Container_metadata, type)) return;
202   if (contains_key(pending_metadata, *type)) return;
203   pending_metadata.insert(*type);
204   if (!type->atom) {
205     if (!type->left->atom) {
206       raise << "invalid type " << to_string(type) << location_for_error_messages << '\n' << end();
207       return;
208     }
209     if (type->left->name == "address")
210       compute_container_sizes(payload_type(type), pending_metadata, location_for_error_messages);
211     // End compute_container_sizes Non-atom Special-cases
212     return;
213   }
214   assert(type->atom);
215   if (!contains_key(Type, type->value)) return;  // error raised elsewhere
216   type_info& info = get(Type, type->value);
217   if (info.kind == CONTAINER)
218     compute_container_sizes(info, type, pending_metadata, location_for_error_messages);
219   // End compute_container_sizes Atom Special-cases
220 }
221 
222 void compute_container_sizes(const type_info& container_info, const type_tree* full_type, set<type_tree>& pending_metadata, const string& location_for_error_messages) {
223   assert(container_info.kind == CONTAINER);
224   // size of a container is the sum of the sizes of its element
225   // (So it can only contain arrays if they're static and include their
226   // length in the type.)
227   container_metadata metadata;
228   for (int i = 0;  i < SIZE(container_info.elements);  ++i) {
229     reagent/*copy*/ element = container_info.elements.at(i);
230     // Compute Container Size(element, full_type)
231     compute_container_sizes(element.type, pending_metadata, location_for_error_messages);
232     metadata.offset.push_back(metadata.size);  // save previous size as offset
233     metadata.size += size_of(element.type);
234   }
235   Container_metadata.push_back(pair<type_tree*, container_metadata>(new type_tree(*full_type), metadata));
236 }
237 
238 const type_tree* payload_type(const type_tree* type) {
239   assert(!type->atom);
240   const type_tree* result = type->right;
241   assert(!result->atom);
242   if (!result->right) return result->left;
243   return result;
244 }
245 
246 container_metadata& get(vector<pair<type_tree*, container_metadata> >& all, const type_tree* key) {
247   for (int i = 0;  i < SIZE(all);  ++i) {
248     if (matches(all.at(i).first, key))
249       return all.at(i).second;
250   }
251   raise << "unknown size for type '" << to_string(key) << "'\n" << end();
252   exit(1);
253 }
254 
255 bool contains_key(const vector<pair<type_tree*, container_metadata> >& all, const type_tree* key) {
256   for (int i = 0;  i < SIZE(all);  ++i) {
257     if (matches(all.at(i).first, key))
258       return true;
259   }
260   return false;
261 }
262 
263 bool matches(const type_tree* a, const type_tree* b) {
264   if (a == b) return true;
265   if (!a || !b) return false;
266   if (a->atom != b->atom) return false;
267   if (a->atom) return a->value == b->value;
268   return matches(a->left, b->left) && matches(a->right, b->right);
269 }
270 
271 :(scenario stash_container)
272 def main [
273   1:num <- copy 34  # first
274   2:num <- copy 35
275   3:num <- copy 36
276   stash [foo:], 1:point-number/raw
277 ]
278 +app: foo: 34 35 36
279 
280 //: for the following unit tests we'll do the work of the transform by hand
281 
282 :(before "End Unit Tests")
283 void test_container_sizes() {
284   // a container we don't have the size for
285   reagent r("x:point");
286   CHECK(!contains_key(Container_metadata, r.type));
287   // scan
288   compute_container_sizes(r, "");
289   // the reagent we scanned knows its size
290   CHECK_EQ(r.metadata.size, 2);
291   // the global table also knows its size
292   CHECK(contains_key(Container_metadata, r.type));
293   CHECK_EQ(get(Container_metadata, r.type).size, 2);
294 }
295 
296 void test_container_sizes_through_aliases() {
297   // a new alias for a container
298   put(Type_abbreviations, "pt", new_type_tree("point"));
299   reagent r("x:pt");
300   // scan
301   compute_container_sizes(r, "");
302   // the reagent we scanned knows its size
303   CHECK_EQ(r.metadata.size, 2);
304   // the global table also knows its size
305   CHECK(contains_key(Container_metadata, r.type));
306   CHECK_EQ(get(Container_metadata, r.type).size, 2);
307 }
308 
309 void test_container_sizes_nested() {
310   // a container we don't have the size for
311   reagent r("x:point-number");
312   CHECK(!contains_key(Container_metadata, r.type));
313   // scan
314   compute_container_sizes(r, "");
315   // the reagent we scanned knows its size
316   CHECK_EQ(r.metadata.size, 3);
317   // the global table also knows its size
318   CHECK(contains_key(Container_metadata, r.type));
319   CHECK_EQ(get(Container_metadata, r.type).size, 3);
320 }
321 
322 void test_container_sizes_recursive() {
323   // define a container containing an address to itself
324   run("container foo [\n"
325       "  x:num\n"
326       "  y:address:foo\n"
327       "]\n");
328   reagent r("x:foo");
329   compute_container_sizes(r, "");
330   CHECK_EQ(r.metadata.size, 2);
331 }
332 
333 void test_container_sizes_from_address() {
334   // a container we don't have the size for
335   reagent container("x:point");
336   CHECK(!contains_key(Container_metadata, container.type));
337   // scanning an address to the container precomputes the size of the container
338   reagent r("x:address:point");
339   compute_container_sizes(r, "");
340   CHECK(contains_key(Container_metadata, container.type));
341   CHECK_EQ(get(Container_metadata, container.type).size, 2);
342 }
343 
344 //:: To access elements of a container, use 'get'
345 //: 'get' takes a 'base' container and an 'offset' into it and returns the
346 //: appropriate element of the container value.
347 
348 :(scenario get)
349 def main [
350   12:num <- copy 34
351   13:num <- copy 35
352   15:num <- get 12:point/raw, 1:offset  # unsafe
353 ]
354 +mem: storing 35 in location 15
355 
356 :(before "End Primitive Recipe Declarations")
357 GET,
358 :(before "End Primitive Recipe Numbers")
359 put(Recipe_ordinal, "get", GET);
360 :(before "End Primitive Recipe Checks")
361 case GET: {
362   if (SIZE(inst.ingredients) != 2) {
363     raise << maybe(get(Recipe, r).name) << "'get' expects exactly 2 ingredients in '" << to_original_string(inst) << "'\n" << end();
364     break;
365   }
366   reagent/*copy*/ base = inst.ingredients.at(0);  // new copy for every invocation
367   // Update GET base in Check
368   if (!base.type) {
369     raise << maybe(get(Recipe, r).name) << "first ingredient of 'get' should be a container, but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
370     break;
371   }
372   const type_tree* base_type = base.type;
373   // Update GET base_type in Check
374   if (!base_type->atom || base_type->value == 0 || !contains_key(Type, base_type->value) || get(Type, base_type->value).kind != CONTAINER) {
375     raise << maybe(get(Recipe, r).name) << "first ingredient of 'get' should be a container, but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
376     break;
377   }
378   const reagent& offset = inst.ingredients.at(1);
379   if (!is_literal(offset) || !is_mu_scalar(offset)) {
380     raise << maybe(get(Recipe, r).name) << "second ingredient of 'get' should have type 'offset', but got '" << inst.ingredients.at(1).original_string << "'\n" << end();
381     break;
382   }
383   int offset_value = 0;
384   if (is_integer(offset.name)) {
385     offset_value = to_integer(offset.name);
386   }
387   // End update GET offset_value in Check
388   if (offset_value < 0 || offset_value >= SIZE(get(Type, base_type->value).elements)) {
389     raise << maybe(get(Recipe, r).name) << "invalid offset '" << offset_value << "' for '" << get(Type, base_type->value).name << "'\n" << end();
390     break;
391   }
392   if (inst.products.empty()) break;
393   reagent/*copy*/ product = inst.products.at(0);
394   // Update GET product in Check
395   //: use base.type rather than base_type because later layers will introduce compound types
396   const reagent/*copy*/ element = element_type(base.type, offset_value);
397   if (!types_coercible(product, element)) {
398     raise << maybe(get(Recipe, r).name) << "'get " << base.original_string << ", " << offset.original_string << "' should write to " << names_to_string_without_quotes(element.type) << " but '" << product.name << "' has type " << names_to_string_without_quotes(product.type) << '\n' << end();
399     break;
400   }
401   break;
402 }
403 :(before "End Primitive Recipe Implementations")
404 case GET: {
405   reagent/*copy*/ base = current_instruction().ingredients.at(0);
406   // Update GET base in Run
407   int base_address = base.value;
408   if (base_address == 0) {
409     raise << maybe(current_recipe_name()) << "tried to access location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
410     break;
411   }
412   const type_tree* base_type = base.type;
413   // Update GET base_type in Run
414   int offset = ingredients.at(1).at(0);
415   if (offset < 0 || offset >= SIZE(get(Type, base_type->value).elements)) break;  // copied from Check above
416   assert(base.metadata.size);
417   int src = base_address + base.metadata.offset.at(offset);
418   trace(9998, "run") << "address to copy is " << src << end();
419   //: use base.type rather than base_type because later layers will introduce compound types
420   reagent/*copy*/ element = element_type(base.type, offset);
421   element.set_value(src);
422   trace(9998, "run") << "its type is " << names_to_string(element.type) << end();
423   // Read element
424   products.push_back(read_memory(element));
425   break;
426 }
427 
428 :(code)
429 const reagent element_type(const type_tree* type, int offset_value) {
430   assert(offset_value >= 0);
431   const type_tree* base_type = type;
432   // Update base_type in element_type
433   assert(contains_key(Type, base_type->value));
434   assert(!get(Type, base_type->value).name.empty());
435   const type_info& info = get(Type, base_type->value);
436   assert(info.kind == CONTAINER);
437   if (offset_value >= SIZE(info.elements)) return reagent();  // error handled elsewhere
438   reagent/*copy*/ element = info.elements.at(offset_value);
439   // End element_type Special-cases
440   return element;
441 }
442 
443 :(scenario get_handles_nested_container_elements)
444 def main [
445   12:num <- copy 34
446   13:num <- copy 35
447   14:num <- copy 36
448   15:num <- get 12:point-number/raw, 1:offset  # unsafe
449 ]
450 +mem: storing 36 in location 15
451 
452 :(scenario get_out_of_bounds)
453 % Hide_errors = true;
454 def main [
455   12:num <- copy 34
456   13:num <- copy 35
457   14:num <- copy 36
458   get 12:point-number/raw, 2:offset  # point-number occupies 3 locations but has only 2 fields; out of bounds
459 ]
460 +error: main: invalid offset '2' for 'point-number'
461 
462 :(scenario get_out_of_bounds_2)
463 % Hide_errors = true;
464 def main [
465   12:num <- copy 34
466   13:num <- copy 35
467   14:num <- copy 36
468   get 12:point-number/raw, -1:offset
469 ]
470 +error: main: invalid offset '-1' for 'point-number'
471 
472 :(scenario get_product_type_mismatch)
473 % Hide_errors = true;
474 def main [
475   12:num <- copy 34
476   13:num <- copy 35
477   14:num <- copy 36
478   15:address:num <- get 12:point-number/raw, 1:offset
479 ]
480 +error: main: 'get 12:point-number/raw, 1:offset' should write to number but '15' has type (address number)
481 
482 //: we might want to call 'get' without saving the results, say in a sandbox
483 
484 :(scenario get_without_product)
485 def main [
486   12:num <- copy 34
487   13:num <- copy 35
488   get 12:point/raw, 1:offset  # unsafe
489 ]
490 # just don't die
491 
492 //:: To write to elements of containers, use 'put'.
493 
494 :(scenario put)
495 def main [
496   12:num <- copy 34
497   13:num <- copy 35
498   $clear-trace
499   12:point <- put 12:point, 1:offset, 36
500 ]
501 +mem: storing 36 in location 13
502 -mem: storing 34 in location 12
503 
504 :(before "End Primitive Recipe Declarations")
505 PUT,
506 :(before "End Primitive Recipe Numbers")
507 put(Recipe_ordinal, "put", PUT);
508 :(before "End Primitive Recipe Checks")
509 case PUT: {
510   if (SIZE(inst.ingredients) != 3) {
511     raise << maybe(get(Recipe, r).name) << "'put' expects exactly 3 ingredients in '" << to_original_string(inst) << "'\n" << end();
512     break;
513   }
514   reagent/*copy*/ base = inst.ingredients.at(0);
515   // Update PUT base in Check
516   if (!base.type) {
517     raise << maybe(get(Recipe, r).name) << "first ingredient of 'put' should be a container, but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
518     break;
519   }
520   const type_tree* base_type = base.type;
521   // Update PUT base_type in Check
522   if (!base_type->atom || base_type->value == 0 || !contains_key(Type, base_type->value) || get(Type, base_type->value).kind != CONTAINER) {
523     raise << maybe(get(Recipe, r).name) << "first ingredient of 'put' should be a container, but got '" << inst.ingredients.at(0).original_string << "'\n" << end();
524     break;
525   }
526   reagent/*copy*/ offset = inst.ingredients.at(1);
527   // Update PUT offset in Check
528   if (!is_literal(offset) || !is_mu_scalar(offset)) {
529     raise << maybe(get(Recipe, r).name) << "second ingredient of 'put' should have type 'offset', but got '" << inst.ingredients.at(1).original_string << "'\n" << end();
530     break;
531   }
532   int offset_value = 0;
533   //: later layers will permit non-integer offsets
534   if (is_integer(offset.name)) {
535     offset_value = to_integer(offset.name);
536     if (offset_value < 0 || offset_value >= SIZE(get(Type, base_type->value).elements)) {
537       raise << maybe(get(Recipe, r).name) << "invalid offset '" << offset_value << "' for '" << get(Type, base_type->value).name << "'\n" << end();
538       break;
539     }
540   }
541   else {
542     offset_value = offset.value;
543   }
544   const reagent& value = inst.ingredients.at(2);
545   //: use base.type rather than base_type because later layers will introduce compound types
546   const reagent& element = element_type(base.type, offset_value);
547   if (!types_coercible(element, value)) {
548     raise << maybe(get(Recipe, r).name) << "'put " << base.original_string << ", " << offset.original_string << "' should write to " << names_to_string_without_quotes(element.type) << " but '" << value.name << "' has type " << names_to_string_without_quotes(value.type) << '\n' << end();
549     break;
550   }
551   if (inst.products.empty()) break;  // no more checks necessary
552   if (inst.products.at(0).name != inst.ingredients.at(0).name) {
553     raise << maybe(get(Recipe, r).name) << "product of 'put' must be first ingredient '" << inst.ingredients.at(0).original_string << "', but got '" << inst.products.at(0).original_string << "'\n" << end();
554     break;
555   }
556   // End PUT Product Checks
557   break;
558 }
559 :(before "End Primitive Recipe Implementations")
560 case PUT: {
561   reagent/*copy*/ base = current_instruction().ingredients.at(0);
562   // Update PUT base in Run
563   int base_address = base.value;
564   if (base_address == 0) {
565     raise << maybe(current_recipe_name()) << "tried to access location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
566     break;
567   }
568   const type_tree* base_type = base.type;
569   // Update PUT base_type in Run
570   int offset = ingredients.at(1).at(0);
571   if (offset < 0 || offset >= SIZE(get(Type, base_type->value).elements)) break;  // copied from Check above
572   int address = base_address + base.metadata.offset.at(offset);
573   trace(9998, "run") << "address to copy to is " << address << end();
574   // optimization: directly write the element rather than updating 'product'
575   // and writing the entire container
576   // Write Memory in PUT in Run
577   write_products = false;
578   for (int i = 0;  i < SIZE(ingredients.at(2));  ++i) {
579     trace("mem") << "storing " << no_scientific(ingredients.at(2).at(i)) << " in location " << address+i << end();
580     put(Memory, address+i, ingredients.at(2).at(i));
581   }
582   break;
583 }
584 
585 :(scenario put_product_error)
586 % Hide_errors = true;
587 def main [
588   local-scope
589   load-ingredients
590   1:point <- merge 34, 35
591   3:point <- put 1:point, x:offset, 36
592 ]
593 +error: main: product of 'put' must be first ingredient '1:point', but got '3:point'
594 
595 //:: Allow containers to be defined in Mu code.
596 
597 :(scenarios load)
598 :(scenario container)
599 container foo [
600   x:num
601   y:num
602 ]
603 +parse: --- defining container foo
604 +parse: element: {x: "number"}
605 +parse: element: {y: "number"}
606 
607 :(scenario container_use_before_definition)
608 container foo [
609   x:num
610   y:bar
611 ]
612 container bar [
613   x:num
614   y:num
615 ]
616 +parse: --- defining container foo
617 +parse: type number: 1000
618 +parse:   element: {x: "number"}
619 # todo: brittle
620 # type bar is unknown at this point, but we assign it a number
621 +parse:   element: {y: "bar"}
622 # later type bar geon
623 +parse: --- defining container bar
624 +parse: type number: 1001
625 +parse:   element: {x: "number"}
626 +parse:   element: {y: "number"}
627 
628 //: if a container is defined again, the new fields add to the original definition
629 :(scenarios run)
630 :(scenario container_extend)
631 container foo [
632   x:num
633 ]
634 # add to previous definition
635 container foo [
636   y:num
637 ]
638 def main [
639   1:num <- copy 34
640   2:num <- copy 35
641   3:num <- get 1:foo, 0:offset
642   4:num <- get 1:foo, 1:offset
643 ]
644 +mem: storing 34 in location 3
645 +mem: storing 35 in location 4
646 
647 :(before "End Command Handlers")
648 else if (command == "container") {
649   insert_container(command, CONTAINER, in);
650 }
651 
652 //: Even though we allow containers to be extended, we don't allow this after
653 //: a call to transform_all. But we do want to detect this situation and raise
654 //: an error. This field will help us raise such errors.
655 :(before "End type_info Fields")
656 int Num_calls_to_transform_all_at_first_definition;
657 :(before "End type_info Constructor")
658 Num_calls_to_transform_all_at_first_definition = -1;
659 
660 :(code)
661 void insert_container(const string& command, kind_of_type kind, istream& in) {
662   skip_whitespace_but_not_newline(in);
663   string name = next_word(in);
664   if (name.empty()) {
665     assert(!has_data(in));
666     raise << "incomplete container definition at end of file (0)\n" << end();
667     return;
668   }
669   // End container Name Refinements
670   trace(9991, "parse") << "--- defining " << command << ' ' << name << end();
671   if (!contains_key(Type_ordinal, name)
672       || get(Type_ordinal, name) == 0) {
673     put(Type_ordinal, name, Next_type_ordinal++);
674   }
675   trace("parse") << "type number: " << get(Type_ordinal, name) << end();
676   skip_bracket(in, "'"+command+"' must begin with '['");
677   type_info& info = get_or_insert(Type, get(Type_ordinal, name));
678   if (info.Num_calls_to_transform_all_at_first_definition == -1) {
679     // initial definition of this container
680     info.Num_calls_to_transform_all_at_first_definition = Num_calls_to_transform_all;
681   }
682   else if (info.Num_calls_to_transform_all_at_first_definition != Num_calls_to_transform_all) {
683     // extension after transform_all
684     raise << "there was a call to transform_all() between the definition of container '" << name << "' and a subsequent extension. This is not supported, since any recipes that used '" << name << "' values have already been transformed and \"frozen\".\n" << end();
685     return;
686   }
687   info.name = name;
688   info.kind = kind;
689   while (has_data(in)) {
690     skip_whitespace_and_comments(in);
691     string element = next_word(in);
692     if (element.empty()) {
693       assert(!has_data(in));
694       raise << "incomplete container definition at end of file (1)\n" << end();
695       return;
696     }
697     if (element == "]") break;
698     if (in.peek() != '\n') {
699       raise << command << " '" << name << "' contains multiple elements on a single line. Containers and exclusive containers must only contain elements, one to a line, no code.\n" << end();
700       // skip rest of container declaration
701       while (has_data(in)) {
702         skip_whitespace_and_comments(in);
703         if (next_word(in) == "]") break;
704       }
705       break;
706     }
707     info.elements.push_back(reagent(element));
708     expand_type_abbreviations(info.elements.back().type);  // todo: use abbreviation before declaration
709     replace_unknown_types_with_unique_ordinals(info.elements.back().type, info);
710     trace(9993, "parse") << "  element: " << to_string(info.elements.back()) << end();
711     // End Load Container Element Definition
712   }
713 }
714 
715 void replace_unknown_types_with_unique_ordinals(type_tree* type, const type_info& info) {
716   if (!type) return;
717   if (!type->atom) {
718     replace_unknown_types_with_unique_ordinals(type->left, info);
719     replace_unknown_types_with_unique_ordinals(type->right, info);
720     return;
721   }
722   assert(!type->name.empty());
723   if (contains_key(Type_ordinal, type->name)) {
724     type->value = get(Type_ordinal, type->name);
725   }
726   // End insert_container Special-cases
727   else if (type->name != "->") {  // used in recipe types
728     put(Type_ordinal, type->name, Next_type_ordinal++);
729     type->value = get(Type_ordinal, type->name);
730   }
731 }
732 
733 void skip_bracket(istream& in, string message) {
734   skip_whitespace_and_comments(in);
735   if (in.get() != '[')
736     raise << message << '\n' << end();
737 }
738 
739 :(scenario multi_word_line_in_container_declaration)
740 % Hide_errors = true;
741 container foo [
742   x:num y:num
743 ]
744 +error: container 'foo' contains multiple elements on a single line. Containers and exclusive containers must only contain elements, one to a line, no code.
745 
746 //: support type abbreviations in container definitions
747 
748 :(scenario type_abbreviations_in_containers)
749 type foo = number
750 container bar [
751   x:foo
752 ]
753 def main [
754   1:num <- copy 34
755   2:foo <- get 1:bar/unsafe, 0:offset
756 ]
757 +mem: storing 34 in location 2
758 
759 :(after "Transform.push_back(expand_type_abbreviations)")
760 Transform.push_back(expand_type_abbreviations_in_containers);  // idempotent
761 :(code)
762 // extremely inefficient; we process all types over and over again, once for every single recipe
763 // but it doesn't seem to cause any noticeable slowdown
764 void expand_type_abbreviations_in_containers(vestigial const recipe_ordinal r) {
765   for (map<type_ordinal, type_info>::iterator p = Type.begin();  p != Type.end();  ++p) {
766     for (int i = 0;  i < SIZE(p->second.elements);  ++i)
767       expand_type_abbreviations(p->second.elements.at(i).type);
768   }
769 }
770 
771 //: ensure scenarios are consistent by always starting new container
772 //: declarations at the same type number
773 :(before "End Reset")  //: for tests
774 Next_type_ordinal = 1000;
775 :(before "End Test Run Initialization")
776 assert(Next_type_ordinal < 1000);
777 
778 :(code)
779 void test_error_on_transform_all_between_container_definition_and_extension() {
780   // define a container
781   run("container foo [\n"
782       "  a:num\n"
783       "]\n");
784   // try to extend the container after transform
785   transform_all();
786   CHECK_TRACE_DOESNT_CONTAIN_ERRORS();
787   Hide_errors = true;
788   run("container foo [\n"
789       "  b:num\n"
790       "]\n");
791   CHECK_TRACE_CONTAINS_ERRORS();
792 }
793 
794 //:: Allow container definitions anywhere in the codebase, but complain if you
795 //:: can't find a definition at the end.
796 
797 :(scenario run_complains_on_unknown_types)
798 % Hide_errors = true;
799 def main [
800   # integer is not a type
801   1:integer <- copy 0
802 ]
803 +error: main: unknown type integer in '1:integer <- copy 0'
804 
805 :(scenario run_allows_type_definition_after_use)
806 def main [
807   1:bar <- copy 0/unsafe
808 ]
809 container bar [
810   x:num
811 ]
812 $error: 0
813 
814 :(before "End Type Modifying Transforms")
815 Transform.push_back(check_or_set_invalid_types);  // idempotent
816 
817 :(code)
818 void check_or_set_invalid_types(const recipe_ordinal r) {
819   recipe& caller = get(Recipe, r);
820   trace(9991, "transform") << "--- check for invalid types in recipe " << caller.name << end();
821   for (int index = 0;  index < SIZE(caller.steps);  ++index) {
822     instruction& inst = caller.steps.at(index);
823     for (int i = 0;  i < SIZE(inst.ingredients);  ++i)
824       check_or_set_invalid_types(inst.ingredients.at(i), caller, inst);
825     for (int i = 0;  i < SIZE(inst.products);  ++i)
826       check_or_set_invalid_types(inst.products.at(i), caller, inst);
827   }
828   // End check_or_set_invalid_types
829 }
830 
831 void check_or_set_invalid_types(reagent& r, const recipe& caller, const instruction& inst) {
832   // Begin check_or_set_invalid_types(r)
833   check_or_set_invalid_types(r.type, maybe(caller.name), "'"+to_original_string(inst)+"'");
834 }
835 
836 void check_or_set_invalid_types(type_tree* type, const string& location_for_error_messages, const string& name_for_error_messages) {
837   if (!type) return;
838   // End Container Type Checks
839   if (!type->atom) {
840     check_or_set_invalid_types(type->left, location_for_error_messages, name_for_error_messages);
841     check_or_set_invalid_types(type->right, location_for_error_messages, name_for_error_messages);
842     return;
843   }
844   if (type->value == 0) return;
845   if (!contains_key(Type, type->value)) {
846     assert(!type->name.empty());
847     if (contains_key(Type_ordinal, type->name))
848       type->value = get(Type_ordinal, type->name);
849     else
850       raise << location_for_error_messages << "unknown type " << type->name << " in " << name_for_error_messages << '\n' << end();
851   }
852 }
853 
854 :(scenario container_unknown_field)
855 % Hide_errors = true;
856 container foo [
857   x:num
858   y:bar
859 ]
860 +error: foo: unknown type in y
861 
862 :(scenario read_container_with_bracket_in_comment)
863 container foo [
864   x:num
865   # ']' in comment
866   y:num
867 ]
868 +parse: --- defining container foo
869 +parse: element: {x: "number"}
870 +parse: element: {y: "number"}
871 
872 :(scenario container_with_compound_field_type)
873 container foo [
874   {x: (address array (address array character))}
875 ]
876 $error: 0
877 
878 :(before "End transform_all")
879 check_container_field_types();
880 
881 :(code)
882 void check_container_field_types() {
883   for (map<type_ordinal, type_info>::iterator p = Type.begin();  p != Type.end();  ++p) {
884     const type_info& info = p->second;
885     // Check Container Field Types(info)
886     for (int i = 0;  i < SIZE(info.elements);  ++i)
887       check_invalid_types(info.elements.at(i).type, maybe(info.name), info.elements.at(i).name);
888   }
889 }
890 
891 void check_invalid_types(const type_tree* type, const string& location_for_error_messages, const string& name_for_error_messages) {
892   if (!type) return;  // will throw a more precise error elsewhere
893   if (!type->atom) {
894     check_invalid_types(type->left, location_for_error_messages, name_for_error_messages);
895     check_invalid_types(type->right, location_for_error_messages, name_for_error_messages);
896     return;
897   }
898   if (type->value != 0) {  // value 0 = compound types (layer parse_tree) or type ingredients (layer shape_shifting_container)
899     if (!contains_key(Type, type->value))
900       raise << location_for_error_messages << "unknown type in " << name_for_error_messages << '\n' << end();
901   }
902 }
903 
904 string to_original_string(const type_ordinal t) {
905   ostringstream out;
906   if (!contains_key(Type, t)) return out.str();
907   const type_info& info = get(Type, t);
908   if (info.kind == PRIMITIVE) return out.str();
909   out << (info.kind == CONTAINER ? "container" : "exclusive-container") << " " << info.name << " [\n";
910   for (int i = 0;  i < SIZE(info.elements);  ++i) {
911     out << "  " << info.elements.at(i).original_string << "\n";
912   }
913   out << "]\n";
914   return out.str();
915 }