about summary refs log blame commit diff stats
path: root/053recipe_header.cc
blob: e299d3c0508f1d4b1b11021d28828ea3e682cb32 (plain) (tree)
a89c1bed ^
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
local utf8 = require 'utf8'

require 'app'
require 'test'

require 'keychord'
require 'file'
require 'button'
local Text = require 'text'
local Drawing = require 'drawing'
local geom = require 'geom'
require 'help'
require 'icons'

function App.initialize(arg)
  love.keyboard.setTextInput(true)  -- bring up keyboard on touch screen
  love.keyboard.setKeyRepeat(true)

-- globals

-- a line is either text or a drawing
-- a text is a table with:
--    mode = 'text'
--    string data
--    screen_line_starting_pos: optional array of grapheme indices if it wraps over more than one screen line
-- a drawing is a table with:
--    mode = 'drawing'
--    a (y) coord in pixels (updated while painting screen),
--    a (h)eight,
--    an array of points, and
--    an array of shapes
-- a shape is a table containing:
--    a mode
--    an array points for mode 'freehand' (raw x,y coords; freehand drawings don't pollute the points array of a drawing)
--    an array vertices for mode 'polygon', 'rectangle', 'square'
--    p1, p2 for mode 'line'
--    p1, p2, arrow-mode for mode 'arrow-line'
--    center, radius for mode 'circle'
--    center, radius, start_angle, end_angle for mode 'arc'
-- Unless otherwise specified, coord fields are normalized; a drawing is always 256 units wide
-- The field names are carefully chosen so that switching modes in midstream
-- remembers previously entered points where that makes sense.
--
-- Open question: how to maintain Sketchpad-style constraints? Answer for now:
-- we don't. Constraints operate only for the duration of a drawing operation.
-- We'll continue to persist them just to keep the option open to continue
-- solving for them. But for now, this is a program to create static drawings
-- once, and read them passively thereafter.
Lines = {{mode='text', data=''}}

-- Lines can be too long to fit on screen, in which case they _wrap_ into
-- multiple _screen lines_.
--
-- Therefore, any potential location for the cursor can be described in two ways:
-- * schema 1: As a combination of line index and position within a line (in utf8 codepoint units)
-- * schema 2: As a combination of line index, screen line index within the line, and a position within the screen line.
--
-- Most of the time we'll only persist positions in schema 1, translating to
-- schema 2 when that's convenient.
Cursor1 = {line=1, pos=1}  -- position of cursor
Screen_top1 = {line=1, pos=1}  -- position of start of screen line at top of screen
Screen_bottom1 = {line=1, pos=1}  -- position of start of screen line at bottom of screen

-- maximize window
love.window.setMode(0, 0)  -- maximize
Screen_width, Screen_height, Screen_flags = love.window.getMode()
-- shrink slightly to account for window decoration
Screen_width = Screen_width-100
Screen_height = Screen_height-100
love.window.setMode(Screen_width, Screen_height)

Cursor_x, Cursor_y = 0, 0  -- in pixels

Current_drawing_mode = 'line'
Previous_drawing_mode = nil

-- maximum width available to either text or drawings, in pixels
Line_width = math.floor(Screen_width/2/40)*40

Zoom = 1.5

Filename = love.filesystem.getUserDirectory()..'/lines.txt'

New_foo = true

  if #arg > 0 then
    Filename = arg[1]
  end
  Lines = load_from_disk(Filename)
  for i,line in ipairs(Lines) do
    if line.mode == 'text' then
      Cursor1.line = i
      break
    end
  end
  love.window.setTitle('Text with Lines - '..Filename)

end

function App.filedropped(file)
  Filename = file:getFilename()
  file:open('r')
  Lines = load_from_file(file)
  file:close()
  for i,line in ipairs(Lines) do
    if line.mode == 'text' then
      Cursor1.line = i
      break
    end
  end
  love.window.setTitle('Text with Lines - '..Filename)
end

function App.draw()
  Button_handlers = {}
  love.graphics.setColor(1, 1, 1)
  love.graphics.rectangle('fill', 0, 0, Screen_width-1, Screen_height-1)
  love.graphics.setColor(0, 0, 0)
  for line_index,line in ipairs(Lines) do
    line.y = nil
  end
  local y = 15
  if New_foo then print('== draw') end
  for line_index,line in ipairs(Lines) do
    if New_foo then print('draw:', line_index, y) end
    if y + math.floor(15*Zoom) > Screen_height then break end
    if line_index >= Screen_top1.line then
      Screen_bottom1.line = line_index
      if line.mode == 'text' and line.data == '' then
        line.y = y
        button('draw', {x=4,y=y+4, w=12,h=12, color={1,1,0},
          icon = icon.insert_drawing,
          onpress1 = function()
                       table.insert(Lines, line_index, {mode='drawing', y=y, h=256/2, points={}, shapes={}, pending={}})
                       if Cursor1.line >= line_index then
                         Cursor1.line = Cursor1.line+1
                       end
                     end})
          if line_index == Cursor1.line then
            Text.draw_cursor(25, y)
          end
        y = y + math.floor(15*Zoom)  -- text height
      elseif line.mode == 'drawing' then
        y = y+10 -- padding
        line.y = y
        Drawing.draw(line)
        y = y + Drawing.pixels(line.h) + 10 -- padding
      else
        if New_foo then print('text') end
        line.y = y
        y, Screen_bottom1.pos = Text.draw(line, Line_width, line_index)
        y = y + math.floor(15*Zoom)  -- text height
        if New_foo then print('aa', y) end
      end
    end
  end
  New_foo = false
--?   print('screen bottom: '..tostring(Screen_bottom1.pos)..' in '..tostring(Lines[Screen_bottom1.line].data))
--?   os.exit(1)
end

function App.update(dt)
  Drawing.update(dt)
end

function App.mousepressed(x,y, mouse_button)
  propagate_to_button_handlers(x,y, mouse_button)

  for line_index,line in ipairs(Lines) do
    if line.mode == 'text' then
      if Text.in_line(line, x,y) then
        Text.move_cursor(line_index, line, x, y)
      end
    elseif line.mode == 'drawing' then
      if Drawing.in_drawing(line, x, y) then
        Drawing.mouse_pressed(line, x,y, button)
      end
    end
  end
end

function App.mousereleased(x,y, button)
  Drawing.mouse_released(x,y, button)
end

function App.textinput(t)
  if Current_drawing_mode == 'name' then
    local drawing = Lines.current
    local p = drawing.points[drawing.pending.target_point]
    p.name = p.name..t
  else
    Text.textinput(t)
  end
  save_to_disk(Lines, Filename)
end

function App.keychord_pressed(chord)
  New_foo = true
  if love.mouse.isDown('1') or chord:sub(1,2) == 'C-' then
    Drawing.keychord_pressed(chord)
  elseif chord == 'escape' and love.mouse.isDown('1') then
    local drawing = Drawing.current_drawing()
    if drawing then
      drawing.pending = {}
    end
  elseif chord == 'escape' and not love.mouse.isDown('1') then
    for _,line in ipairs(Lines) do
      if line.mode == 'drawing' then
        line.show_help = false
      end
    end
  elseif Current_drawing_mode == 'name' then
    if chord == 'return' then
      Current_drawing_mode = Previous_drawing_mode
      Previous_drawing_mode = nil
    else
      local drawing = Lines.current
      local p = drawing.points[drawing.pending.target_point]
      if chord == 'escape' then
        p.name = nil
      elseif chord == 'backspace' then
        local len = utf8.len(p.name)
        local byte_offset = utf8.offset(p.name, len-1)
        p.name = string.sub(p.name, 1, byte_offset)
      end
    end
    save_to_disk(Lines, Filename)
  elseif chord == 'pagedown' then
    Screen_top1.line = Screen_bottom1.line
    Screen_top1.pos = Screen_bottom1.pos
    Cursor1.line = Screen_top1.line
    Cursor1.pos = Screen_top1.pos
    Text.move_cursor_down_to_next_text_line_while_scrolling_again_if_necessary()
  elseif chord == 'pageup' then
    -- duplicate some logic from love.draw
    local y = Screen_height
    while y >= 0 do
      if Screen_top1.line == 1 then break end
      y = y - math.floor(15*Zoom)
      if Lines[Screen_top1.line].mode == 'drawing' then
        y = y - Drawing.pixels(Lines[Screen_top1.line].h)
      end
      Screen_top1.line = Screen_top1.line - 1
    end
    if Cursor1.line ~= Screen_top1.line then
      Cursor1.pos = 1
    end
    Cursor1.line = Screen_top1.line
    Text.move_cursor_down_to_next_text_line_while_scrolling_again_if_necessary()
  else
    Text.keychord_pressed(chord)
  end
end

function App.keyreleased(key, scancode)
end
thor Kartik K. Agaram <vc@akkartik.com> 2016-01-12 12:53:04 -0800 committer Kartik K. Agaram <vc@akkartik.com> 2016-01-12 12:53:04 -0800 2557 - type-check most ingredients ahead of time' href='/akkartik/mu/commit/056recipe_header.cc?h=main&id=7ac8feeff10abfd76f712f8f32406dd30ba1c73e'>7ac8feef ^
6c96a437 ^
bdb6161b ^
7ac8feef ^
70f70118 ^




2b4eb0cc ^



70f70118 ^
7ac8feef ^



















7ac8feef ^
802283e4 ^
2d29369f ^
7ac8feef ^




61880904 ^







91f220ae ^
61880904 ^


















ae9db5a4 ^








7ac8feef ^



1ead3562 ^
7a84094a ^
7ac8feef ^
7a84094a ^
7ac8feef ^

1ead3562 ^
7ac8feef ^
7a84094a ^
7ac8feef ^


1ead3562 ^
b436291f ^
7ac8feef ^
7a84094a ^
7ac8feef ^

1ead3562 ^
7ac8feef ^
b436291f ^
7ac8feef ^




7ac8feef ^
cdf0f349 ^
6c96a437 ^
7ac8feef ^
636837e7 ^
7ac8feef ^

6c96a437 ^
3bfd75fc ^
f8b0b04d ^
2b250717 ^
f8b0b04d ^

7ac8feef ^
6c96a437 ^
7ac8feef ^
3bfd75fc ^
f8b0b04d ^
2b250717 ^
f8b0b04d ^

7ac8feef ^



bcd33d6d ^

70f70118 ^

e6692482 ^
7a84094a ^
70f70118 ^

760f683f ^
1ead3562 ^
70f70118 ^
1ead3562 ^
70f70118 ^
04209f72 ^
f116818c ^
70f70118 ^

f116818c ^
d11bf882 ^
4637d58f ^
f116818c ^
6c96a437 ^
d11bf882 ^
1ead3562 ^
4637d58f ^
2b250717 ^
4637d58f ^

6c96a437 ^
d11bf882 ^
2b250717 ^
70f70118 ^



4637d58f ^

7a84094a ^
4637d58f ^

760f683f ^
1ead3562 ^
4637d58f ^
1ead3562 ^
4637d58f ^
459cdb3d ^
c8f2ff13 ^



dd660682 ^
c8f2ff13 ^



c1585c88 ^

b5f2a629 ^
c1585c88 ^

1ead3562 ^
c1585c88 ^
b5f2a629 ^

















c1585c88 ^



f7631430 ^
808e171d ^
c1585c88 ^

808e171d ^
d11bf882 ^
60c225ba ^
f116818c ^
6c96a437 ^
b5f2a629 ^

d11bf882 ^
9dcbec39 ^
d11bf882 ^
c1585c88 ^


9cfb86fa ^



1ead3562 ^
7a84094a ^
9cfb86fa ^
7a84094a ^
9cfb86fa ^


1ead3562 ^
9cfb86fa ^


04209f72 ^
b2e4056d ^
9cfb86fa ^


d11bf882 ^


b766f5f8 ^
6c96a437 ^
09b8717b ^
d11bf882 ^
c4e143d6 ^
9cfb86fa ^
6c96a437 ^
09b8717b ^
d11bf882 ^
c4e143d6 ^
9cfb86fa ^
6c96a437 ^
d11bf882 ^
9f95c745 ^
6c96a437 ^
9cfb86fa ^
83d8299d ^
b7cd91a6 ^
09b8717b ^

c4e143d6 ^
9cfb86fa ^
6c96a437 ^
15c44292 ^
9cfb86fa ^
83d8299d ^
b7cd91a6 ^
09b8717b ^

c4e143d6 ^
9cfb86fa ^



70f70118 ^


5109e78f ^
1ead3562 ^
7a84094a ^
70f70118 ^
7a84094a ^
70f70118 ^

9cfb86fa ^
1ead3562 ^
70f70118 ^


808e171d ^
f116818c ^
f7e75825 ^

f116818c ^
d11bf882 ^
f116818c ^
09125ea2 ^
6c96a437 ^
d11bf882 ^
1ead3562 ^
d11bf882 ^
c1585c88 ^
f116818c ^
5e320aa0 ^



c1585c88 ^
5e320aa0 ^



c1585c88 ^

d11bf882 ^
1ead3562 ^
c1585c88 ^
6c96a437 ^
c1585c88 ^

d11bf882 ^
c1585c88 ^
d11bf882 ^
c1585c88 ^
d11bf882 ^
c1585c88 ^
f7e75825 ^
70f70118 ^

813b93b8 ^
f116818c ^
1ead3562 ^
7a84094a ^
8de2764d ^
7a84094a ^
8de2764d ^



1ead3562 ^
8de2764d ^



5109e78f ^
1ead3562 ^
7a84094a ^
813b93b8 ^
7a84094a ^
813b93b8 ^

9cfb86fa ^
813b93b8 ^
f116818c ^
813b93b8 ^

5109e78f ^
1ead3562 ^
7a84094a ^
3a49e7e9 ^
7a84094a ^
3a49e7e9 ^


1ead3562 ^
3a49e7e9 ^
acc4792d ^
f116818c ^
3a49e7e9 ^
c1585c88 ^
5e320aa0 ^





f116818c ^
e765f9e7 ^
7a84094a ^
e765f9e7 ^
7a84094a ^
e765f9e7 ^


dd660682 ^
e765f9e7 ^


c1585c88 ^

1ead3562 ^
7a84094a ^


c1585c88 ^
7a84094a ^
c1585c88 ^


7a84094a ^
4c2229fb ^
3b107f18 ^


























09125ea2 ^
3b107f18 ^














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



                                                                              
          
                        
 
                                

                  
                   
          





                                         
                

                            

                                  
 
                                  
                       
                                                            




                                                      
                           
                                                                 
                             




                                                                        

                                                                                      

                                             
                                                                                                  
                                        
   
                                                                 
                             




                                                                        
                                          
                                                                                            
                                        
   
                                   

 
                                      
          
                        
 
                                 

                  
                   
          



                                        
          

     
          
                       
 
         
                       


                             

                                      
                        


                                               

                                          
        
 
                                             
 

                                            
        





                                           
                                             
 

                                            
                   





                                           
                                             
 

                                       
                                               

                                                           
                                            

                                                        


                                                                                   
          
                  


                                
                                   

                           
                                                  

                                                           
                                                               








                                               
                                                                         

 


                                                

             
               
                           
 
                                                






                                                 
                                                         
                                                           
                                                      

                                                        
                                                                                    

                                                        
                                                                    
               
                                                                                  
                                                        
                        
                                                       




                                                      



                                                                                                         
 



















                                                                                                  
                       
                                                                    
                                                                         




                                







                                                                    
                                                                                                      


















                                                                                     








                                                                                     



                                        
          
                 
 
                          

                  
           
 
                                                                  


                                          
          
                   
 
                        

                  
          
 
                                                                 




                                                               
                                        
                                                                                            
                                                  
                                                 
                                               

                                                       
                                                                                            
                                                
                                                                               
                                                                                                                                      

                                                                                                                                             
     
                                                                                      
                                                  
                                             
                                                                         
                                                                                                                                   

                                                                                                                                       



     

                                                              

                                      
                     
                                

                  
                          
          
 
                                                       
 
                      
                                                                             

       
                                                                       
                                               
                                        
                                                                                                                    
                                                         
                                                        
                                                                
                                                                 
                                                                                                                                           

               
                                                              
                                                                             
                                                                                                                               



     

                                        
                       

                  
                          
          
 
                                                                     
 
                                                                           



                     
                      



                                                            

                                                    
                               

                  
          
 

















                                                      



                                  
                                                 
                                                             

       
                                                       
                                         
                                         
                                                                                                                    
                                                               

                                                                                                                                 
                                                                                           
                                                                                                                                          
                                                                                 


   



                                                       
          
                        
 
                                


                                
          


                             
                                          
                                                             


                                                       


                                                                                                 
                                            
                                                               
                                                                                    
                                                                                                 
                                                                                                                                                               
   
                                                            
                                                                                 
                                                                                           
                                                                                                                                                         
   
                                                         
                                                  
                                                                            
                                                        
                                                
                                                                             
                 

                                                                                                        
                                                                                                                                               
     
                                                     
                                                                                           
                                             
                                                                          
                 

                                                                                                     
                                                                                                                                         



     


                                                                              
                                  
          
                        
 
                                

                  
               
        


                             
                                                        
                                                               

       
                                                         
                                         
                                                                                                                      
                                        
                                                         
                                                  
                                                      
                                               
   
                        



                                                                                               
   



                                           

 
                                                                          
                                                        
                                                            
                                                            

                                                           
                                                               
                                                             
                                                                                                                                                         
                                       
                                                                                                   
                                                                                                                                               
     

   
 
                                          
          
                                   
 
                                       



                    
             



                              
                                                 
          
                        
 
                                

                  
               
 
                                             

                             
                                                
          
                        
 
                                


                                
          
 
                                       
                                     
                             
 





                                                                                             
                                                           
          
                        
 
                                


                                
                     


                             

                                                        
          


                            
 
                                


                  
                                                                                      
 


























                                                                               
                                                                                                    














                                                                                                    
//: Advanced notation for the common/easy case where a recipe takes some fixed
//: number of ingredients and yields some fixed number of products.

:(scenario recipe_with_header)
def main [
  1:num/raw <- add2 3, 5
]
def add2 x:num, y:num -> z:num [
  local-scope
  load-ingredients
  z:num <- add x, y
  return z
]
+mem: storing 8 in location 1

//: When loading recipes save any header.

:(before "End recipe Fields")
bool has_header;
vector<reagent> ingredients;
vector<reagent> products;
:(before "End recipe Constructor")
has_header = false;

:(before "End Recipe Refinements")
if (in.peek() != '[') {
  trace("parse") << "recipe has a header; parsing" << end();
  load_recipe_header(in, result);
}

:(code)
void load_recipe_header(istream& in, recipe& result) {
  result.has_header = true;
  while (has_data(in) && in.peek() != '[' && in.peek() != '\n') {
    string s = next_word(in);
    if (s.empty()) {
      assert(!has_data(in));
      raise << "incomplete recipe header at end of file (0)\n" << end();
      return;
    }
    if (s == "<-")
      raise << "recipe " << result.name << " should say '->' and not '<-'\n" << end();
    if (s == "->") break;
    result.ingredients.push_back(reagent(s));
    trace("parse") << "header ingredient: " << result.ingredients.back().original_string << end();
    skip_whitespace_but_not_newline(in);
  }
  while (has_data(in) && in.peek() != '[' && in.peek() != '\n') {
    string s = next_word(in);
    if (s.empty()) {
      assert(!has_data(in));
      raise << "incomplete recipe header at end of file (1)\n" << end();
      return;
    }
    result.products.push_back(reagent(s));
    trace("parse") << "header product: " << result.products.back().original_string << end();
    skip_whitespace_but_not_newline(in);
  }
  // End Load Recipe Header(result)
}

:(scenario recipe_handles_stray_comma)
def main [
  1:num/raw <- add2 3, 5
]
def add2 x:num, y:num -> z:num, [
  local-scope
  load-ingredients
  z:num <- add x, y
  return z
]
+mem: storing 8 in location 1

:(scenario recipe_handles_stray_comma_2)
def main [
  foo
]
def foo, [
  1:num/raw <- add 2, 2
]
def bar [
  1:num/raw <- add 2, 3
]
+mem: storing 4 in location 1

:(scenario recipe_handles_wrong_arrow)
% Hide_errors = true;
def foo a:num <- b:num [
]
+error: recipe foo should say '->' and not '<-'

:(scenario recipe_handles_missing_bracket)
% Hide_errors = true;
def main
]
+error: main: recipe body must begin with '['

