about summary refs log blame commit diff stats
path: root/build4
blob: ab5c4a0b80bc7133941953b143cf2932b5456f33 (plain) (tree)
1
2
3
4
5
6
7
8
9






                                                                             

                                                                              

                                                                           

                                                                          



                                                                            




                                                                            
                        










                                                                  
                          






























































                                                                                            



                                                          



                              

                                                                                                   

           




                 















                                             
                                                         

























                                                                                                        
                                                                                                       

                                                         
                                            
               

















                                                                   
                                           










                                       
                                                   














                                                                                                     
                                                                                                    








                                                                        
                                          










                                                                                                                                                            
                                                










                                        
                                                 








                                                                                    
                                                    









                                                
                                                                                                                       








                                                    
                                                                


















                                                                                                      
                                                                  
                                      
#!/bin/sh
# Experimental alternative to build2 that can run steps in parallel if their
# dependencies are met. Caveats:
#
#   1. We rely on the OS to schedule steps, so thousands of independent tasks
#      will likely be counter-productive.
#   2. Can run out of virtual memory if you spawn too many say $CC processes.
#   3. Compilation errors can cause the script to hang. We tag the most common
#      suspects with '|| quit', but can't eliminate the possibility entirely.
#   4. Ugly as heck! This version really benefits from comparisons with its
#      'upstream', build2. And even then, diff gets confused.
#   5. There's a mechanical difficulty: we use mktemp to reliably create
#      temporary filenames, which has the side effect of also creating the
#      files. So zero-size files are considered equivalent to non-existent
#      files. When some commands have trouble with this (e.g. ar) we need to
#      delete the empty file, which can expose us to a race condition wrt
#      mktemp.

set -e  # stop immediately on error

# Some environment variables that can be passed in. For example, to turn off
# optimization:
#   $ CFLAGS=-g ./build4
test "$CXX" || export CXX=c++
test "$CC" || export CC=cc
test "$CFLAGS" || export CFLAGS="-g -O2"
export CFLAGS="$CFLAGS -Wall -Wextra -ftrapv -fno-strict-aliasing"

# Outline:
# [0-9]*.cc -> mu.cc -> .build/*.cc -> .build/*.o -> .build/mu_bin
# (layers)   |        |              |             |
#          tangle  cleave          $CXX          $CXX

# can also be called with a layer to only build until
#   $ ./build4 --until 050
UNTIL_LAYER=${2:-zzz}

# there's two mechanisms for fast builds here:
# - if a command is quick to run, always run it but update the result only on any change
# - otherwise run it only if the output is 'older_than' the inputs
#
# avoid combining both mechanisms for a single file
# otherwise you'll see spurious messages about files being updated
# risk: a file may unnecessarily update without changes, causing unnecessary work downstream

# return 1 if $1 is older than _any_ of the remaining args
older_than() {
  local target=$1
  shift
  if [ ! -s $target ]
  then
#?     echo "$target has size zero"
#?     echo "updating $target" >&2
    return 0  # success
  fi
  local f
  for f in $*
  do
    if [ $f -nt $target ]
    then
#?       echo "updating $target" >&2
      return 0  # success
    fi
  done
  return 1  # failure
}

# redirect to $1, unless it's already identical
update() {
  if [ ! -e $1 ]
  then
    cat > $1
  else
    cat > $1.tmp
    diff -q $1 $1.tmp >/dev/null  &&  rm $1.tmp  ||  mv $1.tmp $1
  fi
}

update_cp() {
  if [ ! -e $2/$1 ]
  then
    cp $1 $2
  elif [ $1 -nt $2/$1 ]
  then
    cp $1 $2
  fi
}

noisy_cd() {
  cd $1
  echo "-- `pwd`" >&2
}

mv_if_exists() {
  test -e $1  &&  mv $1 $2
  return 0
}

# wait for all the given filenames to exist
# exit immediately if a special file called '.quit' exists
QUITFILE=`pwd`/.quit
rm -f $QUITFILE
wait_for_all() {
  # could use inotify on Linux
  while ! all_exist "$@"
  do
#?     echo waiting: $*
    test -e $QUITFILE  &&  return 1  # some step had an error; stop all waiting steps using errexit
    sleep 1
  done
  return 0
}
quit() {
  touch $QUITFILE
  exit 1
}

all_exist() {
  for f in "$@"
  do
    test -e $f  ||  return 1
  done
  return 0
}

TMP=`mktemp`
mv_if_exists enumerate/enumerate $TMP
(
  wait_for_all enumerate/enumerate.cc
  older_than $TMP enumerate/enumerate.cc && {
    echo "building enumerate"
    $CXX $CFLAGS enumerate/enumerate.cc -o $TMP  ||  quit
    echo "done building enumerate"
  }
  mv $TMP enumerate/enumerate
) &

