1 //: Addresses help us spend less time copying data around.
  2 
  3 //: So far we've been operating on primitives like numbers and characters, and
  4 //: we've started combining these primitives together into larger logical
  5 //: units (containers or arrays) that may contain many different primitives at
  6 //: once. Containers and arrays can grow quite large in complex programs, and
  7 //: we'd like some way to efficiently share them between recipes without
  8 //: constantly having to make copies. Right now 'next-ingredient' and 'return'
  9 //: copy data across recipe boundaries. To avoid copying large quantities of
 10 //: data around, we'll use *addresses*. An address is a bookmark to some
 11 //: arbitrary quantity of data (the *payload*). It's a primitive, so it's as
 12 //: efficient to copy as a number. To read or modify the payload 'pointed to'
 13 //: by an address, we'll perform a *lookup*.
 14 //:
 15 //: The notion of 'lookup' isn't an instruction like 'add' or 'subtract'.
 16 //: Instead it's an operation that can be performed when reading any of the
 17 //: ingredients of an instruction, and when writing to any of the products. To
 18 //: write to the payload of an ingredient rather than its value, simply add
 19 //: the /lookup property to it. Modern computers provide efficient support for
 20 //: addresses and lookups, making this a realistic feature.
 21 
 22 //: todo: give 'new' a custodian ingredient. Following malloc/free is a temporary hack.
 23 
 24 :(scenario new)
 25 # call 'new' two times with identical types without modifying the results; you
 26 # should get back different results
 27 def main [
 28   1:address:num/raw <- new number:type
 29   2:address:num/raw <- new number:type
 30   3:bool/raw <- equal 1:address:num/raw, 2:address:num/raw
 31 ]
 32 +mem: storing 0 in location 3
 33 
 34 :(scenario new_array)
 35 # call 'new' with a second ingredient to allocate an array of some type rather than a single copy
 36 def main [
 37   1:address:array:num/raw <- new number:type, 5
 38   2:address:num/raw <- new number:type
 39   3:num/raw <- subtract 2:address:num/raw, 1:address:array:num/raw
 40 ]
 41 +run: {1: ("address" "array" "number"), "raw": ()} <- new {number: "type"}, {5: "literal"}
 42 +mem: array length is 5
 43 # don't forget the extra location for array length
 44 +mem: storing 6 in location 3
 45 
 46 :(scenario dilated_reagent_with_new)
 47 def main [
 48   1:address:address:num <- new {(address number): type}
 49 ]
 50 +new: size of '(address number)' is 1
 51 
 52 //: 'new' takes a weird 'type' as its first ingredient; don't error on it
 53 :(before "End Mu Types Initialization")
 54 put(Type_ordinal, "type", 0);
 55 :(code)
 56 bool is_mu_type_literal(const reagent& r) {
 57   return is_literal(r) && r.type && r.type->name == "type";
 58 }
 59 
 60 :(before "End Primitive Recipe Declarations")
 61 NEW,
 62 :(before "End Primitive Recipe Numbers")
 63 put(Recipe_ordinal, "new", NEW);
 64 :(before "End Primitive Recipe Checks")
 65 case NEW: {
 66   const recipe& caller = get(Recipe, r);
 67   if (inst.ingredients.empty() || SIZE(inst.ingredients) > 2) {
 68     raise << maybe(caller.name) << "'new' requires one or two ingredients, but got '" << to_original_string(inst) << "'\n" << end();
 69     break;
 70   }
 71   // End NEW Check Special-cases
 72   const reagent& type = inst.ingredients.at(0);
 73   if (!is_mu_type_literal(type)) {
 74     raise << maybe(caller.name) << "first ingredient of 'new' should be a type, but got '" << type.original_string << "'\n" << end();
 75     break;
 76   }
 77   if (SIZE(inst.ingredients) > 1 && !is_mu_number(inst.ingredients.at(1))) {
 78     raise << maybe(caller.name) << "second ingredient of 'new' should be a number (array length), but got '" << type.original_string << "'\n" << end();
 79     break;
 80   }
 81   if (inst.products.empty()) {
 82     raise << maybe(caller.name) << "result of 'new' should never be ignored\n" << end();
 83     break;
 84   }
 85   if (!product_of_new_is_valid(inst)) {
 86     raise << maybe(caller.name) << "product of 'new' has incorrect type: '" << to_original_string(inst) << "'\n" << end();
 87     break;
 88   }
 89   break;
 90 }
 91 :(code)
 92 bool product_of_new_is_valid(const instruction& inst) {
 93   reagent/*copy*/ product = inst.products.at(0);
 94   // Update NEW product in Check
 95   if (!product.type || product.type->atom || product.type->left->value != Address_type_ordinal)
 96     return false;
 97   drop_from_type(product, "address");
 98   if (SIZE(inst.ingredients) > 1) {
 99     // array allocation
100     if (!product.type || product.type->atom || product.type->left->value != Array_type_ordinal)
101       return false;
102     drop_from_type(product, "array");
103   }
104   reagent/*local*/ expected_product(new_type_tree(inst.ingredients.at(0).name));
105   return types_strictly_match(product, expected_product);
106 }
107 
108 void drop_from_type(reagent& r, string expected_type) {
109   assert(!r.type->atom);
110   if (r.type->left->name != expected_type) {
111     raise << "can't drop2 " << expected_type << " from '" << to_string(r) << "'\n" << end();
112     return;
113   }
114   // r.type = r.type->right
115   type_tree* tmp = r.type;
116   r.type = tmp->right;
117   tmp->right = NULL;
118   delete tmp;
119   // if (!r.type->right) r.type = r.type->left
120   assert(!r.type->atom);
121   if (r.type->right) return;
122   tmp = r.type;
123   r.type = tmp->left;
124   tmp->left = NULL;
125   delete tmp;
126 }
127 
128 :(scenario new_returns_incorrect_type)
129 % Hide_errors = true;
130 def main [
131   1:bool <- new num:type
132 ]
133 +error: main: product of 'new' has incorrect type: '1:bool <- new num:type'
134 
135 :(scenario new_discerns_singleton_list_from_atom_container)
136 % Hide_errors = true;
137 def main [
138   1:address:num/raw <- new {(num): type}  # should be '{num: type}'
139 ]
140 +error: main: product of 'new' has incorrect type: '1:address:num/raw <- new {(num): type}'
141 
142 :(scenario new_with_type_abbreviation)
143 def main [
144   1:address:num/raw <- new num:type
145 ]
146 $error: 0
147 
148 :(scenario new_with_type_abbreviation_inside_compound)
149 def main [
150   {1: (address address number), raw: ()} <- new {(& num): type}
151 ]
152 $error: 0
153 
154 //: To implement 'new', a Mu transform turns all 'new' instructions into
155 //: 'allocate' instructions that precompute the amount of memory they want to
156 //: allocate.
157 
158 //: Ensure that we never call 'allocate' directly, and that there's no 'new'
159 //: instructions left after the transforms have run.
160 :(before "End Primitive Recipe Checks")
161 case ALLOCATE: {
162   raise << "never call 'allocate' directly'; always use 'new'\n" << end();
163   break;
164 }
165 :(before "End Primitive Recipe Implementations")
166 case NEW: {
167   raise << "no implementation for 'new'; why wasn't it translated to 'allocate'? Please save a copy of your program and send it to Kartik.\n" << end();
168   break;
169 }
170 
171 :(after "Transform.push_back(check_instruction)")  // check_instruction will guard against direct 'allocate' instructions below
172 Transform.push_back(transform_new_to_allocate);  // idempotent
173 
174 :(code)
175 void transform_new_to_allocate(const recipe_ordinal r) {
176   trace(9991, "transform") << "--- convert 'new' to 'allocate' for recipe " << get(Recipe, r).name << end();
177   for (int i = 0;  i < SIZE(get(Recipe, r).steps);  ++i) {
178     instruction& inst = get(Recipe, r).steps.at(i);
179     // Convert 'new' To 'allocate'
180     if (inst.name == "new") {
181       if (inst.ingredients.empty()) return;  // error raised elsewhere
182       inst.operation = ALLOCATE;
183       type_tree* type = new_type_tree(inst.ingredients.at(0).name);
184       inst.ingredients.at(0).set_value(size_of(type));
185       trace(9992, "new") << "size of '" << inst.ingredients.at(0).name << "' is " << inst.ingredients.at(0).value << end();
186       delete type;
187     }
188   }
189 }
190 
191 //: implement 'allocate' based on size
192 
193 :(before "End Globals")
194 extern const int Reserved_for_tests = 1000;
195 int Memory_allocated_until = Reserved_for_tests;
196 int Initial_memory_per_routine = 100000;
197 :(before "End Reset")
198 Memory_allocated_until = Reserved_for_tests;
199 Initial_memory_per_routine = 100000;
200 :(before "End routine Fields")
201 int alloc, alloc_max;
202 :(before "End routine Constructor")
203 alloc = Memory_allocated_until;
204 Memory_allocated_until += Initial_memory_per_routine;
205 alloc_max = Memory_allocated_until;
206 trace("new") << "routine allocated memory from " << alloc << " to " << alloc_max << end();
207 
208 :(before "End Primitive Recipe Declarations")
209 ALLOCATE,
210 :(before "End Primitive Recipe Numbers")
211 put(Recipe_ordinal, "allocate", ALLOCATE);
212 :(before "End Primitive Recipe Implementations")
213 case ALLOCATE: {
214   // compute the space we need
215   int size = ingredients.at(0).at(0);
216   if (SIZE(ingredients) > 1) {
217     // array allocation
218     trace("mem") << "array length is " << ingredients.at(1).at(0) << end();
219     size = /*space for length*/1 + size*ingredients.at(1).at(0);
220   }
221   int result = allocate(size);
222   if (SIZE(current_instruction().ingredients) > 1) {
223     // initialize array length
224     trace("mem") << "storing " << ingredients.at(1).at(0) << " in location " << result << end();
225     put(Memory, result, ingredients.at(1).at(0));
226   }
227   products.resize(1);
228   products.at(0).push_back(result);
229   break;
230 }
231 :(code)
232 int allocate(int size) {
233   trace("mem") << "allocating size " << size << end();
234 //?   Total_alloc += size;
235 //?   ++Num_alloc;
236   // Allocate Special-cases
237   // compute the region of memory to return
238   // really crappy at the moment
239   ensure_space(size);
240   const int result = Current_routine->alloc;
241   trace("mem") << "new alloc: " << result << end();
242   // initialize allocated space
243   for (int address = result;  address < result+size;  ++address) {
244     trace("mem") << "storing 0 in location " << address << end();
245     put(Memory, address, 0);
246   }
247   Current_routine->alloc += size;
248   // no support yet for reclaiming memory between routines
249   assert(Current_routine->alloc <= Current_routine->alloc_max);
250   return result;
251 }
252 
253 //: statistics for debugging
254 //? :(before "End Globals")
255 //? int Total_alloc = 0;
256 //? int Num_alloc = 0;
257 //? int Total_free = 0;
258 //? int Num_free = 0;
259 //? :(before "End Reset")
260 //? if (!Memory.empty()) {
261 //?   cerr << Total_alloc << "/" << Num_alloc
262 //?        << " vs " << Total_free << "/" << Num_free << '\n';
263 //?   cerr << SIZE(Memory) << '\n';
264 //? }
265 //? Total_alloc = Num_alloc = Total_free = Num_free = 0;
266 
267 :(code)
268 void ensure_space(int size) {
269   if (size > Initial_memory_per_routine) {
270     cerr << "can't allocate " << size << " locations, that's too much compared to " << Initial_memory_per_routine << ".\n";
271     exit(1);
272   }
273   if (Current_routine->alloc + size > Current_routine->alloc_max) {
274     // waste the remaining space and create a new chunk
275     Current_routine->alloc = Memory_allocated_until;
276     Memory_allocated_until += Initial_memory_per_routine;
277     Current_routine->alloc_max = Memory_allocated_until;
278     trace("new") << "routine allocated memory from " << Current_routine->alloc << " to " << Current_routine->alloc_max << end();
279   }
280 }
281 
282 :(scenario new_initializes)
283 % Memory_allocated_until = 10;
284 % put(Memory, Memory_allocated_until, 1);
285 def main [
286   1:address:num <- new number:type
287 ]
288 +mem: storing 0 in location 10
289 
290 :(scenario new_size)
291 def main [
292   11:address:num/raw <- new number:type
293   12:address:num/raw <- new number:type
294   13:num/raw <- subtract 12:address:num/raw, 11:address:num/raw
295 ]
296 # size of number
297 +mem: storing 1 in location 13
298 
299 :(scenario new_array_size)
300 def main [
301   1:address:array:num/raw <- new number:type, 5
302   2:address:num/raw <- new number:type
303   3:num/raw <- subtract 2:address:num/raw, 1:address:array:num/raw
304 ]
305 # 5 locations for array contents + array length
306 +mem: storing 6 in location 3
307 
308 :(scenario new_empty_array)
309 def main [
310   1:address:array:num/raw <- new number:type, 0
311   2:address:num/raw <- new number:type
312   3:num/raw <- subtract 2:address:num/raw, 1:address:array:num/raw
313 ]
314 +run: {1: ("address" "array" "number"), "raw": ()} <- new {number: "type"}, {0: "literal"}
315 +mem: array length is 0
316 # one location for array length
317 +mem: storing 1 in location 3
318 
319 //: If a routine runs out of its initial allocation, it should allocate more.
320 :(scenario new_overflow)
321 % Initial_memory_per_routine = 2;  // barely enough room for point allocation below
322 def main [
323   1:address:num/raw <- new number:type
324   2:address:point/raw <- new point:type  # not enough room in initial page
325 ]
326 +new: routine allocated memory from 1000 to 1002
327 +new: routine allocated memory from 1002 to 1004
328 
329 :(scenario new_without_ingredient)
330 % Hide_errors = true;
331 def main [
332   1:address:number <- new  # missing ingredient
333 ]
334 +error: main: 'new' requires one or two ingredients, but got '1:address:number <- new'