:(scenario recipe_handles_missing_bracket_2)
% Hide_errors = true;
def main
  local-scope
  {
  }
]
# doesn't overflow line when reading header
-parse: header ingredient: local-scope
+error: main: recipe body must begin with '['

:(scenario recipe_handles_missing_bracket_3)
% Hide_errors = true;
def main  # comment
  local-scope
  {
  }
]
# doesn't overflow line when reading header
-parse: header ingredient: local-scope
+error: main: recipe body must begin with '['

:(after "Begin debug_string(recipe x)")
out << "ingredients:\n";
for (int i = 0;  i < SIZE(x.ingredients);  ++i)
  out << "  " << debug_string(x.ingredients.at(i)) << '\n';
out << "products:\n";
for (int i = 0;  i < SIZE(x.products);  ++i)
  out << "  " << debug_string(x.products.at(i)) << '\n';

//: If a recipe never mentions any ingredients or products, assume it has a header.

:(scenario recipe_without_ingredients_or_products_has_header)
def test [
  1:num <- copy 34
]
+parse: recipe test has a header

:(before "End Recipe Body(result)")
if (!result.has_header) {
  result.has_header = true;
  for (int i = 0;  i < SIZE(result.steps);  ++i) {
    const instruction& inst = result.steps.at(i);
    if ((inst.name == "reply" && !inst.ingredients.empty())
        || (inst.name == "return" && !inst.ingredients.empty())
        || inst.name == "next-ingredient"
        || inst.name == "ingredient"
        || inst.name == "rewind-ingredients") {
      result.has_header = false;
      break;
    }
  }
}
if (result.has_header) {
  trace("parse") << "recipe " << result.name << " has a header" << end();
}