TMP=`mktemp`
mv_if_exists tangle/tangle $TMP
(
  wait_for_all tangle/*.cc
  older_than $TMP tangle/*.cc && {
    echo "building tangle"
    cd tangle
      # auto-generate various lists (ending in '_list' by convention) {
      # list of types
      {
        grep -h "^struct .* {" [0-9]*.cc  |sed 's/\(struct *[^ ]*\).*/\1;/'
        grep -h "^typedef " [0-9]*.cc
      }  |update type_list
      # list of function declarations, so I can define them in any order
      grep -h "^[^ #].*) {" [0-9]*.cc  |sed 's/ {.*/;/'  |update function_list
      # list of code files to compile
      ls [0-9]*.cc  |grep -v "\.test\.cc$"  |sed 's/.*/#include "&"/'  |update file_list
      # list of test files to compile
      ls [0-9]*.test.cc  |sed 's/.*/#include "&"/'  |update test_file_list
      # list of tests to run
      grep -h "^[[:space:]]*void test_" [0-9]*.cc  |sed 's/^\s*void \(.*\)() {$/\1,/'  |update test_list
      grep -h "^\s*void test_" [0-9]*.cc  |sed 's/^\s*void \(.*\)() {.*/"\1",/'  |update test_name_list
      # }
      # Now that we have all the _lists, compile 'tangle'
      $CXX $CFLAGS boot.cc -o $TMP  ||  quit
      $TMP test
    cd ..
    echo "done building tangle"
  }
  mv $TMP tangle/tangle
) &

wait_for_all enumerate/enumerate
echo "enumerating layers"
LAYERS=$(./enumerate/enumerate --until $UNTIL_LAYER  |grep '\.cc$')
echo "done enumerating layers"

TMP=`mktemp`
mv_if_exists mu.cc $TMP
(
  wait_for_all $LAYERS enumerate/enumerate tangle/tangle
  older_than $TMP $LAYERS enumerate/enumerate tangle/tangle && {
    echo "running tangle"
    # no update here; rely on 'update' calls downstream
    ./tangle/tangle $LAYERS >$TMP  ||  quit
    echo "done running tangle"
  }
  mv $TMP mu.cc
) &

TMP=`mktemp`
mv_if_exists cleave/cleave $TMP
(
  wait_for_all cleave/cleave.cc
  older_than $TMP cleave/cleave.cc && {
    echo "building cleave"
    $CXX $CFLAGS cleave/cleave.cc -o $TMP  ||  quit
    rm -rf .build
    echo "done building cleave"
  }
  mv $TMP cleave/cleave
) &

wait_for_all mu.cc cleave/cleave  # cleave/cleave just for the .build cleanup
mkdir -p .build
# auto-generate function declarations, so I can define them in any order
# functions start out unindented, have all args on the same line, and end in ') {'
#
#                                      \/ ignore methods
grep -h "^[^[:space:]#].*) {$" mu.cc  |grep -v ":.*("  |sed 's/ {.*/;/'  |update .build/function_list
# auto-generate list of tests to run
grep -h "^\s*void test_" mu.cc  |sed 's/^\s*void \(.*\)() {.*/\1,/'  |update .build/test_list
grep -h "^\s*void test_" mu.cc  |sed 's/^\s*void \(.*\)() {.*/"\1",/'  |update .build/test_name_list
mkdir -p .build/termbox
update_cp termbox/termbox.h .build/termbox

TMP=`mktemp`
mv_if_exists mu_bin $TMP
(
  wait_for_all mu.cc cleave/cleave termbox/*.c termbox/*.h termbox/*.inl
  older_than $TMP mu.cc *_list cleave/cleave termbox/* && {
    echo "building mu_bin"
    ./cleave/cleave mu.cc .build  ||  quit
    cd .build
      # create the list of global variable declarations from the corresponding definitions
      grep ';' global_definitions_list  |sed 's/[=(].*/;/'  |sed 's/^[^\/# ]/extern &/'  |sed 's/^extern extern /extern /'  |update global_declarations_list
      for f in mu_*.cc
      do
        OBJ=`echo $f |sed 's/\.cc$/.o/'`
        TMP=`mktemp`
        mv_if_exists $OBJ $TMP
        (
          older_than $TMP $f header global_declarations_list function_list test_list && {
            echo "building $OBJ"
            $CXX $CFLAGS -c $f -o $TMP  ||  quit
            echo "done building $OBJ"
          }
          mv $TMP $OBJ
        ) &
      done
    cd ../termbox
      TMP=`mktemp`
      mv_if_exists utf8.o $TMP
      (
        older_than $TMP utf8.c && {
          echo "building termbox/utf8.o"
          $CC $CFLAGS -c utf8.c -o $TMP  ||  quit
          echo "done building termbox/utf8.o"
        }
        mv $TMP utf8.o
      ) &
      TMP=`mktemp`
      mv_if_exists termbox.o $TMP
      (
        older_than $TMP termbox.c termbox.h input.inl output.inl bytebuffer.inl && {
          echo "building termbox/termbox.o"
          $CC $CFLAGS -c termbox.c -o $TMP  ||  quit
          echo "done building termbox/termbox.o"
        }
        mv $TMP termbox.o
      ) &
      TMP=`mktemp`
      mv_if_exists libtermbox.a $TMP
      (
        wait_for_all termbox.o utf8.o
        older_than $TMP termbox.o utf8.o && {
          echo "building termbox/libtermbox.a"
          rm $TMP;  ar rcs $TMP termbox.o utf8.o  ||  quit  # race condition; later mktemp may end up reusing this file
          echo "done building termbox/libtermbox.a"
        }
        mv $TMP libtermbox.a
      ) &
    cd ..
    MU_OBJS=`echo .build/mu_*.cc |sed 's/\.cc/.o/g'`
    echo wait_for_all $MU_OBJS termbox/libtermbox.a
    wait_for_all $MU_OBJS termbox/libtermbox.a
    echo "building .build/mu_bin"
    $CXX $CFLAGS $MU_OBJS termbox/libtermbox.a -o $TMP  ||  quit
    echo "done building .build/mu_bin"
    echo "done building mu_bin"
  }
  mv $TMP mu_bin
) &

