about summary refs log blame commit diff stats
path: root/html/035compute_segment_address.cc.html
blob: 1fadcf827850b443df2c4d28188d4fa5cd4806e0 (plain) (tree)
1
2
3
4
5
6
7
8
9



                                                                                          
                                                 

                                                

                                                                                                               
                                                 

                       

                                                                                                 
                    
                                     
           
                                
                             

                                                                           
                               
                              















                                                                                 
                                                  















                                                                              
                                                                                                                                                               
                         







                                                                                                                                                  
                                                                                                                                                                                                               
                                                                                                              



                                                                                                                                                             
                                                                                                                                  











                                                                                                                          
                                                                                                           
                                                                                                                                                                                                                                                                                                              

                                                                              
                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

                                                                                                                                                                                                                                                                                                                                                                                                                                                


                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              

                                                                                                                                    
                                                                                                                                                                                                                                                                                           




                                                                                                                                                                                                                                     
                                                                                                                                                                                                                                                                                                                                                                                                                                           
                                                                                                                                                                                                                                                                                                                              



                                                                                                                    
                                                                                                                                                                                                                                                                                            
                                                                                                                                                    
                                                                                                                                                                                                                                                                                                                                                                                                                                              
                                                                                                                                                                                                                                                                          



                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                                                                                                                                                                                                           
                                                                                                                                                  
                                                                                                                                                                                                                                                                                                                  














                                                                                                                                                     
                                                                                                                                                  



                                                                                                                                              



                                     
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Mu - 035compute_segment_address.cc</title>
<meta name="Generator" content="Vim/8.1">
<meta name="plugin-version" content="vim8.1_v1">
<meta name="syntax" content="cpp">
<meta name="settings" content="number_lines,use_css,pre_wrap,no_foldcolumn,expand_tabs,line_ids,prevent_copy=">
<meta name="colorscheme" content="minimal-light">
<style type="text/css">
<!--
pre { white-space: pre-wrap; font-family: monospace; color: #000000; background-color: #c6c6c6; }
body { font-size:12pt; font-family: monospace; color: #000000; background-color: #c6c6c6; }
a { color:inherit; }
* { font-size:12pt; font-size: 1em; }
.LineNr { }
.SpecialChar { color: #d70000; }
.Constant { color: #008787; }
.Comment { color: #005faf; }
.Normal { color: #000000; background-color: #c6c6c6; padding-bottom: 1px; }
.Identifier { color: #af5f00; }
.Delimiter { color: #c000c0; }
-->
</style>

<script type='text/javascript'>
<!--

/* function to open any folds containing a jumped-to line before jumping to it */
function JumpToLine()
{
  var lineNum;
  lineNum = window.location.hash;
  lineNum = lineNum.substr(1); /* strip off '#' */

  if (lineNum.indexOf('L') == -1) {
    lineNum = 'L'+lineNum;
  }
  var lineElem = document.getElementById(lineNum);
  /* Always jump to new location even if the line was hidden inside a fold, or
   * we corrected the raw number to a line ID.
   */
  if (lineElem) {
    lineElem.scrollIntoView(true);
  }
  return true;
}
if ('onhashchange' in window) {
  window.onhashchange = JumpToLine;
}

-->
</script>
</head>
<body onload='JumpToLine();'>
<a href='https://github.com/akkartik/mu/blob/master/035compute_segment_address.cc'>https://github.com/akkartik/mu/blob/master/035compute_segment_address.cc</a>
<pre id='vimCodeElement'>
<span id="L1" class="LineNr"> 1 </span><span class="Comment">//: ELF binaries have finicky rules about the precise alignment each segment</span>
<span id="L2" class="LineNr"> 2 </span><span class="Comment">//: should start at. They depend on the amount of code in a program.</span>
<span id="L3" class="LineNr"> 3 </span><span class="Comment">//: We shouldn't expect people to adjust segment addresses everytime they make</span>
<span id="L4" class="LineNr"> 4 </span><span class="Comment">//: a change to their programs.</span>
<span id="L5" class="LineNr"> 5 </span><span class="Comment">//: Let's start taking the given segment addresses as guidelines, and adjust</span>
<span id="L6" class="LineNr"> 6 </span><span class="Comment">//: them as necessary.</span>
<span id="L7" class="LineNr"> 7 </span><span class="Comment">//: This gives up a measure of control in placing code and data.</span>
<span id="L8" class="LineNr"> 8 </span>
<span id="L9" class="LineNr"> 9 </span><span class="Normal">void</span> <a href='035compute_segment_address.cc.html#L9'>test_segment_name</a><span class="Delimiter">()</span> <span class="Delimiter">{</span>
<span id="L10" class="LineNr">10 </span>  <a href='011run.cc.html#L82'>run</a><span class="Delimiter">(</span>
<span id="L11" class="LineNr">11 </span>      <span class="Constant">&quot;== code 0x09000000\n&quot;</span>
<span id="L12" class="LineNr">12 </span>      <span class="Constant">&quot;05/add-to-EAX  0x0d0c0b0a/imm32\n&quot;</span>
<span id="L13" class="LineNr">13 </span>      <span class="Comment">// code starts at 0x09000000 + p_offset, which is 0x54 for a single-segment binary</span>
<span id="L14" class="LineNr">14 </span>  <span class="Delimiter">);</span>
<span id="L15" class="LineNr">15 </span>  <a href='003trace.cc.html#L290'>CHECK_TRACE_CONTENTS</a><span class="Delimiter">(</span>
<span id="L16" class="LineNr">16 </span>      <span class="Constant">&quot;load: 0x09000054 -&gt; 05\n&quot;</span>
<span id="L17" class="LineNr">17 </span>      <span class="Constant">&quot;load: 0x09000055 -&gt; 0a\n&quot;</span>
<span id="L18" class="LineNr">18 </span>      <span class="Constant">&quot;load: 0x09000056 -&gt; 0b\n&quot;</span>
<span id="L19" class="LineNr">19 </span>      <span class="Constant">&quot;load: 0x09000057 -&gt; 0c\n&quot;</span>
<span id="L20" class="LineNr">20 </span>      <span class="Constant">&quot;load: 0x09000058 -&gt; 0d\n&quot;</span>
<span id="L21" class="LineNr">21 </span>      <span class="Constant">&quot;run: add imm32 0x0d0c0b0a to EAX\n&quot;</span>
<span id="L22" class="LineNr">22 </span>      <span class="Constant">&quot;run: storing 0x0d0c0b0a\n&quot;</span>
<span id="L23" class="LineNr">23 </span>  <span class="Delimiter">);</span>
<span id="L24" class="LineNr">24 </span><span class="Delimiter">}</span>
<span id="L25" class="LineNr">25 </span>
<span id="L26" class="LineNr">26 </span><span class="Comment">//: compute segment address</span>
<span id="L27" class="LineNr">27 </span>
<span id="L28" class="LineNr">28 </span><span class="Delimiter">:(before &quot;End Transforms&quot;)</span>
<span id="L29" class="LineNr">29 </span><span class="SpecialChar"><a href='031transforms.cc.html#L4'>Transform</a></span><span class="Delimiter">.</span>push_back<span class="Delimiter">(</span><a href='035compute_segment_address.cc.html#L32'>compute_segment_starts</a><span class="Delimiter">);</span>
<span id="L30" class="LineNr">30 </span>
<span id="L31" class="LineNr">31 </span><span class="Delimiter">:(code)</span>
<span id="L32" class="LineNr">32 </span><span class="Normal">void</span> <a href='035compute_segment_address.cc.html#L32'>compute_segment_starts</a><span class="Delimiter">(</span>program&amp; p<span class="Delimiter">)</span> <span class="Delimiter">{</span>
<span id="L33" class="LineNr">33 </span>  <a href='003trace.cc.html#L96'>trace</a><span class="Delimiter">(</span><span class="Constant">3</span><span class="Delimiter">,</span> <span class="Constant">&quot;transform&quot;</span><span class="Delimiter">)</span> &lt;&lt; <span class="Constant">&quot;-- compute segment addresses&quot;</span> &lt;&lt; end<span class="Delimiter">();</span>
<span id="L34" class="LineNr">34 </span>  <span class="Normal">uint32_t</span> p_offset = <span class="Comment">/*</span><span class="Comment">size of ehdr</span><span class="Comment">*/</span><span class="Constant">0x34</span> + <a href='001help.cc.html#L166'>SIZE</a><span class="Delimiter">(</span>p<span class="Delimiter">.</span><a href='011run.cc.html#L106'>segments</a><span class="Delimiter">)</span>*<span class="Constant">0x20</span><span class="Comment">/*</span><span class="Comment">size of each phdr</span><span class="Comment">*/</span><span class="Delimiter">;</span>
<span id="L35" class="LineNr">35 </span>  <span class="Normal">for</span> <span class="Delimiter">(</span><span class="Normal">size_t</span> i = <span class="Constant">0</span><span class="Delimiter">;</span>  i &lt; p<span class="Delimiter">.</span><a href='011run.cc.html#L106'>segments</a><span class="Delimiter">.</span>size<span class="Delimiter">();</span>  ++i<span class="Delimiter">)</span> <span class="Delimiter">{</span>
<span id="L36" class="LineNr">36 </span>    segment&amp; curr = p<span class="Delimiter">.</span><a href='011run.cc.html#L106'>segments</a><span class="Delimiter">.</span>at<span class="Delimiter">(</span>i<span class="Delimiter">);</span>
<span id="L37" class="LineNr">37 </span>    <span class="Normal">if</span> <span class="Delimiter">(</span>curr<span class="Delimiter">.</span>start &gt;= <span class="Constant">0x08000000</span><span class="Delimiter">)</span> <span class="Delimiter">{</span>
<span id="L38" class="LineNr">38 </span>      <span class="Comment">// valid address for user space, so assume we're creating a real ELF binary, not just running a test</span>
<span id="L39" class="LineNr">39 </span>      curr<span class="Delimiter">.</span>start &amp;= <span class="Constant">0xfffff000</span><span class="Delimiter">;</span>  <span class="Comment">// same number of zeros as the p_align used when emitting the ELF binary</span>
<span id="L40" class="LineNr">40 </span>      curr<span class="Delimiter">.</span>start |= <span class="Delimiter">(</span>p_offset &amp; <span class="Constant">0xfff</span><span class="Delimiter">);</span>
<span id="L41" class="LineNr">41 </span>      <a href='003trace.cc.html#L96'>trace</a><span class="Delimiter">(</span><span class="Constant">99</span><span class="Delimiter">,</span> <span class="Constant">&quot;transform&quot;</span><span class="Delimiter">)</span> &lt;&lt; <span class="Constant">&quot;segment &quot;</span> &lt;&lt; i &lt;&lt; <span class="Constant">&quot; begins at address 0x&quot;</span> &lt;&lt; <a href='010vm.cc.html#L408'>HEXWORD</a> &lt;&lt; curr<span class="Delimiter">.</span>start &lt;&lt; end<span class="Delimiter">();</span>
<span id="L42" class="LineNr">42 </span>    <span class="Delimiter">}</span>
<span id="L43" class="LineNr">43 </span>    p_offset += size_of<span class="Delimiter">(</span>curr<span class="Delimiter">);</span>
<span id="L44" class="LineNr">44 </span>    assert<span class="Delimiter">(</span>p_offset &lt; <a href='010vm.cc.html#L98'>SEGMENT_ALIGNMENT</a><span class="Delimiter">);</span>  <span class="Comment">// for now we get less and less available space in each successive segment</span>
<span id="L45" class="LineNr">45 </span>  <span class="Delimiter">}</span>
<span id="L46" class="LineNr">46 </span><span class="Delimiter">}</span>
<span id="L47" class="LineNr">47 </span>
<span id="L48" class="LineNr">48 </span><span class="Normal">uint32_t</span> size_of<span class="Delimiter">(</span><span class="Normal">const</span> segment&amp; s<span class="Delimiter">)</span> <span class="Delimiter">{</span>
<span id="L49" class="LineNr">49 </span>  <span class="Normal">uint32_t</span> sum = <span class="Constant">0</span><span class="Delimiter">;</span>
<span id="L50" class="LineNr">50 </span>  <span class="Normal">for</span> <span class="Delimiter">(</span><span class="Normal">int</span> i = <span class="Constant">0</span><span class="Delimiter">;</span>  i &lt; <a href='001help.cc.html#L166'>SIZE</a><span class="Delimiter">(</span>s<span class="Delimiter">.</span><a href='011run.cc.html#L113'>lines</a><span class="Delimiter">);</span>  ++i<span class="Delimiter">)</span>
<span id="L51" class="LineNr">51 </span>    sum += <a href='035compute_segment_address.cc.html#L56'>num_bytes</a><span class="Delimiter">(</span>s<span class="Delimiter">.</span><a href='011run.cc.html#L113'>lines</a><span class="Delimiter">.</span>at<span class="Delimiter">(</span>i<span class="Delimiter">));</span>
<span id="L52" class="LineNr">52 </span>  <span class="Identifier">return</span> sum<span class="Delimiter">;</span>
<span id="L53" class="LineNr">53 </span><span class="Delimiter">}</span>
<span id="L54" class="LineNr">54 </span>
<span id="L55" class="LineNr">55 </span><span class="Comment">// Assumes all bitfields are packed.</span>
<span id="L56" class="LineNr">56 </span><span class="Normal">uint32_t</span> <a href='035compute_segment_address.cc.html#L56'>num_bytes</a><span class="Delimiter">(</span><span class="Normal">const</span> line&amp; inst<span class="Delimiter">)</span> <span class="Delimiter">{</span>
<span id="L57" class="LineNr">57 </span>  <span class="Normal">uint32_t</span> sum = <span class="Constant">0</span><span class="Delimiter">;</span>
<span id="L58" class="LineNr">58 </span>  <span class="Normal">for</span> <span class="Delimiter">(</span><span class="Normal">int</span> i = <span class="Constant">0</span><span class="Delimiter">;</span>  i &lt; <a href='001help.cc.html#L166'>SIZE</a><span class="Delimiter">(</span>inst<span class="Delimiter">.</span><a href='011run.cc.html#L122'>words</a><span class="Delimiter">);</span>  ++i<span class="Delimiter">)</span>
<span id="L59" class="LineNr">59 </span>    sum += size_of<span class="Delimiter">(</span>inst<span class="Delimiter">.</span><a href='011run.cc.html#L122'>words</a><span class="Delimiter">.</span>at<span class="Delimiter">(</span>i<span class="Delimiter">));</span>
<span id="L60" class="LineNr">60 </span>  <span class="Identifier">return</span> sum<span class="Delimiter">;</span>
<span id="L61" class="LineNr">61 </span><span class="Delimiter">}</span>
<span id="L62" class="LineNr">62 </span>
<span id="L63" class="LineNr">63 </span><span class="Normal">int</span> size_of<span class="Delimiter">(</span><span class="Normal">const</span> word&amp; w<span class="Delimiter">)</span> <span class="Delimiter">{</span>
<span id="L64" class="LineNr">64 </span>  <span class="Normal">if</span> <span class="Delimiter">(</span>has_argument_metadata<span class="Delimiter">(</span>w<span class="Delimiter">,</span> <span class="Constant">&quot;disp32&quot;</span><span class="Delimiter">)</span> || has_argument_metadata<span class="Delimiter">(</span>w<span class="Delimiter">,</span> <span class="Constant">&quot;imm32&quot;</span><span class="Delimiter">))</span>
<span id="L65" class="LineNr">65 </span>    <span class="Identifier">return</span> <span class="Constant">4</span><span class="Delimiter">;</span>
<span id="L66" class="LineNr">66 </span>  <span class="Normal">else</span> <span class="Normal">if</span> <span class="Delimiter">(</span>has_argument_metadata<span class="Delimiter">(</span>w<span class="Delimiter">,</span> <span class="Constant">&quot;disp16&quot;</span><span class="Delimiter">))</span>
<span id="L67" class="LineNr">67 </span>    <span class="Identifier">return</span> <span class="Constant">2</span><span class="Delimiter">;</span>
<span id="L68" class="LineNr">68 </span>  <span class="Comment">// End size_of(word w) Special-cases</span>
<span id="L69" class="LineNr">69 </span>  <span class="Normal">else</span>
<span id="L70" class="LineNr">70 </span>    <span class="Identifier">return</span> <span class="Constant">1</span><span class="Delimiter">;</span>
<span id="L71" class="LineNr">71 </span><span class="Delimiter">}</span>
<span id="L72" class="LineNr">72 </span>
<span id="L73" class="LineNr">73 </span><span class="Comment">//: Dependencies:</span>
<span id="L74" class="LineNr">74 </span><span class="Comment">//: - We'd like to compute segment addresses before setting up global variables,</span>
<span id="L75" class="LineNr">75 </span><span class="Comment">//:   because computing addresses for global variables requires knowing where</span>
<span id="L76" class="LineNr">76 </span><span class="Comment">//:   the data segment starts.</span>
<span id="L77" class="LineNr">77 </span><span class="Comment">//: - We'd like to finish expanding labels before computing segment addresses,</span>
<span id="L78" class="LineNr">78 </span><span class="Comment">//:   because it would make computing the sizes of segments more self-contained</span>
<span id="L79" class="LineNr">79 </span><span class="Comment">//:   (num_bytes).</span>
<span id="L80" class="LineNr">80 </span><span class="Comment">//:</span>
<span id="L81" class="LineNr">81 </span><span class="Comment">//: Decision: compute segment addresses before expanding labels, by being</span>
<span id="L82" class="LineNr">82 </span><span class="Comment">//: aware in this layer of certain argument types that will eventually occupy</span>
<span id="L83" class="LineNr">83 </span><span class="Comment">//: multiple bytes.</span>
<span id="L84" class="LineNr">84 </span><span class="Comment">//:</span>
<span id="L85" class="LineNr">85 </span><span class="Comment">//: The layer to expand labels later hooks into num_bytes() to teach this</span>
<span id="L86" class="LineNr">86 </span><span class="Comment">//: layer that labels occupy zero space in the binary.</span>
</pre>
</body>
</html>
<!-- vim: set foldmethod=manual : -->
83b0a665c4fee2407fac1b714b68'>^
1d1faace ^

1d1faace ^



760f683f ^
1d1faace ^








7a84094a ^
1d1faace ^


471839da ^
1d1faace ^




93d4cc93 ^
4a943d4e ^

















0c1791a9 ^
93d4cc93 ^
4a943d4e ^







































































































































































































































































































































































































































































































































































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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307

                                                                         























                                        
 



                                                                             
 



                                                                           
                                

                                                                                                                                                   
 


                                                                                      
               
                                                                                                     
              

 

                                                                      

                                                    
 
                                  


                                                                          
                                                                                                                       

                                                                             
                                                                                  
                           


   

                                                                         

                                            
                                                                         
                                                       
                                                                                                            


         
       
                             
                                                                                                                                   
                                
                                              

                                                                 

                                                                                                  




                                                                                                  
                                                                                      
                                                                                                 
                                                                                         


                   
                                                                                
                                                
                                                                                           
                                                                                      





                   



                                                                                  
                          
                                                                                                               
                              
                                                     
                                                    


                                                                                             







                                                                                                                                 


                                                                                                                            
   
                       







                                                                                          
                                                                               

                                          
                                                                            






                                  

     
             

 
                                                                  
                                           

                                                        

 
                                                            
                                              
                                                        
                                                                

                  
                                                     
                                                             

                  


               
                                                                                   

                      
                                                                      

 
                                                                                                                 

                        
                                                                                                      
                                                                                                                                   
                                      
                                                                         









                                                                                   

 
                                                      
                                               

 
                                                           
                          
                                                       


                                                                                                 
                                                                                    


                                                      
                                                                           
                                                   
                                                                        


                







                                                          
                                                                                 
















                                                                        

                                                                                                          
                                                       
                                                  
                                                                                           
                
                                         
                                                    

                                                                 
                             
                                          
                                     
                                                                                                                  
 

                                                                                                                    






                                                                                     
                                                                                                                                              
                                 

                                 
                                                                                        
   
                                           

                                                                                                   
                                                                                      
                                                               
                                                                                                  
                       
                         
   
                                                               
 
                                                                                                                                          
                                                                
                                                                                                                                 

                                                                        

                                                   


                                          
                                                                                
                                     
                                                       
                                                                                 
                                                    
                                                                              
                                                   
                                            
                                                                             
                                                         
                                                                                                                       
                                                         
                                                                                                                     


   
                                                                                                                        
                                                                                                         
                                              
                                               
                                                                                           

           
                                                                   


                                                                
                
                                                                                                                                                     

           
                                         
                                                                                                                       
                            
                                                                                                  

 
                                                                                                                                                                           
                                                                      
                                     
                                                                 
                                                        
                              
                                                                                                     
                                                                                                              
   
                                                            
                                     
                                                              
                                                  
                                    
                           
                                                                                                           


   


                                                                                                                                                                                                                                        

 
                                                                                                                                                                                                                                                                                     

                             
                           
                                                                                                       
                                                                                                                         
                                                                                           
           
   



                                                                                                                         







                                                                                                                                     
       
                                                         
                                                                                                                                       
                                                                                 
       

                                                                                                 
                                                                                                                                









                                                                                   


        
                                                                                                                                                          
                                                                                                                                                            
   

 
                                                                                                  
                      
                               
                                                                               
                                                          
                                                                                 
                                                                            
                                                       
                                                                              
                    
                                                      
                                               
                                                                                               
                                                      
                                                                             
                                                   
                                                                          
                                                                                
                                                                                      



                                                                     



     

                                                                                                                
                                                                                      
                
                                                                                                                      

           
                                             

 
                                                                                               
                    
                    



                                                                                                                                                                                                                



                                                    



                                                                        
                                                           
                                                                                           



                                                         
     

                                                                                 
   
        
                         
   
 
 


                                                             
                                                      
                                                                                 
                                                   










                                                                              
                                             


                                         



                                    




                       
                                                     
                              
                   


             
                                                               



                                    
                        



             
                                                                                      
                                                                                                   
                                                          
                                                                      
                                                       
                                                                   
                                                      
                                               
                                                      
                                                                  
                                                   
                                                               


   
                                                                              
                                                         
                                                                                                      
                                                                                                                   

           
                            
                                                                                                                  



           



































































































































































                                                                              
 

                                                                             



                                                                                 
                                           








                                                                           
                 


                                  
                                                   




                                        
                                                       

















                                                                        
 
                                                                                               







































































































































































































































































































































































































































































































































































                                                                                             
//:: Like container definitions, recipes too can contain type parameters.

void test_shape_shifting_recipe() {
  run(
      "def main [\n"
      "  10:point <- merge 14, 15\n"
      "  12:point <- foo 10:point\n"
      "]\n"
      // non-matching variant
      "def foo a:num -> result:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- copy 34\n"
      "]\n"
      // matching shape-shifting variant
      "def foo a:_t -> result:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- copy a\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 14 in location 12\n"
      "mem: storing 15 in location 13\n"
  );
}

//: Before anything else, disable transforms for shape-shifting recipes and
//: make sure we never try to actually run a shape-shifting recipe. We should
//: be rewriting such instructions to *specializations* with the type
//: ingredients filled in.

//: One exception (and this makes things very ugly): we need to expand type
//: abbreviations in shape-shifting recipes because we need them types for
//: deciding which variant to specialize.

:(before "End Transform Checks")
r.transformed_until = t;
if (Transform.at(t) != static_cast<transform_fn>(expand_type_abbreviations) && any_type_ingredient_in_header(/*recipe_ordinal*/p->first)) continue;

:(after "Running One Instruction")
if (Current_routine->calls.front().running_step_index == 0
    && any_type_ingredient_in_header(Current_routine->calls.front().running_recipe)) {
//?   DUMP("");
  raise << "ran into unspecialized shape-shifting recipe " << current_recipe_name() << '\n' << end();
//?   exit(0);
}

//: Make sure we don't match up literals with type ingredients without
//: specialization.
:(before "End Matching Types For Literal(to)")
if (contains_type_ingredient_name(to)) return false;

:(after "Static Dispatch Phase 2")
candidates = strictly_matching_shape_shifting_variants(inst, variants);
if (!candidates.empty()) {
  recipe_ordinal exemplar = best_shape_shifting_variant(inst, candidates);
  trace(102, "transform") << "found variant to specialize: " << exemplar << ' ' << get(Recipe, exemplar).name << end();
  string new_recipe_name = insert_new_variant(exemplar, inst, caller_recipe);
  if (new_recipe_name != "") {
    trace(102, "transform") << "new specialization: " << new_recipe_name << end();
    return new_recipe_name;
  }
}

//: before running Mu programs, make sure no unspecialized shape-shifting
//: recipes can be called

:(before "End Instruction Operation Checks")
if (contains_key(Recipe, inst.operation) && !is_primitive(inst.operation)
    && any_type_ingredient_in_header(inst.operation)) {
  raise << maybe(caller.name) << "instruction '" << inst.name << "' has no valid specialization\n" << end();
  return;
}

:(code)
// phase 3 of static dispatch
vector<recipe_ordinal> strictly_matching_shape_shifting_variants(const instruction& inst, const vector<recipe_ordinal>& variants) {
  vector<recipe_ordinal> result;
  for (int i = 0;  i < SIZE(variants);  ++i) {
    if (variants.at(i) == -1) continue;
    if (!any_type_ingredient_in_header(variants.at(i))) continue;
    if (!all_concrete_header_reagents_strictly_match(inst, get(Recipe, variants.at(i)))) continue;
    result.push_back(variants.at(i));
  }
  return result;
}

bool all_concrete_header_reagents_strictly_match(const instruction& inst, const recipe& variant) {
  for (int i = 0;  i < min(SIZE(inst.ingredients), SIZE(variant.ingredients));  ++i) {
    if (!concrete_type_names_strictly_match(variant.ingredients.at(i), inst.ingredients.at(i))) {
      trace(103, "transform") << "concrete-type match failed: ingredient " << i << end();
      return false;
    }
  }
  for (int i = 0;  i < min(SIZE(inst.products), SIZE(variant.products));  ++i) {
    if (is_dummy(inst.products.at(i))) continue;
    if (!concrete_type_names_strictly_match(variant.products.at(i), inst.products.at(i))) {
      trace(103, "transform") << "concrete-type match failed: product " << i << end();
      return false;
    }
  }
  return true;
}

// manual prototype
vector<recipe_ordinal> keep_max(const instruction&, const vector<recipe_ordinal>&,
                                int (*)(const instruction&, recipe_ordinal));

// tie-breaker for phase 3
recipe_ordinal best_shape_shifting_variant(const instruction& inst, const vector<recipe_ordinal>& candidates) {
  assert(!candidates.empty());
  if (SIZE(candidates) == 1) return candidates.at(0);
//?   cerr << "A picking shape-shifting variant:\n";
  vector<recipe_ordinal> result1 = keep_max(inst, candidates, number_of_concrete_type_names);
  assert(!result1.empty());
  if (SIZE(result1) == 1) return result1.at(0);
//?   cerr << "B picking shape-shifting variant:\n";
  vector<recipe_ordinal> result2 = keep_max(inst, result1, arity_fit);
  assert(!result2.empty());
  if (SIZE(result2) == 1) return result2.at(0);
//?   cerr << "C picking shape-shifting variant:\n";
  vector<recipe_ordinal> result3 = keep_max(inst, result2, number_of_type_ingredients);
  if (SIZE(result3) > 1) {
    raise << "\nCouldn't decide the best shape-shifting variant for instruction '" << to_original_string(inst) << "'\n" << end();
    cerr << "This is a hole in Mu. Please copy the following candidates into an email to Kartik Agaram <mu@akkartik.com>\n";
    for (int i = 0;  i < SIZE(candidates);  ++i)
      cerr << "  " << header_label(get(Recipe, candidates.at(i))) << '\n';
  }
  return result3.at(0);
}

vector<recipe_ordinal> keep_max(const instruction& inst, const vector<recipe_ordinal>& in,
                                int (*scorer)(const instruction&, recipe_ordinal)) {
  assert(!in.empty());
  vector<recipe_ordinal> out;
  out.push_back(in.at(0));
  int best_score = (*scorer)(inst, in.at(0));
//?   cerr << best_score << " " << header_label(get(Recipe, in.at(0))) << '\n';
  for (int i = 1;  i < SIZE(in);  ++i) {
    int score = (*scorer)(inst, in.at(i));
//?     cerr << score << " " << header_label(get(Recipe, in.at(i))) << '\n';
    if (score == best_score) {
      out.push_back(in.at(i));
    }
    else if (score > best_score) {
      best_score = score;
      out.clear();
      out.push_back(in.at(i));
    }
  }
  return out;
}

int arity_fit(const instruction& inst, recipe_ordinal candidate) {
  const recipe& r = get(Recipe, candidate);
  return (SIZE(inst.products) - SIZE(r.products))
       + (SIZE(r.ingredients) - SIZE(inst.ingredients));
}

bool any_type_ingredient_in_header(recipe_ordinal variant) {
  const recipe& caller = get(Recipe, variant);
  for (int i = 0;  i < SIZE(caller.ingredients);  ++i) {
    if (contains_type_ingredient_name(caller.ingredients.at(i)))
      return true;
  }
  for (int i = 0;  i < SIZE(caller.products);  ++i) {
    if (contains_type_ingredient_name(caller.products.at(i)))
      return true;
  }
  return false;
}

bool concrete_type_names_strictly_match(reagent/*copy*/ to, reagent/*copy*/ from) {
  canonize_type(to);
  canonize_type(from);
  return concrete_type_names_strictly_match(to.type, from.type, from);
}

bool concrete_type_names_strictly_match(const type_tree* to, const type_tree* from, const reagent& rhs_reagent) {
  if (!to) return !from;
  if (!from) return !to;
  if (to->atom && is_type_ingredient_name(to->name)) return true;  // type ingredient matches anything
  if (!to->atom && to->right == NULL && to->left != NULL && to->left->atom && is_type_ingredient_name(to->left->name)) return true;
  if (from->atom && is_mu_address(to))
    return from->name == "literal-address" && rhs_reagent.name == "null";
  if (!from->atom && !to->atom)
    return concrete_type_names_strictly_match(to->left, from->left, rhs_reagent)
        && concrete_type_names_strictly_match(to->right, from->right, rhs_reagent);
  if (from->atom != to->atom) return false;
  // both from and to are atoms
  if (from->name == "literal")
    return Literal_type_names.find(to->name) != Literal_type_names.end();
  if (to->name == "literal")
    return Literal_type_names.find(from->name) != Literal_type_names.end();
  return to->name == from->name;
}

bool contains_type_ingredient_name(const reagent& x) {
  return contains_type_ingredient_name(x.type);
}

bool contains_type_ingredient_name(const type_tree* type) {
  if (!type) return false;
  if (is_type_ingredient_name(type->name)) return true;
  return contains_type_ingredient_name(type->left) || contains_type_ingredient_name(type->right);
}

int number_of_concrete_type_names(const instruction& /*unused*/, recipe_ordinal r) {
  const recipe& caller = get(Recipe, r);
  int result = 0;
  for (int i = 0;  i < SIZE(caller.ingredients);  ++i)
    result += number_of_concrete_type_names(caller.ingredients.at(i).type);
  for (int i = 0;  i < SIZE(caller.products);  ++i)
    result += number_of_concrete_type_names(caller.products.at(i).type);
  return result;
}

int number_of_concrete_type_names(const type_tree* type) {
  if (!type) return 0;
  if (type->atom)
    return is_type_ingredient_name(type->name) ? 0 : 1;
  return number_of_concrete_type_names(type->left)
       + number_of_concrete_type_names(type->right);
}

int number_of_type_ingredients(const instruction& /*unused*/, recipe_ordinal r) {
  const recipe& caller = get(Recipe, r);
  int result = 0;
  for (int i = 0;  i < SIZE(caller.ingredients);  ++i)
    result += number_of_type_ingredients(caller.ingredients.at(i).type);
  for (int i = 0;  i < SIZE(caller.products);  ++i)
    result += number_of_type_ingredients(caller.products.at(i).type);
  return result;
}

int number_of_type_ingredients(const type_tree* type) {
  if (!type) return 0;
  if (type->atom)
    return is_type_ingredient_name(type->name) ? 1 : 0;
  return number_of_type_ingredients(type->left)
       + number_of_type_ingredients(type->right);
}

// returns name of new variant
string insert_new_variant(recipe_ordinal exemplar, const instruction& inst, const recipe& caller_recipe) {
  string new_name = next_unused_recipe_name(inst.name);
  assert(!contains_key(Recipe_ordinal, new_name));
  recipe_ordinal new_recipe_ordinal = put(Recipe_ordinal, new_name, Next_recipe_ordinal++);
  // make a copy
  assert(contains_key(Recipe, exemplar));
  assert(!contains_key(Recipe, new_recipe_ordinal));
  put(Recipe, new_recipe_ordinal, /*copy*/get(Recipe, exemplar));
  recipe& new_recipe = get(Recipe, new_recipe_ordinal);
  new_recipe.name = new_name;
  new_recipe.ordinal = new_recipe_ordinal;
  new_recipe.is_autogenerated = true;
  trace(103, "transform") << "switching " << inst.name << " to specialized " << header_label(new_recipe) << end();

  trace(102, "transform") << "transforming new specialization: " << new_recipe.name << end();
  trace(102, "transform") << new_recipe.name << ": performing transforms until check_or_set_types_by_name" << end();
  int transform_index = 0;
  for (transform_index = 0;  transform_index < SIZE(Transform);  ++transform_index) {
    if (Transform.at(transform_index) == check_or_set_types_by_name) break;
    (*Transform.at(transform_index))(new_recipe_ordinal);
  }
  new_recipe.transformed_until = transform_index-1;

  trace(102, "transform") << new_recipe.name << ": performing type-ingredient-aware version of transform check_or_set_types_by_name" << end();
  compute_type_names(new_recipe);
  new_recipe.transformed_until++;

  trace(102, "transform") << new_recipe.name << ": replacing type ingredients" << end();
  {
    map<string, const type_tree*> mappings;
    bool error = false;
    compute_type_ingredient_mappings(get(Recipe, exemplar), inst, mappings, caller_recipe, &error);
    if (!error) error = (SIZE(mappings) != type_ingredient_count_in_header(exemplar));
    if (!error) replace_type_ingredients(new_recipe, mappings);
    for (map<string, const type_tree*>::iterator p = mappings.begin();  p != mappings.end();  ++p)
      delete p->second;
    if (error) return "";
  }
  ensure_all_concrete_types(new_recipe, get(Recipe, exemplar));

  trace(102, "transform") << new_recipe.name << ": recording the new variant before recursively calling resolve_ambiguous_calls" << end();
  get(Recipe_variants, inst.name).push_back(new_recipe_ordinal);
  trace(102, "transform") << new_recipe.name << ": performing remaining transforms (including resolve_ambiguous_calls)" << end();
  for (/*nada*/;  transform_index < SIZE(Transform);  ++transform_index)
    (*Transform.at(transform_index))(new_recipe_ordinal);
  new_recipe.transformed_until = SIZE(Transform)-1;
  return new_recipe.name;
}

void compute_type_names(recipe& variant) {
  trace(103, "transform") << "-- compute type names: " << variant.name << end();
  map<string, type_tree*> type_names;
  for (int i = 0;  i < SIZE(variant.ingredients);  ++i)
    save_or_deduce_type_name(variant.ingredients.at(i), type_names, variant, "");
  for (int i = 0;  i < SIZE(variant.products);  ++i)
    save_or_deduce_type_name(variant.products.at(i), type_names, variant, "");
  for (int i = 0;  i < SIZE(variant.steps);  ++i) {
    instruction& inst = variant.steps.at(i);
    trace(103, "transform") << "  instruction: " << to_string(inst) << end();
    for (int in = 0;  in < SIZE(inst.ingredients);  ++in)
      save_or_deduce_type_name(inst.ingredients.at(in), type_names, variant, " in '" + to_original_string(inst) + "'");
    for (int out = 0;  out < SIZE(inst.products);  ++out)
      save_or_deduce_type_name(inst.products.at(out), type_names, variant, " in '" + to_original_string(inst) + "'");
  }
}

void save_or_deduce_type_name(reagent& x, map<string, type_tree*>& type, const recipe& variant, const string& context) {
  trace(104, "transform") << "    checking " << to_string(x) << ": " << names_to_string(x.type) << end();
  if (!x.type && contains_key(type, x.name)) {
    x.type = new type_tree(*get(type, x.name));
    trace(104, "transform") << "    deducing type to " << names_to_string(x.type) << end();
    return;
  }
  // Type Check in Type-ingredient-aware check_or_set_types_by_name
  // This is different from check_or_set_types_by_name.
  // We've found it useful in the past for tracking down bugs in
  // specialization.
  if (!x.type) {
    raise << maybe(variant.original_name) << "unknown type for '" << x.original_string << "'" << context << " (check the name for typos)\n" << end();
    return;
  }
  if (contains_key(type, x.name)) return;
  if (x.type->name == "offset" || x.type->name == "variant") return;  // special-case for container-access instructions
  put(type, x.name, x.type);
  trace(103, "transform") << "type of '" << x.name << "' is " << names_to_string(x.type) << end();
}

void compute_type_ingredient_mappings(const recipe& exemplar, const instruction& inst, map<string, const type_tree*>& mappings, const recipe& caller_recipe, bool* error) {
  int limit = min(SIZE(inst.ingredients), SIZE(exemplar.ingredients));
  for (int i = 0;  i < limit;  ++i) {
    const reagent& exemplar_reagent = exemplar.ingredients.at(i);
    reagent/*copy*/ ingredient = inst.ingredients.at(i);
    canonize_type(ingredient);
    if (is_mu_address(exemplar_reagent) && ingredient.name == "null") continue;  // assume it matches
    accumulate_type_ingredients(exemplar_reagent, ingredient, mappings, exemplar, inst, caller_recipe, error);
  }
  limit = min(SIZE(inst.products), SIZE(exemplar.products));
  for (int i = 0;  i < limit;  ++i) {
    const reagent& exemplar_reagent = exemplar.products.at(i);
    reagent/*copy*/ product = inst.products.at(i);
    if (is_dummy(product)) continue;
    canonize_type(product);
    accumulate_type_ingredients(exemplar_reagent, product, mappings, exemplar, inst, caller_recipe, error);
  }
}

void accumulate_type_ingredients(const reagent& exemplar_reagent, reagent& refinement, map<string, const type_tree*>& mappings, const recipe& exemplar, const instruction& call_instruction, const recipe& caller_recipe, bool* error) {
  assert(refinement.type);
  accumulate_type_ingredients(exemplar_reagent.type, refinement.type, mappings, exemplar, exemplar_reagent, call_instruction, caller_recipe, error);
}

void accumulate_type_ingredients(const type_tree* exemplar_type, const type_tree* refinement_type, map<string, const type_tree*>& mappings, const recipe& exemplar, const reagent& exemplar_reagent, const instruction& call_instruction, const recipe& caller_recipe, bool* error) {
  if (!exemplar_type) return;
  if (!refinement_type) {
    // probably a bug in mu
    // todo: make this smarter; only flag an error if exemplar_type contains some *new* type ingredient
    raise << maybe(exemplar.name) << "missing type ingredient for " << exemplar_reagent.original_string << '\n' << end();
    raise << "  (called from '" << to_original_string(call_instruction) << "')\n" << end();
    return;
  }
  if (!exemplar_type->atom && exemplar_type->right == NULL && !refinement_type->atom && refinement_type->right != NULL) {
    exemplar_type = exemplar_type->left;
    assert_for_now(exemplar_type->atom);
  }
  if (exemplar_type->atom) {
    if (is_type_ingredient_name(exemplar_type->name)) {
      const type_tree* curr_refinement_type = NULL;  // temporary heap allocation; must always be deleted before it goes out of scope
      if (exemplar_type->atom)
        curr_refinement_type = new type_tree(*refinement_type);
      else {
        assert(!refinement_type->atom);
        curr_refinement_type = new type_tree(*refinement_type->left);
      }
      if (!contains_key(mappings, exemplar_type->name)) {
        trace(103, "transform") << "adding mapping from " << exemplar_type->name << " to " << to_string(curr_refinement_type) << end();
        put(mappings, exemplar_type->name, new type_tree(*curr_refinement_type));
      }
      else {
        if (!deeply_equal_type_names(get(mappings, exemplar_type->name), curr_refinement_type)) {
          raise << maybe(caller_recipe.name) << "no call found for '" << to_original_string(call_instruction) << "'\n" << end();
          *error = true;
          delete curr_refinement_type;
          return;
        }
        if (get(mappings, exemplar_type->name)->name == "literal") {
          delete get(mappings, exemplar_type->name);
          put(mappings, exemplar_type->name, new type_tree(*curr_refinement_type));
        }
      }
      delete curr_refinement_type;
    }
  }
  else {
    accumulate_type_ingredients(exemplar_type->left, refinement_type->left, mappings, exemplar, exemplar_reagent, call_instruction, caller_recipe, error);
    accumulate_type_ingredients(exemplar_type->right, refinement_type->right, mappings, exemplar, exemplar_reagent, call_instruction, caller_recipe, error);
  }
}

void replace_type_ingredients(recipe& new_recipe, const map<string, const type_tree*>& mappings) {
  // update its header
  if (mappings.empty()) return;
  trace(103, "transform") << "replacing in recipe header ingredients" << end();
  for (int i = 0;  i < SIZE(new_recipe.ingredients);  ++i)
    replace_type_ingredients(new_recipe.ingredients.at(i), mappings, new_recipe);
  trace(103, "transform") << "replacing in recipe header products" << end();
  for (int i = 0;  i < SIZE(new_recipe.products);  ++i)
    replace_type_ingredients(new_recipe.products.at(i), mappings, new_recipe);
  // update its body
  for (int i = 0;  i < SIZE(new_recipe.steps);  ++i) {
    instruction& inst = new_recipe.steps.at(i);
    trace(103, "transform") << "replacing in instruction '" << to_string(inst) << "'" << end();
    for (int j = 0;  j < SIZE(inst.ingredients);  ++j)
      replace_type_ingredients(inst.ingredients.at(j), mappings, new_recipe);
    for (int j = 0;  j < SIZE(inst.products);  ++j)
      replace_type_ingredients(inst.products.at(j), mappings, new_recipe);
    // special-case for new: replace type ingredient in first ingredient *value*
    if (inst.name == "new" && inst.ingredients.at(0).type->name != "literal-string") {
      type_tree* type = parse_type_tree(inst.ingredients.at(0).name);
      replace_type_ingredients(type, mappings);
      inst.ingredients.at(0).name = inspect(type);
      delete type;
    }
  }
}

void replace_type_ingredients(reagent& x, const map<string, const type_tree*>& mappings, const recipe& caller) {
  string before = to_string(x);
  trace(103, "transform") << "replacing in ingredient " << x.original_string << end();
  if (!x.type) {
    raise << "specializing " << caller.original_name << ": missing type for '" << x.original_string << "'\n" << end();
    return;
  }
  replace_type_ingredients(x.type, mappings);
}

void replace_type_ingredients(type_tree* type, const map<string, const type_tree*>& mappings) {
  if (!type) return;
  if (!type->atom) {
    if (type->right == NULL && type->left != NULL && type->left->atom && contains_key(mappings, type->left->name) && !get(mappings, type->left->name)->atom && get(mappings, type->left->name)->right != NULL) {
      *type = *get(mappings, type->left->name);
      return;
    }
    replace_type_ingredients(type->left, mappings);
    replace_type_ingredients(type->right, mappings);
    return;
  }
  if (contains_key(Type_ordinal, type->name))  // todo: ugly side effect
    type->value = get(Type_ordinal, type->name);
  if (!contains_key(mappings, type->name))
    return;
  const type_tree* replacement = get(mappings, type->name);
  trace(103, "transform") << type->name << " => " << names_to_string(replacement) << end();
  if (replacement->atom) {
    if (!contains_key(Type_ordinal, replacement->name)) {
      // error in program; should be reported elsewhere
      return;
    }
    type->name = (replacement->name == "literal") ? "number" : replacement->name;
    type->value = get(Type_ordinal, type->name);
  }
  else {
    *type = *replacement;
  }
}

int type_ingredient_count_in_header(recipe_ordinal variant) {
  const recipe& caller = get(Recipe, variant);
  set<string> type_ingredients;
  for (int i = 0;  i < SIZE(caller.ingredients);  ++i)
    accumulate_type_ingredients(caller.ingredients.at(i).type, type_ingredients);
  for (int i = 0;  i < SIZE(caller.products);  ++i)
    accumulate_type_ingredients(caller.products.at(i).type, type_ingredients);
  return SIZE(type_ingredients);
}

void accumulate_type_ingredients(const type_tree* type, set<string>& out) {
  if (!type) return;
  if (is_type_ingredient_name(type->name)) out.insert(type->name);
  accumulate_type_ingredients(type->left, out);
  accumulate_type_ingredients(type->right, out);
}

type_tree* parse_type_tree(const string& s) {
  string_tree* s2 = parse_string_tree(s);
  type_tree* result = new_type_tree(s2);
  delete s2;
  return result;
}

string inspect(const type_tree* x) {
  ostringstream out;
  dump_inspect(x, out);
  return out.str();
}

void dump_inspect(const type_tree* x, ostream& out) {
  if (!x->left && !x->right) {
    out << x->name;
    return;
  }
  out << '(';
  for (const type_tree* curr = x;  curr;  curr = curr->right) {
    if (curr != x) out << ' ';
    if (curr->left)
      dump_inspect(curr->left, out);
    else
      out << curr->name;
  }
  out << ')';
}

void ensure_all_concrete_types(/*const*/ recipe& new_recipe, const recipe& exemplar) {
  trace(103, "transform") << "-- ensure all concrete types in recipe " << new_recipe.name << end();
  for (int i = 0;  i < SIZE(new_recipe.ingredients);  ++i)
    ensure_all_concrete_types(new_recipe.ingredients.at(i), exemplar);
  for (int i = 0;  i < SIZE(new_recipe.products);  ++i)
    ensure_all_concrete_types(new_recipe.products.at(i), exemplar);
  for (int i = 0;  i < SIZE(new_recipe.steps);  ++i) {
    instruction& inst = new_recipe.steps.at(i);
    for (int j = 0;  j < SIZE(inst.ingredients);  ++j)
      ensure_all_concrete_types(inst.ingredients.at(j), exemplar);
    for (int j = 0;  j < SIZE(inst.products);  ++j)
      ensure_all_concrete_types(inst.products.at(j), exemplar);
  }
}

void ensure_all_concrete_types(/*const*/ reagent& x, const recipe& exemplar) {
  if (!x.type || contains_type_ingredient_name(x.type)) {
    raise << maybe(exemplar.name) << "failed to map a type to " << x.original_string << '\n' << end();
    if (!x.type) x.type = new type_tree("added_by_ensure_all_concrete_types", 0);  // just to prevent crashes later
    return;
  }
  if (x.type->value == -1) {
    raise << maybe(exemplar.name) << "failed to map a type to the unknown " << x.original_string << '\n' << end();
    return;
  }
}

void test_shape_shifting_recipe_2() {
  run(
      "def main [\n"
      "  10:point <- merge 14, 15\n"
      "  12:point <- foo 10:point\n"
      "]\n"
      // non-matching shape-shifting variant
      "def foo a:_t, b:_t -> result:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- copy 34\n"
      "]\n"
      // matching shape-shifting variant
      "def foo a:_t -> result:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- copy a\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 14 in location 12\n"
      "mem: storing 15 in location 13\n"
  );
}

void test_shape_shifting_recipe_nonroot() {
  run(
      "def main [\n"
      "  10:foo:point <- merge 14, 15, 16\n"
      "  20:point <- bar 10:foo:point\n"
      "]\n"
      // shape-shifting recipe with type ingredient following some other type
      "def bar a:foo:_t -> result:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- get a, x:offset\n"
      "]\n"
      "container foo:_t [\n"
      "  x:_t\n"
      "  y:num\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 14 in location 20\n"
      "mem: storing 15 in location 21\n"
  );
}

void test_shape_shifting_recipe_nested() {
  run(
      "container c:_a:_b [\n"
      "  a:_a\n"
      "  b:_b\n"
      "]\n"
      "def main [\n"
      "  s:text <- new [abc]\n"
      "  {x: (c (address array character) number)} <- merge s, 34\n"
      "  foo x\n"
      "]\n"
      "def foo x:c:_bar:_baz [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "]\n"
  );
  // no errors
}

void test_shape_shifting_recipe_type_deduction_ignores_offsets() {
  run(
      "def main [\n"
      "  10:foo:point <- merge 14, 15, 16\n"
      "  20:point <- bar 10:foo:point\n"
      "]\n"
      "def bar a:foo:_t -> result:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  x:num <- copy 1\n"
      "  result <- get a, x:offset  # shouldn't collide with other variable\n"
      "]\n"
      "container foo:_t [\n"
      "  x:_t\n"
      "  y:num\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 14 in location 20\n"
      "mem: storing 15 in location 21\n"
  );
}

void test_shape_shifting_recipe_empty() {
  run(
      "def main [\n"
      "  foo 1\n"
      "]\n"
      // shape-shifting recipe with no body
      "def foo a:_t [\n"
      "]\n"
  );
  // shouldn't crash
}

void test_shape_shifting_recipe_handles_shape_shifting_new_ingredient() {
  run(
      "def main [\n"
      "  1:&:foo:point <- bar 3\n"
      "  11:foo:point <- copy *1:&:foo:point\n"
      "]\n"
      "container foo:_t [\n"
      "  x:_t\n"
      "  y:num\n"
      "]\n"
      "def bar x:num -> result:&:foo:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
         // new refers to _t in its ingredient *value*
      "  result <- new {(foo _t) : type}\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 0 in location 11\n"
      "mem: storing 0 in location 12\n"
      "mem: storing 0 in location 13\n"
  );
}

void test_shape_shifting_recipe_handles_shape_shifting_new_ingredient_2() {
  run(
      "def main [\n"
      "  1:&:foo:point <- bar 3\n"
      "  11:foo:point <- copy *1:&:foo:point\n"
      "]\n"
      "def bar x:num -> result:&:foo:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
         // new refers to _t in its ingredient *value*
      "  result <- new {(foo _t) : type}\n"
      "]\n"
      // container defined after use
      "container foo:_t [\n"
      "  x:_t\n"
      "  y:num\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 0 in location 11\n"
      "mem: storing 0 in location 12\n"
      "mem: storing 0 in location 13\n"
  );
}

void test_shape_shifting_recipe_called_with_dummy() {
  run(
      "def main [\n"
      "  _ <- bar 34\n"
      "]\n"
      "def bar x:_t -> result:&:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- copy null\n"
      "]\n"
  );
  CHECK_TRACE_COUNT("error", 0);
}

// this one needs a little more fine-grained control
void test_shape_shifting_new_ingredient_does_not_pollute_global_namespace() {
  // if you specialize a shape-shifting recipe that allocates a type-ingredient..
  transform("def barz x:_elem [\n"
            "  local-scope\n"
            "  load-ingredients\n"
            "  y:&:num <- new _elem:type\n"
            "]\n"
            "def fooz [\n"
            "  local-scope\n"
            "  barz 34\n"
            "]\n");
  // ..and if you then try to load a new shape-shifting container with that
  // type-ingredient
  run("container foo:_elem [\n"
      "  x:_elem\n"
      "  y:num\n"
      "]\n");
  // then it should work as usual
  reagent callsite("x:foo:point");
  reagent element = element_type(callsite.type, 0);
  CHECK_EQ(element.name, "x");
  CHECK_EQ(element.type->name, "point");
  CHECK(!element.type->right);
}

//: specializing a type ingredient with a compound type
void test_shape_shifting_recipe_supports_compound_types() {
  run(
      "def main [\n"
      "  1:&:point <- new point:type\n"
      "  *1:&:point <- put *1:&:point, y:offset, 34\n"
      "  3:&:point <- bar 1:&:point  # specialize _t to address:point\n"
      "  5:point <- copy *3:&:point\n"
      "]\n"
      "def bar a:_t -> result:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- copy a\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 6\n"
  );
}

//: specializing a type ingredient with a compound type -- while *inside* another compound type
void test_shape_shifting_recipe_supports_compound_types_2() {
  run(
      "container foo:_t [\n"
      "  value:_t\n"
      "]\n"
      "def bar x:&:foo:_t -> result:_t [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  result <- get *x, value:offset\n"
      "]\n"
      "def main [\n"
      "  1:&:foo:&:point <- new {(foo address point): type}\n"
      "  2:&:point <- bar 1:&:foo:&:point\n"
      "]\n"
  );
  // no errors; call to 'bar' successfully specialized
}

void test_shape_shifting_recipe_error() {
  Hide_errors = true;
  run(
      "def main [\n"
      "  a:num <- copy 3\n"
      "  b:&:num <- foo a\n"
      "]\n"
      "def foo a:_t -> b:_t [\n"
      "  load-ingredients\n"
      "  b <- copy a\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "error: main: no call found for 'b:&:num <- foo a'\n"
  );
}

void test_specialize_inside_recipe_without_header() {
  run(
      "def main [\n"
      "  foo 3\n"
      "]\n"
      "def foo [\n"
      "  local-scope\n"
      "  x:num <- next-ingredient  # ensure no header\n"
      "  1:num/raw <- bar x  # call a shape-shifting recipe\n"
      "]\n"
      "def bar x:_elem -> y:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  y <- add x, 1\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 4 in location 1\n"
  );
}

void test_specialize_with_literal() {
  run(
      "def main [\n"
      "  local-scope\n"
         // permit literal to map to number
      "  1:num/raw <- foo 3\n"
      "]\n"
      "def foo x:_elem -> y:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  y <- add x, 1\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 4 in location 1\n"
  );
}

void test_specialize_with_literal_2() {
  run(
      "def main [\n"
      "  local-scope\n"
         // permit literal to map to character
      "  1:char/raw <- foo 3\n"
      "]\n"
      "def foo x:_elem -> y:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  y <- add x, 1\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 4 in location 1\n"
  );
}

void test_specialize_with_literal_3() {
  run(
      "def main [\n"
      "  local-scope\n"
         // permit '0' to map to address to shape-shifting type-ingredient
      "  1:&:char/raw <- foo null\n"
      "]\n"
      "def foo x:&:_elem -> y:&:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  y <- copy x\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 0 in location 1\n"
  );
  CHECK_TRACE_COUNT("error", 0);
}

void test_specialize_with_literal_4() {
  Hide_errors = true;
  run(
      "def main [\n"
      "  local-scope\n"
         // ambiguous call: what's the type of its ingredient?!
      "  foo 0\n"
      "]\n"
      "def foo x:&:_elem -> y:&:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  y <- copy x\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "error: main: instruction 'foo' has no valid specialization\n"
  );
}

void test_specialize_with_literal_5() {
  run(
      "def main [\n"
      "  foo 3, 4\n"  // recipe mapping two variables to literals
      "]\n"
      "def foo x:_elem, y:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  1:num/raw <- add x, y\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 7 in location 1\n"
  );
}

void test_multiple_shape_shifting_variants() {
  run(
      // try to call two different shape-shifting recipes with the same name
      "def main [\n"
      "  e1:d1:num <- merge 3\n"
      "  e2:d2:num <- merge 4, 5\n"
      "  1:num/raw <- foo e1\n"
      "  2:num/raw <- foo e2\n"
      "]\n"
      // the two shape-shifting definitions
      "def foo a:d1:_elem -> b:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 34\n"
      "]\n"
      "def foo a:d2:_elem -> b:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 35\n"
      "]\n"
      // the shape-shifting containers they use
      "container d1:_elem [\n"
      "  x:_elem\n"
      "]\n"
      "container d2:_elem [\n"
      "  x:num\n"
      "  y:_elem\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 1\n"
      "mem: storing 35 in location 2\n"
  );
}

void test_multiple_shape_shifting_variants_2() {
  run(
      // static dispatch between shape-shifting variants, _including pointer lookups_
      "def main [\n"
      "  e1:d1:num <- merge 3\n"
      "  e2:&:d2:num <- new {(d2 number): type}\n"
      "  1:num/raw <- foo e1\n"
      "  2:num/raw <- foo *e2\n"  // different from previous scenario
      "]\n"
      "def foo a:d1:_elem -> b:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 34\n"
      "]\n"
      "def foo a:d2:_elem -> b:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 35\n"
      "]\n"
      "container d1:_elem [\n"
      "  x:_elem\n"
      "]\n"
      "container d2:_elem [\n"
      "  x:num\n"
      "  y:_elem\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 1\n"
      "mem: storing 35 in location 2\n"
  );
}

void test_missing_type_in_shape_shifting_recipe() {
  Hide_errors = true;
  run(
      "def main [\n"
      "  a:d1:num <- merge 3\n"
      "  foo a\n"
      "]\n"
      "def foo a:d1:_elem -> b:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  copy e\n"  // no such variable
      "  return 34\n"
      "]\n"
      "container d1:_elem [\n"
      "  x:_elem\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "error: foo: unknown type for 'e' in 'copy e' (check the name for typos)\n"
      "error: specializing foo: missing type for 'e'\n"
  );
  // and it doesn't crash
}

void test_missing_type_in_shape_shifting_recipe_2() {
  Hide_errors = true;
  run(
      "def main [\n"
      "  a:d1:num <- merge 3\n"
      "  foo a\n"
      "]\n"
      "def foo a:d1:_elem -> b:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  get e, x:offset\n"  // unknown variable in a 'get', which does some extra checking
      "  return 34\n"
      "]\n"
      "container d1:_elem [\n"
      "  x:_elem\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "error: foo: unknown type for 'e' in 'get e, x:offset' (check the name for typos)\n"
      "error: specializing foo: missing type for 'e'\n"
  );
  // and it doesn't crash
}

void test_specialize_recursive_shape_shifting_recipe() {
  transform(
      "def main [\n"
      "  1:num <- copy 34\n"
      "  2:num <- foo 1:num\n"
      "]\n"
      "def foo x:_elem -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  {\n"
      "    break\n"
      "    y:num <- foo x\n"
      "  }\n"
      "  return y\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "transform: new specialization: foo_2\n"
  );
  // transform terminates
}

void test_specialize_most_similar_variant() {
  run(
      "def main [\n"
      "  1:&:num <- new number:type\n"
      "  10:num <- foo 1:&:num\n"
      "]\n"
      "def foo x:_elem -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 34\n"
      "]\n"
      "def foo x:&:_elem -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 35\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 35 in location 10\n"
  );
}

void test_specialize_most_similar_variant_2() {
  run(
      // version with headers padded with lots of unrelated concrete types
      "def main [\n"
      "  1:num <- copy 23\n"
      "  2:&:@:num <- copy null\n"
      "  4:num <- foo 2:&:@:num, 1:num\n"
      "]\n"
      // variant with concrete type
      "def foo dummy:&:@:num, x:num -> y:num, dummy:&:@:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 34\n"
      "]\n"
      // shape-shifting variant
      "def foo dummy:&:@:num, x:_elem -> y:num, dummy:&:@:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 35\n"
      "]\n"
  );
  // prefer the concrete variant
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 4\n"
  );
}

void test_specialize_most_similar_variant_3() {
  run(
      "def main [\n"
      "  1:text <- new [abc]\n"
      "  foo 1:text\n"
      "]\n"
      "def foo x:text [\n"
      "  10:num <- copy 34\n"
      "]\n"
      "def foo x:&:_elem [\n"
      "  10:num <- copy 35\n"
      "]\n"
  );
  // make sure the more precise version was used
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 10\n"
  );
}

void test_specialize_literal_as_number() {
  run(
      "def main [\n"
      "  1:num <- foo 23\n"
      "]\n"
      "def foo x:_elem -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 34\n"
      "]\n"
      "def foo x:char -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 35\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 1\n"
  );
}

void test_specialize_literal_as_number_2() {
  run(
      // version calling with literal
      "def main [\n"
      "  1:num <- foo 0\n"
      "]\n"
      // variant with concrete type
      "def foo x:num -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 34\n"
      "]\n"
      // shape-shifting variant
      "def foo x:&:_elem -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 35\n"
      "]\n"
  );
  // prefer the concrete variant, ignore concrete types in scoring the shape-shifting variant
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 1\n"
  );
}

void test_specialize_literal_as_address() {
  run(
      "def main [\n"
      "  1:num <- foo null\n"
      "]\n"
      // variant with concrete address type
      "def foo x:&:num -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 34\n"
      "]\n"
      // shape-shifting variant
      "def foo x:&:_elem -> y:num [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  return 35\n"
      "]\n"
  );
  // prefer the concrete variant, ignore concrete types in scoring the shape-shifting variant
  CHECK_TRACE_CONTENTS(
      "mem: storing 34 in location 1\n"
  );
}

void test_missing_type_during_specialization() {
  Hide_errors = true;
  run(
      // define a shape-shifting recipe
      "def foo a:_elem [\n"
      "]\n"
      // define a container with field 'z'
      "container foo2 [\n"
      "  z:num\n"
      "]\n"
      "def main [\n"
      "  local-scope\n"
      "  x:foo2 <- merge 34\n"
      "  y:num <- get x, z:offse  # typo in 'offset'\n"
         // define a variable with the same name 'z'
      "  z:num <- copy 34\n"
      "  foo z\n"
      "]\n"
  );
  // shouldn't crash
}

void test_missing_type_during_specialization2() {
  Hide_errors = true;
  run(
      // define a shape-shifting recipe
      "def foo a:_elem [\n"
      "]\n"
      // define a container with field 'z'
      "container foo2 [\n"
      "  z:num\n"
      "]\n"
      "def main [\n"
      "  local-scope\n"
      "  x:foo2 <- merge 34\n"
      "  y:num <- get x, z:offse  # typo in 'offset'\n"
         // define a variable with the same name 'z'
      "  z:&:num <- copy 34\n"
         // trigger specialization of the shape-shifting recipe
      "  foo *z\n"
      "]\n"
  );
  // shouldn't crash
}

void test_tangle_shape_shifting_recipe() {
  run(
      // shape-shifting recipe
      "def foo a:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  <label1>\n"
      "]\n"
      // tangle some code that refers to the type ingredient
      "after <label1> [\n"
      "  b:_elem <- copy a\n"
      "]\n"
      // trigger specialization
      "def main [\n"
      "  local-scope\n"
      "  foo 34\n"
      "]\n"
  );
  CHECK_TRACE_COUNT("error", 0);
}

void test_tangle_shape_shifting_recipe_with_type_abbreviation() {
  run(
      // shape-shifting recipe
      "def foo a:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  <label1>\n"
      "]\n"
      // tangle some code that refers to the type ingredient
      "after <label1> [\n"
      "  b:bool <- copy false\n"  // type abbreviation
      "]\n"
      // trigger specialization
      "def main [\n"
      "  local-scope\n"
      "  foo 34\n"
      "]\n"
  );
  CHECK_TRACE_COUNT("error", 0);
}

void test_shape_shifting_recipe_coexists_with_primitive() {
  run(
      // recipe overloading a primitive with a generic type
      "def add a:&:foo:_elem [\n"
      "  assert 0, [should not get here]\n"
      "]\n"
      "def main [\n"
         // call primitive add with literal 0
      "  add 0, 0\n"
      "]\n"
  );
  CHECK_TRACE_COUNT("error", 0);
}

void test_specialization_heuristic_test_1() {
  run(
      // modeled on the 'buffer' container in text.mu
      "container foo_buffer:_elem [\n"
      "  x:num\n"
      "]\n"
      "def main [\n"
      "  append 1:&:foo_buffer:char/raw, 2:text/raw\n"
      "]\n"
      "def append buf:&:foo_buffer:_elem, x:_elem -> buf:&:foo_buffer:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  stash 34\n"
      "]\n"
      "def append buf:&:foo_buffer:char, x:_elem -> buf:&:foo_buffer:char [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  stash 35\n"
      "]\n"
      "def append buf:&:foo_buffer:_elem, x:&:@:_elem -> buf:&:foo_buffer:_elem [\n"
      "  local-scope\n"
      "  load-ingredients\n"
      "  stash 36\n"
      "]\n"
  );
  CHECK_TRACE_CONTENTS(
      "app: 36\n"
  );
}