//: Support type abbreviations in headers.

:(scenario type_abbreviations_in_recipe_headers)
def main [
  local-scope
  a:text <- foo
  1:char/raw <- index *a, 0
]
def foo -> a:text [  # 'text' is an abbreviation
  local-scope
  load-ingredients
  a <- new [abc]
]
+mem: storing 97 in location 1

:(before "End Expand Type Abbreviations(caller)")
for (long int i = 0;  i < SIZE(caller.ingredients);  ++i)
  expand_type_abbreviations(caller.ingredients.at(i).type);
for (long int i = 0;  i < SIZE(caller.products);  ++i)
  expand_type_abbreviations(caller.products.at(i).type);

//: Rewrite 'load-ingredients' to instructions to create all reagents in the header.

:(before "End Rewrite Instruction(curr, recipe result)")
if (curr.name == "load-ingredients" || curr.name == "load-inputs") {
  curr.clear();
  recipe_ordinal op = get(Recipe_ordinal, "next-ingredient-without-typechecking");
  for (int i = 0;  i < SIZE(result.ingredients);  ++i) {
    curr.operation = op;
    curr.name = "next-ingredient-without-typechecking";
    curr.products.push_back(result.ingredients.at(i));
    result.steps.push_back(curr);
    curr.clear();
  }
}
if (curr.name == "next-ingredient-without-typechecking") {
  raise << maybe(result.name) << "never call 'next-ingredient-without-typechecking' directly\n" << end();
  curr.clear();
}