## [0-9]*.mu -> core.mu

wait_for_all enumerate/enumerate
echo "building core.mu"
MU_LAYERS=$(./enumerate/enumerate --until $UNTIL_LAYER  |grep '\.mu$') || exit 0  # ok if no .mu files
cat $MU_LAYERS  |update core.mu
echo "done building core.mu"

wait_for_all mu_bin
exit 0

# scenarios considered:
#   0 status when nothing needs updating
#   only a single layer is recompiled when changing a C++ function
#   stop immediately after any failure
Kartik K. Agaram <vc@akkartik.com> 2015-07-31 17:08:30 -0700 1909 - clean up all null pointers of that ilk' href='/akkartik/mu/commit/032array.cc?h=hlt&id=18e626dfe83c21822debc6f5a56eaea2b3102220'>18e626df ^
2b250717 ^
46026f62 ^

3473c63a ^
15936c91 ^

15936c91 ^
2b250717 ^
551d155c ^

090cad5c ^
9f7f62ed ^
c442a5ad ^

fb1fcbc9 ^

a55bbd06 ^


7e9c6925 ^
3377364a ^
9f7f62ed ^



3377364a ^
93d4cc93 ^








9f7f62ed ^
93d4cc93 ^
9f7f62ed ^
7e9c6925 ^

b8348923 ^
34068eb3 ^
93d4cc93 ^


91ec4681 ^
93d4cc93 ^
b8348923 ^
93d4cc93 ^
b8348923 ^


34068eb3 ^
91ec4681 ^




23d3a022 ^
91ec4681 ^



93d4cc93 ^




cb48c5d7 ^





23d3a022 ^
cb48c5d7 ^

23d3a022 ^
cb48c5d7 ^
551d155c ^
5f98a10c ^
1ead3562 ^
23d3a022 ^

551d155c ^
23d3a022 ^
551d155c ^
051c4738 ^
5f98a10c ^
1ead3562 ^
23d3a022 ^

551d155c ^
23d3a022 ^
a55bbd06 ^
fb85b3b4 ^
5f98a10c ^
1ead3562 ^
fb85b3b4 ^
23d3a022 ^
fb85b3b4 ^
23d3a022 ^
fb85b3b4 ^
5c6840b8 ^


1ead3562 ^
192d59d3 ^
192d59d3 ^
5c6840b8 ^


991d76f3 ^
1848b18f ^
991d76f3 ^
1ead3562 ^
192d59d3 ^
192d59d3 ^
1848b18f ^
991d76f3 ^
1848b18f ^

991d76f3 ^
a55bbd06 ^
991d76f3 ^
b8515e8a ^
991d76f3 ^

2b250717 ^
e4630643 ^

3473c63a ^
15936c91 ^
1ad3fe9e ^
9dcbec39 ^
46026f62 ^

3473c63a ^
15936c91 ^

9dcbec39 ^
991d76f3 ^

3473c63a ^
15936c91 ^
090cad5c ^
991d76f3 ^
9dcbec39 ^
fb85b3b4 ^

fc19980d ^

0d219477 ^


fc19980d ^
b8515e8a ^


991d76f3 ^
3473c63a ^
15936c91 ^
b24eb476 ^
18e626df ^
2b250717 ^
18e626df ^

3473c63a ^
15936c91 ^

15936c91 ^
2b250717 ^
551d155c ^

9f7f62ed ^
c442a5ad ^
991d76f3 ^

59874868 ^
991d76f3 ^
6e793202 ^
6c96a437 ^
c442a5ad ^
991d76f3 ^

59874868 ^
a55bbd06 ^
c8a58cdc ^
991d76f3 ^
5f98a10c ^
1ead3562 ^
c6520d96 ^
991d76f3 ^

551d155c ^
9393ccc8 ^
551d155c ^
991d76f3 ^
5f98a10c ^
1ead3562 ^
c6520d96 ^
23d3a022 ^

551d155c ^
23d3a022 ^
551d155c ^
0d219477 ^


192d59d3 ^

0d219477 ^
192d59d3 ^
0d219477 ^
c8a58cdc ^


1ead3562 ^
192d59d3 ^
23d3a022 ^
c8a58cdc ^
23d3a022 ^
c8a58cdc ^



795f5244 ^
b8515e8a ^
c8a58cdc ^
b8515e8a ^
2b250717 ^
e4630643 ^

3473c63a ^
15936c91 ^

9dcbec39 ^
c8a58cdc ^

b8515e8a ^



3473c63a ^
15936c91 ^

2b250717 ^
18e626df ^

cfb142b9 ^
15936c91 ^
c8a58cdc ^

e74a2940 ^




991d76f3 ^
e74a2940 ^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538

                                                                              



                                                                               
 

                                               
          
                                                                                   
                               
 
                                     



                                             
                                                  
                                       
                    
                              
                                                                                                                                                        

          
                                                
                                         
                              
                                                                                                                                   

          
                             
                                                                                                                   


                                                                   

                                                                 
                                                                                                                        

          


                                                          
                                                                                                                                                                                         

          



                                                
                                                                 
                                       
                                   



                                                                 
                                                       
                                                                                                            
                                                                
                                               
                                                                                             
                     
                                               
                                   
                              

                         

 
                      
                                                                          
                               



                                                                              
          




                                   
 



                              
 
                       
          




                               


                     



                                                                                
                                                
                                                                                       
                       
                                                                                                             
             
   
                                                                                
 
 
                                                    
                                                                              

                                                

                                                                                                                                                           
                         
                                                      




                                  

                                                                          
                                              
                                                                                       
 
                             


                                                                           
                                                  
               
               


         




                                                                                                                        
                                                     

                     
             
 
                                                            
 











                                                                                                                                        
                                                                                                     



                                                                                                                              

 

                                                                             
                                              






                                                                                              

               

          

                                   


           
                                 
                     
                
                             
 
         
                   
                                 


               

                                                
                 
          



                               
                                                                                         
 
                               
 


                                                 






                                                            
 

                               
 
                               
          



                               

                                     
 
                               
 

                                             
                                        
                                    
                                       
             
                                    
                                                                                                                                      

          
                                                
                               
                           
                                                                                                                

          
                                                 

                                
                                                                                                                                                   

          
                                   
                                                
                                  
                                                          
                                           
                                                                                                                                                                                                                                   

          



                                                
                                                                 
                             
                                
                                                                                 
                          
                                                                                                                                              

          
                                                                  

                                               
                                                                                      
                                                                                                                                                                          

          
                                                          
                                                                                             

                                                                                        

                                           


        
       
                                                      



                                                 
                      








                                                                                                                      
                             
   
                     

 
                                    
                                   


                                                                                                                                                                       
                         
                                                        
   
                                               


                                        
                          




                                   
                                                                       



                               




                                 





                               
                                                        

                            
                               
 
                               
                     
          

                                                                                                          
 
                                                           
 
                                 
                     
          

                               
 
                                                         
 
                                       
                     
          
                                 
                                  
 
                                                                                           
 


                                                                              
          
                               
                        


                
                                               
 
                     
          
                               
                                             
 
                              

                                             
          
                                        
                                            
                                       

                                    
                                                                                                                                          

          
                                                
                                   
                           
                                                                                                                    

          
                                                 

                                    
                                                                                                                                                                               

          
                                                 
                                    
                                                          
                                         
                                                                                                                                                                                                                                                                                                                  

          

                                                                


                                                                                                                                                                                                                    
                                 


                                                
                 
                                                                 
                                 
                                
                          
                                                                                                                                              

          
                                                                  

                                               
                                                                                      
                                                                                                                                                                          

          
                                                                                                    
                                                                                  

                                                                            
                         
                                                                              
                                     
                                           
                                                                                                                         

                                        
        
 
 
                                   
                     
          
                                 

                                                                                                                                             
 
                                                                                       
 
                                     
                     
          
                                 

                                                        
 
                                                                                          
 


                                   

                                                 
 
                                                                                                      
 


                                   
          
                               
                              
 
                              



                                             
                                      
                                       
              
                                    
                                                                                                                                       

          
                                                 

                                 
                                                                                                   

          



                                                
                                                                  

                               
                                                                                                                                              

          
                     
                                                               

        




                                                                             
                                                                     
               
//: Arrays contain a variable number of elements of the same type. Their value
//: starts with the length of the array.
//:
//: You can create arrays of containers, but containers can only contain
//: elements of a fixed size, so you can't create containers containing arrays.
//: Create containers containing addresses to arrays instead.