//: internal version of next-ingredient; don't call this directly
:(before "End Primitive Recipe Declarations")
NEXT_INGREDIENT_WITHOUT_TYPECHECKING,
:(before "End Primitive Recipe Numbers")
put(Recipe_ordinal, "next-ingredient-without-typechecking", NEXT_INGREDIENT_WITHOUT_TYPECHECKING);
:(before "End Primitive Recipe Checks")
case NEXT_INGREDIENT_WITHOUT_TYPECHECKING: {
  break;
}
:(before "End Primitive Recipe Implementations")
case NEXT_INGREDIENT_WITHOUT_TYPECHECKING: {
  assert(!Current_routine->calls.empty());
  if (current_call().next_ingredient_to_process < SIZE(current_call().ingredient_atoms)) {
    products.push_back(
        current_call().ingredient_atoms.at(current_call().next_ingredient_to_process));
    assert(SIZE(products) == 1);  products.resize(2);  // push a new vector
    products.at(1).push_back(1);
    ++current_call().next_ingredient_to_process;
  }
  else {
    products.resize(2);
    // pad the first product with sufficient zeros to match its type
    products.at(0).resize(size_of(current_instruction().products.at(0)));
    products.at(1).push_back(0);
  }
  break;
}

//: more useful error messages if someone forgets 'load-ingredients'

:(scenario load_ingredients_missing_error)
% Hide_errors = true;
def foo a:num [
  local-scope
  b:num <- add a:num, 1
]
+error: foo: tried to read ingredient 'a' in 'b:num <- add a:num, 1' but it hasn't been written to yet
+error:   did you forget 'load-ingredients'?

:(after "use-before-set Error")
if (is_present_in_ingredients(caller, ingredient.name))
  raise << "  did you forget 'load-ingredients'?\n" << end();

:(scenario load_ingredients_missing_error_2)
% Hide_errors = true;
def foo a:num [
  local-scope
  b:num <- add a, 1
]
+error: foo: missing type for 'a' in 'b:num <- add a, 1'
+error:   did you forget 'load-ingredients'?

:(after "missing-type Error 1")
if (is_present_in_ingredients(get(Recipe, get(Recipe_ordinal, recipe_name)), x.name))
  raise << "  did you forget 'load-ingredients'?\n" << end();

:(code)
bool is_present_in_ingredients(const recipe& callee, const string& ingredient_name) {
  for (int i = 0;  i < SIZE(callee.ingredients);  ++i) {
    if (callee.ingredients.at(i).name == ingredient_name)
      return true;
  }
  return false;
}

//:: Check all calls against headers.

:(scenario show_clear_error_on_bad_call)
% Hide_errors = true;
def main [
  1:num <- foo 34
]
def foo x:point -> y:num [
  local-scope
  load-ingredients
  return 35
]
+error: main: ingredient 0 has the wrong type at '1:num <- foo 34'