//: You can create arrays using 'create-array'.
:(scenario create_array)
def main [
  # create an array occupying locations 1 (for the size) and 2-4 (for the elements)
  1:array:num:3 <- create-array
]
+run: creating array from 4 locations

:(before "End Primitive Recipe Declarations")
CREATE_ARRAY,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "create-array", CREATE_ARRAY);
:(before "End Primitive Recipe Checks")
case CREATE_ARRAY: {
  if (inst.products.empty()) {
    raise << maybe(get(Recipe, r).name) << "'create-array' needs one product and no ingredients but got '" << to_original_string(inst) << '\n' << end();
    break;
  }
  reagent/*copy*/ product = inst.products.at(0);
  // Update CREATE_ARRAY product in Check
  if (!is_mu_array(product)) {
    raise << maybe(get(Recipe, r).name) << "'create-array' cannot create non-array '" << product.original_string << "'\n" << end();
    break;
  }
  if (!product.type->right) {
    raise << maybe(get(Recipe, r).name) << "create array of what? '" << to_original_string(inst) << "'\n" << end();
    break;
  }
  // 'create-array' will need to check properties rather than types
  type_tree* array_length_from_type = product.type->right->right;
  if (!array_length_from_type) {
    raise << maybe(get(Recipe, r).name) << "create array of what size? '" << to_original_string(inst) << "'\n" << end();
    break;
  }
  if (!product.type->right->right->atom)
    array_length_from_type = array_length_from_type->left;
  if (!is_integer(array_length_from_type->name)) {
    raise << maybe(get(Recipe, r).name) << "'create-array' product should specify size of array after its element type, but got '" << product.type->right->right->name << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case CREATE_ARRAY: {
  reagent/*copy*/ product = current_instruction().products.at(0);
  // Update CREATE_ARRAY product in Run
  int base_address = product.value;
  type_tree* array_length_from_type = product.type->right->right;
  if (!product.type->right->right->atom)
    array_length_from_type = array_length_from_type->left;
  int array_length = to_integer(array_length_from_type->name);
  // initialize array length, so that size_of will work
  trace(Callstack_depth+1, "mem") << "storing " << array_length << " in location " << base_address << end();
  put(Memory, base_address, array_length);  // in array elements
  int size = size_of(product);  // in locations
  trace(Callstack_depth+1, "run") << "creating array from " << size << " locations" << end();
  // initialize array
  for (int i = 1;  i <= size_of(product);  ++i)
    put(Memory, base_address+i, 0);
  // no need to update product
  write_products = false;
  break;
}

:(scenario copy_array)
# Arrays can be copied around with a single instruction just like numbers,
# no matter how large they are.
# You don't need to pass the size around, since each array variable stores its
# size in memory at run-time. We'll call a variable with an explicit size a
# 'static' array, and one without a 'dynamic' array since it can contain
# arrays of many different sizes.
def main [
  1:array:num:3 <- create-array
  2:num <- copy 14
  3:num <- copy 15
  4:num <- copy 16
  5:array:num <- copy 1:array:num:3
]
+mem: storing 3 in location 5
+mem: storing 14 in location 6
+mem: storing 15 in location 7
+mem: storing 16 in location 8

:(scenario stash_array)
def main [
  1:array:num:3 <- create-array
  2:num <- copy 14
  3:num <- copy 15
  4:num <- copy 16
  stash [foo:], 1:array:num:3
]
+app: foo: 3 14 15 16

:(before "End types_coercible Special-cases")
if (is_mu_array(from) && is_mu_array(to))
  return types_strictly_match(array_element(from.type), array_element(to.type));

:(before "End size_of(reagent r) Special-cases")
if (!r.type->atom && r.type->left->atom && r.type->left->value == Array_type_ordinal) {
  if (!r.type->right) {
    raise << maybe(current_recipe_name()) << "'" << r.original_string << "' is an array of what?\n" << end();
    return 1;
  }
  return /*space for length*/1 + array_length(r)*size_of(array_element(r.type));
}

:(before "End size_of(type) Non-atom Special-cases")
if (type->left->value == Array_type_ordinal) return static_array_length(type);
:(code)
int static_array_length(const type_tree* type) {
  if (!type->atom && type->right && !type->right->atom && type->right->right && !type->right->right->atom && !type->right->right->right  // exactly 3 types
      && type->right->right->left && type->right->right->left->atom && is_integer(type->right->right->left->name)) {  // third 'type' is a number
    // get size from type
    return to_integer(type->right->right->left->name);
  }
  cerr << to_string(type) << '\n';
  assert(false);
}

//: disable the size mismatch check for arrays since the destination array
//: need not be initialized
:(before "End size_mismatch(x) Special-cases")
if (x.type && !x.type->atom && x.type->left->value == Array_type_ordinal) return false;

//:: arrays inside containers
//: arrays are disallowed inside containers unless their length is fixed in
//: advance

:(scenario container_permits_static_array_element)
container foo [
  x:array:num:3
]
$error: 0

:(before "End insert_container Special-cases")
else if (is_integer(type->name)) {  // sometimes types will contain non-type tags, like numbers for the size of an array
  type->value = 0;
}

:(scenario container_disallows_dynamic_array_element)
% Hide_errors = true;
container foo [
  x:array:num
]
+error: container 'foo' cannot determine size of element 'x'

:(before "End Load Container Element Definition")
{
  const type_tree* type = info.elements.back().type;
  if (type && type->atom && type->name == "array") {
    raise << "container '" << name << "' doesn't specify type of array elements for '" << info.elements.back().name << "'\n" << end();
    continue;
  }
  if (type && !type->atom && type->left->atom && type->left->name == "array") {
    if (!type->right) {
      raise << "container '" << name << "' doesn't specify type of array elements for '" << info.elements.back().name << "'\n" << end();
      continue;
    }
    if (!type->right->right || !is_integer(type->right->right->left->name)) {  // array has no length
      raise << "container '" << name << "' cannot determine size of element '" << info.elements.back().name << "'\n" << end();
      continue;
    }
  }
}

//: disable the size mismatch check for 'merge' instructions since containers
//: can contain arrays, and since we already do plenty of checking for them
:(before "End size_mismatch(x) Special-cases")
if (current_call().running_step_index < SIZE(get(Recipe, current_call().running_recipe).steps)
    && current_instruction().operation == MERGE) {
  return false;
}

:(scenario merge_static_array_into_container)
container foo [
  x:num
  y:array:num:3
]
def main [
  1:array:num:3 <- create-array
  10:foo <- merge 34, 1:array:num:3
]
# no errors

:(scenario code_inside_container)
% Hide_errors = true;
container card [
  rank:num <- next-ingredient
]
def foo [
  1:card <- merge 3
  2:num <- get 1:card rank:offset
]
# shouldn't die

//:: To access elements of an array, use 'index'

:(scenario index)
def main [
  1:array:num:3 <- create-array
  2:num <- copy 14
  3:num <- copy 15
  4:num <- copy 16
  10:num <- index 1:array:num:3, 0/index  # the index must be a non-negative whole number
]
+mem: storing 14 in location 10

:(scenario index_compound_element)
def main [
  {1: (array (address number) 3)} <- create-array
  # skip alloc id
  3:num <- copy 14
  # skip alloc id
  5:num <- copy 15
  # skip alloc id
  7:num <- copy 16
  10:address:num <- index {1: (array (address number) 3)}, 0
]
# skip alloc id
+mem: storing 14 in location 11

:(scenario index_direct_offset)
def main [
  1:array:num:3 <- create-array
  2:num <- copy 14
  3:num <- copy 15
  4:num <- copy 16
  10:num <- copy 0
  20:num <- index 1:array:num, 10:num
]
+mem: storing 14 in location 20

:(before "End Primitive Recipe Declarations")
INDEX,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "index", INDEX);
:(before "End Primitive Recipe Checks")
case INDEX: {
  if (SIZE(inst.ingredients) != 2) {
    raise << maybe(get(Recipe, r).name) << "'index' expects exactly 2 ingredients in '" << to_original_string(inst) << "'\n" << end();
    break;
  }
  reagent/*copy*/ base = inst.ingredients.at(0);
  // Update INDEX base in Check
  if (!is_mu_array(base)) {
    raise << maybe(get(Recipe, r).name) << "'index' on a non-array '" << base.original_string << "'\n" << end();
    break;
  }
  reagent/*copy*/ index = inst.ingredients.at(1);
  // Update INDEX index in Check
  if (!is_mu_number(index)) {
    raise << maybe(get(Recipe, r).name) << "second ingredient of 'index' should be a number, but got '" << index.original_string << "'\n" << end();
    break;
  }
  if (inst.products.empty()) break;
  reagent/*copy*/ product = inst.products.at(0);
  // Update INDEX product in Check
  reagent/*local*/ element(copy_array_element(base.type));
  if (!types_coercible(product, element)) {
    raise << maybe(get(Recipe, r).name) << "'index' on '" << base.original_string << "' can't be saved in '" << product.original_string << "'; type should be '" << names_to_string_without_quotes(element.type) << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case INDEX: {
  reagent/*copy*/ base = current_instruction().ingredients.at(0);
  // Update INDEX base in Run
  int base_address = base.value;
  trace(Callstack_depth+1, "run") << "base address is " << base_address << end();
  if (base_address == 0) {
    raise << maybe(current_recipe_name()) << "tried to access location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
    break;
  }
  reagent/*copy*/ index = current_instruction().ingredients.at(1);
  // Update INDEX index in Run
  vector<double> index_val(read_memory(index));
  if (index_val.at(0) < 0 || index_val.at(0) >= get_or_insert(Memory, base_address)) {
    raise << maybe(current_recipe_name()) << "invalid index " << no_scientific(index_val.at(0)) << " in '" << to_original_string(current_instruction()) << "'\n" << end();
    break;
  }
  reagent/*local*/ element(copy_array_element(base.type));
  element.set_value(base_address + /*skip length*/1 + index_val.at(0)*size_of(element.type));
  trace(Callstack_depth+1, "run") << "address to copy is " << element.value << end();
  trace(Callstack_depth+1, "run") << "its type is " << to_string(element.type) << end();
  // Read element
  products.push_back(read_memory(element));
  break;
}

:(code)
type_tree* copy_array_element(const type_tree* type) {
  return new type_tree(*array_element(type));
}

type_tree* array_element(const type_tree* type) {
  assert(type->right);
  if (type->right->atom) {
    return type->right;
  }
  else if (!type->right->right) {
    return type->right->left;
  }
  // hack: support array:num:3 without requiring extra parens
  else if (type->right->right->left && type->right->right->left->atom && is_integer(type->right->right->left->name)) {
    assert(!type->right->right->right);
    return type->right->left;
  }
  return type->right;
}

int array_length(const reagent& x) {
  // x should already be canonized.
  // hack: look for length in type
  if (!x.type->atom && x.type->right && !x.type->right->atom && x.type->right->right && !x.type->right->right->atom && !x.type->right->right->right  // exactly 3 types
      && x.type->right->right->left && x.type->right->right->left->atom && is_integer(x.type->right->right->left->name)) {  // third 'type' is a number
    // get size from type
    return to_integer(x.type->right->right->left->name);
  }
  // this should never happen at transform time
  return get_or_insert(Memory, x.value);
}

:(before "End Unit Tests")
void test_array_length_compound() {
  put(Memory, 1, 3);
  put(Memory, 2, 14);
  put(Memory, 3, 15);
  put(Memory, 4, 16);
  reagent x("1:array:address:num");  // 3 types, but not a static array
  populate_value(x);
  CHECK_EQ(array_length(x), 3);
}

void test_array_length_static() {
  reagent x("1:array:num:3");
  CHECK_EQ(array_length(x), 3);
}

:(scenario index_truncates)
def main [
  1:array:num:3 <- create-array
  2:num <- copy 14
  3:num <- copy 15
  4:num <- copy 16
  10:num <- index 1:array:num:3, 1.5  # non-whole number
]
# fraction is truncated away
+mem: storing 15 in location 10

:(scenario index_out_of_bounds)
% Hide_errors = true;
def main [
  1:array:point:3 <- create-array
  index 1:array:point:3, 4  # less than size of array in locations, but larger than its length in elements
]
+error: main: invalid index 4 in 'index 1:array:point:3, 4'

:(scenario index_out_of_bounds_2)
% Hide_errors = true;
def main [
  1:array:num:3 <- create-array
  index 1:array:num, -1
]
+error: main: invalid index -1 in 'index 1:array:num, -1'

:(scenario index_product_type_mismatch)
% Hide_errors = true;
def main [
  1:array:point:3 <- create-array
  10:num <- index 1:array:point, 0
]
+error: main: 'index' on '1:array:point' can't be saved in '10:num'; type should be 'point'

//: we might want to call 'index' without saving the results, say in a sandbox

:(scenario index_without_product)
def main [
  1:array:num:3 <- create-array
  index 1:array:num:3, 0
]
# just don't die

//:: To write to elements of arrays, use 'put'.

:(scenario put_index)
def main [
  1:array:num:3 <- create-array
  1:array:num <- put-index 1:array:num, 1, 34
]
+mem: storing 34 in location 3

:(before "End Primitive Recipe Declarations")
PUT_INDEX,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "put-index", PUT_INDEX);
:(before "End Primitive Recipe Checks")
case PUT_INDEX: {
  if (SIZE(inst.ingredients) != 3) {
    raise << maybe(get(Recipe, r).name) << "'put-index' expects exactly 3 ingredients in '" << to_original_string(inst) << "'\n" << end();
    break;
  }
  reagent/*copy*/ base = inst.ingredients.at(0);
  // Update PUT_INDEX base in Check
  if (!is_mu_array(base)) {
    raise << maybe(get(Recipe, r).name) << "'put-index' on a non-array '" << base.original_string << "'\n" << end();
    break;
  }
  reagent/*copy*/ index = inst.ingredients.at(1);
  // Update PUT_INDEX index in Check
  if (!is_mu_number(index)) {
    raise << maybe(get(Recipe, r).name) << "second ingredient of 'put-index' should have type 'number', but got '" << inst.ingredients.at(1).original_string << "'\n" << end();
    break;
  }
  reagent/*copy*/ value = inst.ingredients.at(2);
  // Update PUT_INDEX value in Check
  reagent/*local*/ element(copy_array_element(base.type));
  if (!types_coercible(element, value)) {
    raise << maybe(get(Recipe, r).name) << "'put-index " << base.original_string << ", " << inst.ingredients.at(1).original_string << "' should store " << names_to_string_without_quotes(element.type) << " but '" << value.name << "' has type " << names_to_string_without_quotes(value.type) << '\n' << end();
    break;
  }
  if (inst.products.empty()) break;  // no more checks necessary
  if (inst.products.at(0).name != inst.ingredients.at(0).name) {
    raise << maybe(get(Recipe, r).name) << "product of 'put-index' must be first ingredient '" << inst.ingredients.at(0).original_string << "', but got '" << inst.products.at(0).original_string << "'\n" << end();
    break;
  }
  // End PUT_INDEX Product Checks
  break;
}
:(before "End Primitive Recipe Implementations")
case PUT_INDEX: {
  reagent/*copy*/ base = current_instruction().ingredients.at(0);
  // Update PUT_INDEX base in Run
  int base_address = base.value;
  if (base_address == 0) {
    raise << maybe(current_recipe_name()) << "tried to access location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
    break;
  }
  reagent/*copy*/ index = current_instruction().ingredients.at(1);
  // Update PUT_INDEX index in Run
  vector<double> index_val(read_memory(index));
  if (index_val.at(0) < 0 || index_val.at(0) >= get_or_insert(Memory, base_address)) {
    raise << maybe(current_recipe_name()) << "invalid index " << no_scientific(index_val.at(0)) << " in '" << to_original_string(current_instruction()) << "'\n" << end();
    break;
  }
  int address = base_address + /*skip length*/1 + index_val.at(0)*size_of(array_element(base.type));
  trace(Callstack_depth+1, "run") << "address to copy to is " << address << end();
  // optimization: directly write the element rather than updating 'product'
  // and writing the entire array
  write_products = false;
  vector<double> value = read_memory(current_instruction().ingredients.at(2));
  // Write Memory in PUT_INDEX in Run
  for (int i = 0;  i < SIZE(value);  ++i) {
    trace(Callstack_depth+1, "mem") << "storing " << no_scientific(value.at(i)) << " in location " << address+i << end();
    put(Memory, address+i, value.at(i));
  }
  break;
}

:(scenario put_index_out_of_bounds)
% Hide_errors = true;
def main [
  1:array:point:3 <- create-array
  8:point <- merge 34, 35
  1:array:point <- put-index 1:array:point, 4, 8:point  # '4' is less than size of array in locations, but larger than its length in elements
]
+error: main: invalid index 4 in '1:array:point <- put-index 1:array:point, 4, 8:point'

:(scenario put_index_out_of_bounds_2)
% Hide_errors = true;
def main [
  1:array:point:3 <- create-array
  10:point <- merge 34, 35
  1:array:point <- put-index 1:array:point, -1, 10:point
]
+error: main: invalid index -1 in '1:array:point <- put-index 1:array:point, -1, 10:point'

:(scenario put_index_product_error)
% Hide_errors = true;
def main [
  1:array:num:3 <- create-array
  4:array:num:3 <- put-index 1:array:num:3, 0, 34
]
+error: main: product of 'put-index' must be first ingredient '1:array:num:3', but got '4:array:num:3'

//:: compute the length of an array

:(scenario array_length)
def main [
  1:array:num:3 <- create-array
  10:num <- length 1:array:num
]
+mem: storing 3 in location 10

:(before "End Primitive Recipe Declarations")
LENGTH,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "length", LENGTH);
:(before "End Primitive Recipe Checks")
case LENGTH: {
  if (SIZE(inst.ingredients) != 1) {
    raise << maybe(get(Recipe, r).name) << "'length' expects exactly 2 ingredients in '" << to_original_string(inst) << "'\n" << end();
    break;
  }
  reagent/*copy*/ array = inst.ingredients.at(0);
  // Update LENGTH array in Check
  if (!is_mu_array(array)) {
    raise << "tried to calculate length of non-array '" << array.original_string << "'\n" << end();
    break;
  }
  break;
}
:(before "End Primitive Recipe Implementations")
case LENGTH: {
  reagent/*copy*/ array = current_instruction().ingredients.at(0);
  // Update LENGTH array in Run
  if (array.value == 0) {
    raise << maybe(current_recipe_name()) << "tried to access location 0 in '" << to_original_string(current_instruction()) << "'\n" << end();
    break;
  }
  products.resize(1);
  products.at(0).push_back(get_or_insert(Memory, array.value));
  break;
}

//: optimization: none of the instructions in this layer use 'ingredients' so
//: stop copying potentially huge arrays into it.
:(before "End should_copy_ingredients Special-cases")
recipe_ordinal r = current_instruction().operation;
if (r == CREATE_ARRAY || r == INDEX || r == PUT_INDEX || r == LENGTH)
  return false;