:(scenario show_clear_error_on_bad_call_2)
% Hide_errors = true;
def main [
  1:point <- foo 34
]
def foo x:num -> y:num [
  local-scope
  load-ingredients
  return x
]
+error: main: product 0 has the wrong type at '1:point <- foo 34'

:(after "Transform.push_back(check_instruction)")
Transform.push_back(check_calls_against_header);  // idempotent
:(code)
void check_calls_against_header(const recipe_ordinal r) {
  const recipe& caller = get(Recipe, r);
  trace(9991, "transform") << "--- type-check calls inside recipe " << caller.name << end();
  for (int i = 0;  i < SIZE(caller.steps);  ++i) {
    const instruction& inst = caller.steps.at(i);
    if (is_primitive(inst.operation)) continue;
    const recipe& callee = get(Recipe, inst.operation);
    if (!callee.has_header) continue;
    for (long int i = 0;  i < min(SIZE(inst.ingredients), SIZE(callee.ingredients));  ++i) {
      // ingredients coerced from call to callee
      if (!types_coercible(callee.ingredients.at(i), inst.ingredients.at(i))) {
        raise << maybe(caller.name) << "ingredient " << i << " has the wrong type at '" << to_original_string(inst) << "'\n" << end();
        raise << "  ['" << to_string(callee.ingredients.at(i).type) << "' vs '" << to_string(inst.ingredients.at(i).type) << "']\n" << end();
      }
    }
    for (long int i = 0;  i < min(SIZE(inst.products), SIZE(callee.products));  ++i) {
      if (is_dummy(inst.products.at(i))) continue;
      // products coerced from callee to call
      if (!types_coercible(inst.products.at(i), callee.products.at(i))) {
        raise << maybe(caller.name) << "product " << i << " has the wrong type at '" << to_original_string(inst) << "'\n" << end();
        raise << "  ['" << to_string(inst.products.at(i).type) << "' vs '" << to_string(callee.products.at(i).type) << "']\n" << end();
      }
    }
  }
}

//:: Check types going in and out of all recipes with headers.

:(scenarios transform)
:(scenario recipe_headers_are_checked)
% Hide_errors = true;
def add2 x:num, y:num -> z:num [
  local-scope
  load-ingredients
  z:&:num <- copy 0/unsafe
  return z
]
+error: add2: replied with the wrong type at 'return z'

:(before "End Checks")
Transform.push_back(check_return_instructions_against_header);  // idempotent

:(code)
void check_return_instructions_against_header(const recipe_ordinal r) {
  const recipe& caller_recipe = get(Recipe, r);
  if (!caller_recipe.has_header) return;
  trace(9991, "transform") << "--- checking return instructions against header for " << caller_recipe.name << end();
  for (int i = 0;  i < SIZE(caller_recipe.steps);  ++i) {
    const instruction& inst = caller_recipe.steps.at(i);
    if (inst.name != "reply" && inst.name != "return") continue;
    if (SIZE(caller_recipe.products) != SIZE(inst.ingredients)) {
      raise << maybe(caller_recipe.name) << "replied with the wrong number of products at '" << to_original_string(inst) << "'\n" << end();
      continue;
    }
    for (int i = 0;  i < SIZE(caller_recipe.products);  ++i) {
      if (!types_match(caller_recipe.products.at(i), inst.ingredients.at(i)))
        raise << maybe(caller_recipe.name) << "replied with the wrong type at '" << to_original_string(inst) << "'\n" << end();
    }
  }
}

:(scenario recipe_headers_are_checked_2)
% Hide_errors = true;
def add2 x:num, y:num [
  local-scope
  load-ingredients
  z:&:num <- copy 0/unsafe
  return z
]
+error: add2: replied with the wrong number of products at 'return z'

:(scenario recipe_headers_are_checked_against_pre_transformed_instructions)
% Hide_errors = true;
def foo -> x:num [
  local-scope
  x:num <- copy 0
  z:bool <- copy false
  return-if z, z
]
+error: foo: replied with the wrong type at 'return-if z, z'

:(scenario recipe_headers_check_for_duplicate_names)
% Hide_errors = true;
def foo x:num, x:num -> z:num [
  local-scope
  load-ingredients
  return z
]
+error: foo: 'x' can't repeat in the ingredients

:(scenario recipe_headers_check_for_duplicate_names_2)
% Hide_errors = true;
def foo x:num, x:num [  # no result
  local-scope
  load-ingredients
]
+error: foo: 'x' can't repeat in the ingredients

:(scenario recipe_headers_check_for_missing_types)
% Hide_errors = true;
def main [
  foo 0
]
def foo a [  # no type for 'a'
]
+error: foo: ingredient 'a' has no type

:(before "End recipe Fields")
map<string, int> ingredient_index;

:(after "Begin Instruction Modifying Transforms")
Transform.push_back(check_header_ingredients);  // idempotent

:(code)
void check_header_ingredients(const recipe_ordinal r) {
  recipe& caller_recipe = get(Recipe, r);
  caller_recipe.ingredient_index.clear();
  trace(9991, "transform") << "--- checking return instructions against header for " << caller_recipe.name << end();
  for (int i = 0;  i < SIZE(caller_recipe.ingredients);  ++i) {
    if (caller_recipe.ingredients.at(i).type == NULL)
      raise << maybe(caller_recipe.name) << "ingredient '" << caller_recipe.ingredients.at(i).name << "' has no type\n" << end();
    if (contains_key(caller_recipe.ingredient_index, caller_recipe.ingredients.at(i).name))
      raise << maybe(caller_recipe.name) << "'" << caller_recipe.ingredients.at(i).name << "' can't repeat in the ingredients\n" << end();
    put(caller_recipe.ingredient_index, caller_recipe.ingredients.at(i).name, i);
  }
}

//: Deduce types from the header if possible.

:(scenarios run)
:(scenario deduce_instruction_types_from_recipe_header)
def main [
  1:num/raw <- add2 3, 5
]
def add2 x:num, y:num -> z:num [
  local-scope
  load-ingredients
  z <- add x, y  # no type for z
  return z
]
+mem: storing 8 in location 1

:(after "Begin Type Modifying Transforms")
Transform.push_back(deduce_types_from_header);  // idempotent

:(code)
void deduce_types_from_header(const recipe_ordinal r) {
  recipe& caller_recipe = get(Recipe, r);
  if (caller_recipe.products.empty()) return;
  trace(9991, "transform") << "--- deduce types from header for " << caller_recipe.name << end();
  map<string, const type_tree*> header_type;
  for (int i = 0;  i < SIZE(caller_recipe.ingredients);  ++i) {
    if (!caller_recipe.ingredients.at(i).type) continue;  // error handled elsewhere
    put(header_type, caller_recipe.ingredients.at(i).name, caller_recipe.ingredients.at(i).type);
    trace(9993, "transform") << "type of " << caller_recipe.ingredients.at(i).name << " is " << names_to_string(caller_recipe.ingredients.at(i).type) << end();
  }
  for (int i = 0;  i < SIZE(caller_recipe.products);  ++i) {
    if (!caller_recipe.products.at(i).type) continue;  // error handled elsewhere
    put(header_type, caller_recipe.products.at(i).name, caller_recipe.products.at(i).type);
    trace(9993, "transform") << "type of " << caller_recipe.products.at(i).name << " is " << names_to_string(caller_recipe.products.at(i).type) << end();
  }
  for (int i = 0;  i < SIZE(caller_recipe.steps);  ++i) {
    instruction& inst = caller_recipe.steps.at(i);
    trace(9992, "transform") << "instruction: " << to_string(inst) << end();
    for (int i = 0;  i < SIZE(inst.ingredients);  ++i) {
      if (inst.ingredients.at(i).type) continue;
      if (header_type.find(inst.ingredients.at(i).name) == header_type.end())
        continue;
      if (!contains_key(header_type, inst.ingredients.at(i).name)) continue;  // error handled elsewhere
      inst.ingredients.at(i).type = new type_tree(*get(header_type, inst.ingredients.at(i).name));
      trace(9993, "transform") << "type of " << inst.ingredients.at(i).name << " is " << names_to_string(inst.ingredients.at(i).type) << end();
    }
    for (int i = 0;  i < SIZE(inst.products);  ++i) {
      trace(9993, "transform") << "  product: " << to_string(inst.products.at(i)) << end();
      if (inst.products.at(i).type) continue;
      if (header_type.find(inst.products.at(i).name) == header_type.end())
        continue;
      if (!contains_key(header_type, inst.products.at(i).name)) continue;  // error handled elsewhere
      inst.products.at(i).type = new type_tree(*get(header_type, inst.products.at(i).name));
      trace(9993, "transform") << "type of " << inst.products.at(i).name << " is " << names_to_string(inst.products.at(i).type) << end();
    }
  }
}

//: One final convenience: no need to say what to return if the information is
//: in the header.

:(scenario return_based_on_header)
def main [
  1:num/raw <- add2 3, 5
]
def add2 x:num, y:num -> z:num [
  local-scope
  load-ingredients
  z <- add x, y
  return
]
+mem: storing 8 in location 1

:(after "Transform.push_back(check_header_ingredients)")
Transform.push_back(fill_in_return_ingredients);  // idempotent

:(code)
void fill_in_return_ingredients(const recipe_ordinal r) {
  recipe& caller_recipe = get(Recipe, r);
  trace(9991, "transform") << "--- fill in return ingredients from header for recipe " << caller_recipe.name << end();
  if (!caller_recipe.has_header) return;
  for (int i = 0;  i < SIZE(caller_recipe.steps);  ++i) {
    instruction& inst = caller_recipe.steps.at(i);
    if (inst.name == "reply" || inst.name == "return")
      add_header_products(inst, caller_recipe);
  }
  // fall through return
  if (!caller_recipe.steps.empty()) {
    const instruction& final_instruction = caller_recipe.steps.at(SIZE(caller_recipe.steps)-1);
    if (final_instruction.name == "reply" || final_instruction.name == "return")
      return;
  }
  instruction inst;
  inst.name = "return";
  add_header_products(inst, caller_recipe);
  caller_recipe.steps.push_back(inst);
}

void add_header_products(instruction& inst, const recipe& caller_recipe) {
  assert(inst.name == "reply" || inst.name == "return");
  // collect any products with the same names as ingredients
  for (int i = 0;  i < SIZE(caller_recipe.products);  ++i) {
    // if the ingredient is missing, add it from the header
    if (SIZE(inst.ingredients) == i)
      inst.ingredients.push_back(caller_recipe.products.at(i));
    // if it's missing /same_as_ingredient, try to fill it in
    if (contains_key(caller_recipe.ingredient_index, caller_recipe.products.at(i).name) && !has_property(inst.ingredients.at(i), "same_as_ingredient")) {
      ostringstream same_as_ingredient;
      same_as_ingredient << get(caller_recipe.ingredient_index, caller_recipe.products.at(i).name);
      inst.ingredients.at(i).properties.push_back(pair<string, string_tree*>("same-as-ingredient", new string_tree(same_as_ingredient.str())));
    }
  }
}

:(scenario explicit_return_ignores_header)
def main [
  1:num/raw, 2:num/raw <- add2 3, 5
]
def add2 a:num, b:num -> y:num, z:num [
  local-scope
  load-ingredients
  y <- add a, b
  z <- subtract a, b
  return a, z
]
+mem: storing 3 in location 1
+mem: storing -2 in location 2

:(scenario return_on_fallthrough_based_on_header)
def main [
  1:num/raw <- add2 3, 5
]
def add2 x:num, y:num -> z:num [
  local-scope
  load-ingredients
  z <- add x, y
]
+transform: instruction: return {z: "number"}
+mem: storing 8 in location 1

:(scenario return_on_fallthrough_already_exists)
def main [
  1:num/raw <- add2 3, 5
]
def add2 x:num, y:num -> z:num [
  local-scope
  load-ingredients
  z <- add x, y  # no type for z
  return z
]
+transform: instruction: return {z: ()}
-transform: instruction: return z:num
+mem: storing 8 in location 1

:(scenario return_causes_error_in_empty_recipe)
% Hide_errors = true;
def foo -> x:num [
]
+error: foo: tried to read ingredient 'x' in 'return x:num' but it hasn't been written to yet

:(scenario return_after_conditional_return_based_on_header)
def main [
  1:num/raw <- add2 3, 5
]
def add2 x:num, y:num -> z:num [
  local-scope
  load-ingredients
  z <- add x, y  # no type for z
  return-if false, 34
]
+mem: storing 8 in location 1

:(scenario recipe_headers_perform_same_ingredient_check)
% Hide_errors = true;
def main [
  1:num <- copy 34
  2:num <- copy 34
  3:num <- add2 1:num, 2:num
]
def add2 x:num, y:num -> x:num [
  local-scope
  load-ingredients
]
+error: main: '3:num <- add2 1:num, 2:num' should write to '1:num' rather than '3:num'

//: One special-case is recipe 'main'. Make sure it's only ever taking in text
//: ingredients, and returning a single number.

:(scenario recipe_header_ingredients_constrained_for_main)
% Hide_errors = true;
def main x:num [
]
+error: ingredients of recipe 'main' must all be text (address:array:character)

:(scenario recipe_header_products_constrained_for_main)
% Hide_errors = true;
def main -> x:text [
]
+error: recipe 'main' must return at most a single product, a number

:(scenario recipe_header_products_constrained_for_main_2)
% Hide_errors = true;
def main -> x:num, y:num [
]
+error: recipe 'main' must return at most a single product, a number

:(after "Transform.push_back(expand_type_abbreviations)")
Transform.push_back(check_recipe_header_constraints);
:(code)
void check_recipe_header_constraints(const recipe_ordinal r) {
  const recipe& caller = get(Recipe, r);
  if (caller.name != "main") return;
  trace(9992, "transform") << "check recipe header constraints for recipe " << caller.name << end();
  if (!caller.has_header) return;
  reagent/*local*/ expected_ingredient("x:address:array:character");
  for (int i = 0; i < SIZE(caller.ingredients); ++i) {
    if (!types_strictly_match(expected_ingredient, caller.ingredients.at(i))) {
      raise << "ingredients of recipe 'main' must all be text (address:array:character)\n" << end();
      break;
    }
  }
  int nprod = SIZE(caller.products);
  reagent/*local*/ expected_product("x:number");
  if (nprod > 1
      || (nprod == 1 && !types_strictly_match(expected_product, caller.products.at(0)))) {
    raise << "recipe 'main' must return at most a single product, a number\n" << end();
  }
}