Source

Forth interpreter / machine / greensyn.rkt

  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
 #lang racket

(require "programs.rkt" "state.rkt" "stack.rkt")

;(define TYPE `BV4)
;(define LOG_SIZE 2)

(define SIZE 4) ; number of bits per word

(define TYPE (string->symbol (format "BV~e" SIZE)))
(define MAX (sub1 (arithmetic-shift 1 SIZE)))
(define EXP_MASK (string->symbol (format "bv~e" MAX)))

(define STACK_SIZE (* 8 SIZE))
(define STACK_TYPE (string->symbol (format "BV~e" STACK_SIZE)))
  
(define MEM_ENTRIES 3)
(define MEM_SIZE (* MEM_ENTRIES SIZE))
(define MEM_TYPE (string->symbol (format "BV~e" MEM_SIZE)))

(define COMM_ENTRIES 4)
(define COMM_SIZE (* COMM_ENTRIES SIZE))
(define COMM_TYPE (string->symbol (format "BV~e" COMM_SIZE)))
(define COMM_BIT 3)

(define TIME_SIZE 16)

(define U-ID 0)
(define D-ID 1)
(define L-ID 2)
(define R-ID 3)
(define U-SEND `sendp0)
(define D-SEND `sendp1)
(define L-SEND `sendp2)
(define R-SEND `sendp3)
(define U-RECV `recvp0)
(define D-RECV `recvp1)
(define L-RECV `recvp2)
(define R-RECV `recvp3)

(define CHOICES (vector-length choice-id))
(define N_OF_SLOW (vector-length memory-op))
(define HOLE_BIT (inexact->exact (ceiling (+ (/ (log CHOICES) (log 2))))))

;;; counterexample
(struct inout (input output comm))

(define inout-list '())

;; TODO: Use lists instead of vectors, or something.
(define spec (make-vector MEM-SIZE))
(define spec-lit (make-vector MEM-SIZE))
(define spec-count 0) ; number of instructions in spec
(define cand (make-vector MEM-SIZE))
(define cand-lit (make-vector MEM-SIZE))
(define cand-count 0) ; number of instructions in candidate program
(define output-constraint constraint-all)
(define SUPPORT `all)

(define (to-number word)
  (cond
   [(equal? word `up) UP]
   [(equal? word `down) DOWN]
   [(equal? word `left) LEFT]
   [(equal? word `right) RIGHT]
   [else word]))

;;; Converts a name of an instruction (as a symbol) to its numeric
;;; representation. Turns numbers into the code for @p.
(define (to-choice name)
  (if (vector-member name choice-id)
      (cons (vector-member name choice-id) 0)
      (cons (vector-member `@p choice-id) (to-number name))))

;;; Compile code (string of instructions) into output vector
;;; and return number of instructions in the given code
(define (compile code output output-lit)
  (define count 0)
  (define in (open-input-string code))
  (define (go)
    (define (append-vector inst)
      (vector-set! output count (car inst))
      (vector-set! output-lit count (cdr inst))
      (set! count (add1 count))
      (go))
    (let ([next (read in)])
	  (if (eof-object? next)
	      (void)
	      (append-vector (to-choice next)))))
  (go)
  count)

(define var 
  (case-lambda [(base i) (string->symbol (format "~a_v~a" base i))]
               [(base i j) (string->symbol (format "~a_~a_v~a" base i j))]))

(define (var-no-v base i)
  (string->symbol (format "~a_~a" base i)))

(define (makeBV bit)
  (string->symbol (format "BV~e" bit)))

(define (makebv bit)
  (string->symbol (format "bv~e" bit)))

(define (declare-bitvector )
  (pretty-display `(define-sort BV3 () (_ BitVec 3)))                            ; for index
  (pretty-display `(define-sort ,(makeBV HOLE_BIT) () (_ BitVec ,HOLE_BIT)))     ; for hole
  (pretty-display `(define-sort ,(makeBV SIZE) () (_ BitVec ,SIZE)))             ; for normal variables
  (pretty-display `(define-sort ,(makeBV STACK_SIZE) () (_ BitVec ,STACK_SIZE))) ; for stack
  (pretty-display `(define-sort ,(makeBV MEM_SIZE) () (_ BitVec ,MEM_SIZE)))     ; for mem
  (pretty-display `(define-sort ,(makeBV COMM_SIZE) () (_ BitVec ,COMM_SIZE)))   ; for comm
  (pretty-display `(define-sort ,(makeBV COMM_BIT) () (_ BitVec ,COMM_BIT)))     ; for comm index
  (pretty-display `(define-sort ,(makeBV TIME_SIZE) () (_ BitVec ,TIME_SIZE)))     ; for time
  )

;;;;;;;;;;;;;;;;;;;;;;;; Generate necessary Z3 functions ;;;;;;;;;;;;;;;;;;;;;;;;

(define-syntax-rule (define-fun id form ...)
  (define id `(define-fun id form ...)))

; for power-of-2-bit
;(define-fun bitidx ((i BV3)) (,STACK_TYPE)
;  (concat (_ bv0 ,(- (- STACK_SIZE 3) LOG_SIZE)) (concat i (_ bv0 ,LOG_SIZE))))

;;; Create index into "array" bitvector
(define (declare-bitidx func-name array-size index-size)
  (define array-type (string->symbol (format "BV~e" array-size)))
  (define index-type (string->symbol (format "BV~e" index-size)))
  (newline)
  (pretty-display
   `(define-fun ,func-name ((i ,index-type)) (,array-type)
      (bvmul (concat (_ bv0 ,(- array-size index-size)) i) (_ ,(makebv SIZE) ,array-size)))))

;;; Get an entry in "array" bitvector at the given index
(define (declare-get func-name array-size index-size index-func)
  (define array-type (string->symbol (format "BV~e" array-size)))
  (define index-type (string->symbol (format "BV~e" index-size)))
  (newline)
  (pretty-display 
   `(define-fun ,func-name ((array ,array-type) (index ,index-type)) (,TYPE)
      ((_ extract ,(sub1 SIZE) 0) (bvlshr array (,index-func index))))))

;;; Return the "array" bitvector that is replaced at the given index with the given value
(define (declare-modify func-name array-size index-size index-func)
  (define array-type (string->symbol (format "BV~e" array-size)))
  (define index-type (string->symbol (format "BV~e" index-size)))
  (newline)
  (pretty-display
   `(define-fun ,func-name ((array ,array-type) (index ,index-type) (ele ,TYPE)) (,array-type)
      (bvor
       (bvand array (bvnot (bvshl (_ ,EXP_MASK ,array-size) (,index-func index))))
       (bvshl (concat (_ bv0 ,(- array-size SIZE)) ele) (,index-func index))))))
      
(define (declare-functions)
  (declare-bitidx `bitidx-stack STACK_SIZE 3)
  (declare-bitidx `bitidx-mem   MEM_SIZE   SIZE)
  (declare-bitidx `bitidx-comm  COMM_SIZE  COMM_BIT)
  (declare-get `get-stack       STACK_SIZE 3    `bitidx-stack)
  (declare-get `get-mem         MEM_SIZE   SIZE `bitidx-mem)
  (declare-get `get-comm        COMM_SIZE  COMM_BIT `bitidx-comm)
  (declare-modify `modify-stack STACK_SIZE 3    `bitidx-stack)
  (declare-modify `modify-mem   MEM_SIZE   SIZE `bitidx-mem))

;;;;;;;;;;;;;;;;;;;;;;;; Generate Z3 variables ;;;;;;;;;;;;;;;;;;;;;;;;

(define (declare-init v n i bit)
  (for* ([step (in-range 0 n)])
    (pretty-display `(declare-const ,(var v step i) ,(makeBV bit)))))

(define (declare-init-zero v n i bit)
  (for* ([step (in-range 0 n)])
    (pretty-display `(declare-const ,(var v step i) ,(makeBV bit))))
  (pretty-display `(assert (= ,(var v 0 i) (_ ,(makebv 0) ,bit)))))

(define (declare-vector-one name i vec-size)
  (pretty-display `(declare-const ,(var name i) ,(makeBV (* vec-size SIZE)))))

(define (declare-holes n)
  (for* ([step (in-range 1 n)])
    (pretty-display `(declare-const ,(var-no-v `h step) ,(makeBV HOLE_BIT)))
    (pretty-display `(declare-const ,(var-no-v `hlit step) ,TYPE))))

(define (encode-program prog literal n name)
  (for* ([step (in-range 1 n)])
    (pretty-display `(declare-const ,(var-no-v name step) ,(makeBV HOLE_BIT)))
    (pretty-display `(assert (= ,(var-no-v name step) (_ ,(makebv (vector-ref prog (sub1 step))) ,HOLE_BIT))))
    (pretty-display `(declare-const ,(var-no-v (format "~alit" name) step) ,TYPE))
    (pretty-display `(assert (= ,(var-no-v (format "~alit" name) step) (_ ,(makebv (vector-ref literal (sub1 step))) ,SIZE))))
))

(define (declare-vars n from to)
  (for* ([i (in-range from to)])
       (declare-init `dst n i STACK_SIZE)
       (declare-init `rst n i STACK_SIZE)
       (declare-init `sp n i 3)
       (declare-init `rp n i 3)
       (declare-init `mem n i MEM_SIZE)

       (for* ([var `(t s r a b)])
	    (declare-init var n i SIZE))

       (for* ([var `(sendp0 sendp1 sendp2 sendp3 recvp0 recvp1 recvp2 recvp3)])
	    (declare-init-zero var n i COMM_BIT))

       (for* ([var `(send0 send1 send2 send3 recv0 recv1 recv2 recv3)])
	    (declare-vector-one var i COMM_ENTRIES))))

;;;;;;;;;;;;;;;;;;;;;;;; Generate Z3 formulas ;;;;;;;;;;;;;;;;;;;;;;;;

;;; syn is true for synthesizer, false for verifier
;;; when syn is true, memory out of bound check and communication check are included.
(define (generate-choice choice step n i name syn)
  (define prev (sub1 step))

  ;;; pop from data stack to s
  (define (shrink)
    (set! check_s (format "(= s_~e_v~e (get-stack dst_~e_v~e sp_~e_v~e))" step i prev i prev i))
    (set! check_sp (format "(= sp_~e_v~e (bvsub sp_~e_v~e (_ bv1 3))) " step i prev i)))

  ;;; pop from return stack to r
  (define (shrink-return)
    (set! check_r (format "(= r_~e_v~e (get-stack rst_~e_v~e rp_~e_v~e))" step i prev i prev i))
    (set! check_rp (format "(= rp_~e_v~e (bvsub rp_~e_v~e (_ bv1 3))) " step i prev i)))

  ;;; push from s to data stack
  (define (grow)
    (set! check_s (format "(= s_~e_v~e t_~a_v~e)" step i prev i))
    (set! check_sp (format "(= sp_~e_v~e (bvadd sp_~a_v~e (_ bv1 ~a))) " step i prev i 3))
    (set! check_dst (format "(= dst_~e_v~e (modify-stack dst_~a_v~e sp_~e_v~e s_~a_v~e))" step i prev i step i prev i)))

  ;;; push from r to return stack
  (define (grow-return)
    (set! check_r (format "(= r_~e_v~e t_~a_v~e)" step i prev i))
    (set! check_rp (format "(= rp_~e_v~e (bvadd rp_~a_v~e (_ bv1 ~a))) " step i prev i 3))
    (set! check_rst (format "(= rst_~e_v~e (modify-stack rst_~a_v~e rp_~e_v~e r_~a_v~e))" step i prev i step i prev i)))
  
  ;;; for pushing c to data stack
  (define (push-const c)
    (set! check_t (format "(= t_~e_v~e (_ bv~e ~e))" step i c SIZE))
    (grow))

  (define (multiply-step)
    (define ssize (sub1 SIZE))
    (define t-even (format "(concat ((_ extract ~a ~a) t_~e_v~e) ((_ extract ~a 1) t_~e_v~e))" ssize ssize prev i ssize prev i)) ; bvashr
    (define a-even (format "(concat ((_ extract 0 0) t_~e_v~e) ((_ extract ~a 1) a_~e_v~e))" prev i ssize prev i))

    (define sum (format "(bvadd (concat #b0 t_~e_v~e) (concat #b0 s_~e_v~e))" prev i prev i))
    (define sum17 (format "(concat ((_ extract ~a ~a) ~a) (_ bv0 ~a))" ssize ssize sum ssize))
    (define t-odd (format "(bvor ((_ extract ~a 1) ~a) ~a)" SIZE sum sum17))
    (define a-odd (format "(concat ((_ extract 0 0) ~a) ((_ extract ~a 1) a_~e_v~e))" sum ssize prev i))
    
    (set! check_t (format "(= t_~e_v~e (ite (= ((_ extract 0 0) a_~e_v~e) #b0) ~a ~a))" 
			  step i prev i t-even t-odd))
    (set! check_a (format "(= a_~e_v~e (ite (= ((_ extract 0 0) a_~e_v~e) #b0) ~a ~a))" 
			  step i prev i a-even a-odd)))

  (define (write-port reg port val)
    (string-append (string-append
      (format  "(ite (= ~a_~a_v~e (_ bv~e ~e)) " reg prev i val SIZE)
      (if syn
	  (format  "(and (and (= (get-comm send~a_v~e sendp~a_~a_v~e) t_~a_v~e) (= sendp~a_~e_v~e (bvadd sendp~a_~a_v~e (_ bv1 ~e)))) (bvule sendp~e_~e_v~e sendp~e_~e_v~e)) "
		   port i port prev i prev i     port step i port prev i COMM_BIT     port step i port (sub1 n) i)
	  (format  "(and (= (get-comm send~a_v~e sendp~a_~a_v~e) t_~a_v~e) (= sendp~a_~e_v~e (bvadd sendp~a_~a_v~e (_ bv1 ~e)))) "
		   port i port prev i prev i     port step i port prev i COMM_BIT)))
      (format  "(= sendp~e_~e_v~e sendp~e_~e_v~e))" port step i port prev i)))
    
  (define (read-port reg port val)
    (string-append (string-append
      (format "(ite (= ~a_~a_v~e (_ bv~e ~e)) " reg prev i val SIZE)
      (if syn
	  (format "(and (and (= (get-comm recv~a_v~e recvp~a_~a_v~e) t_~a_v~e) (= recvp~a_~e_v~e (bvadd recvp~a_~a_v~e (_ bv1 ~e)))) (bvule sendp~e_~e_v~e sendp~e_~e_v~e)) "
		  port i port prev i step i     port step i port prev i COMM_BIT     port step i port (sub1 n) i)
	  (format "(and (= (get-comm recv~a_v~e recvp~a_~a_v~e) t_~a_v~e) (= recvp~a_~e_v~e (bvadd recvp~a_~a_v~e (_ bv1 ~e)))) "
		  port i port prev i step i     port step i port prev i COMM_BIT)))
      (format "(= recvp~e_~e_v~e recvp~e_~e_v~e))" port step i port prev i)))
  
  ;;; check that value in register is valid for read or write from a port
  (define (mem-range reg)
    (if syn
	(string-append (string-append (string-append (string-append (string-append
          (format "(and (= ~a_~e_v~e ~a_~a_v~e) " reg step i reg prev i)
	  (format "(or (or (or (or (bvult ~a_~a_v~e (_ bv~e ~e)) " reg prev i MEM_ENTRIES SIZE))
	  (format "(= ~a_~a_v~e (_ bv~e ~e))) " reg prev i UP SIZE))
	  (format "(= ~a_~a_v~e (_ bv~e ~e))) " reg prev i DOWN SIZE))
          (format "(= ~a_~a_v~e (_ bv~e ~e))) " reg prev i LEFT SIZE))
          (format "(= ~a_~a_v~e (_ bv~e ~e))))" reg prev i RIGHT SIZE))
	(format "(= ~a_~e_v~e ~a_~a_v~e)" reg step i reg prev i)))

  ;;; default formula for an instruction: equal to the value in the previous step
  (define check_hole (format "(and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (= ~a_~e (_ bv~e ~e)) " name step (vector-member choice choice-id) HOLE_BIT))
  (define check_sp (format "(= sp_~e_v~e sp_~e_v~e)" step i prev i))
  (define check_rp (format "(= rp_~e_v~e rp_~e_v~e)" step i prev i))
  (define check_t (format "(= t_~e_v~e t_~e_v~e)" step i prev i))
  (define check_s (format "(= s_~e_v~e s_~e_v~e)" step i prev i))
  (define check_r (format "(= r_~e_v~e r_~e_v~e)" step i prev i))
  (define check_a (format "(= a_~e_v~e a_~e_v~e)" step i prev i))
  (define check_b (format "(= b_~e_v~e b_~e_v~e)" step i prev i))
  (define check_dst (format "(= dst_~e_v~e dst_~e_v~e)" step i prev i))
  (define check_rst (format "(= rst_~e_v~e rst_~e_v~e)" step i prev i))
  (define check_mem (format "(= mem_~e_v~e mem_~e_v~e)" step i prev i))
  (define check_sendp_u (format "(= sendp~e_~e_v~e sendp~e_~e_v~e)" U-ID step i U-ID prev i))
  (define check_sendp_d (format "(= sendp~e_~e_v~e sendp~e_~e_v~e)" D-ID step i D-ID prev i))
  (define check_sendp_l (format "(= sendp~e_~e_v~e sendp~e_~e_v~e)" L-ID step i L-ID prev i))
  (define check_sendp_r (format "(= sendp~e_~e_v~e sendp~e_~e_v~e)" R-ID step i R-ID prev i))
  (define check_recvp_u (format "(= recvp~e_~e_v~e recvp~e_~e_v~e)" U-ID step i U-ID prev i))
  (define check_recvp_d (format "(= recvp~e_~e_v~e recvp~e_~e_v~e)" D-ID step i D-ID prev i))
  (define check_recvp_l (format "(= recvp~e_~e_v~e recvp~e_~e_v~e)" L-ID step i L-ID prev i))
  (define check_recvp_r (format "(= recvp~e_~e_v~e recvp~e_~e_v~e)" R-ID step i R-ID prev i))

  (cond 
    ; 2*
    [(equal? choice `2*) 
               (set! check_t (format "(= t_~e_v~e (bvshl t_~e_v~e (_ bv1 ~e)))" step i prev i SIZE))]
    ; shiftl
    [(equal? choice `lshift)
     (set! check_t (format "(= t_~e_v~e (bvshl s_~e_v~e t_~e_v~e))" step i prev i prev i))
     (shrink)]
    ; 2/
    [(equal? choice `2/)
               (set! check_t (format "(= t_~e_v~e (bvashr t_~e_v~e (_ bv1 ~e)))" step i prev i SIZE))]
    ; shiftr
    [(equal? choice `rshift)
     (set! check_t (format "(= t_~e_v~e (bvashr s_~e_v~e t_~e_v~e))" step i prev i prev i))
     (shrink)]
    ; /
    [(equal? choice `/)
     (set! check_t (format "(= t_~e_v~e (bvsdiv s_~e_v~e t_~e_v~e))" step i prev i prev i))
     (shrink)]
    ; -
    [(equal? choice `-)
               (set! check_t (format "(= t_~e_v~e (bvnot t_~e_v~e))" step i prev i))]
    ; +
    [(equal? choice `+)
               (set! check_t 
		     (if (= step 1)
			 (format "(= t_~e_v~e (bvadd t_~e_v~e s_~e_v~e))" step i prev i prev i)
			 (format "(and (= t_~e_v~e (bvadd t_~e_v~e s_~e_v~e)) (= ~a_~a (_ bv~a ~a)))" 
				 step i prev i prev i     name prev (vector-member 'nop choice-id) HOLE_BIT)))
               (shrink)]
    ; and
    [(equal? choice `and)
               (set! check_t (format "(= t_~e_v~e (bvand t_~e_v~e s_~e_v~e))" step i prev i prev i))
               (shrink)]
    ; or
    [(equal? choice `or)
               (set! check_t (format "(= t_~e_v~e (bvxor t_~e_v~e s_~e_v~e))" step i prev i prev i))
               (shrink)]
    ; drop
    [(equal? choice `drop) 
               (set! check_t (format "(= t_~e_v~e s_~e_v~e)" step i prev i))
               (shrink)]
    ; dup
    [(equal? choice `dup)
               (set! check_t (format "(= t_~e_v~e t_~a_v~e)" step i prev i))
	       (grow)]
    ; @+ (can't read port)
    [(equal? choice `@+)
               (set! check_a 
		     (if syn
			 (format "(and (bvult a_~a_v~e (_ bv~e ~e)) (= a_~e_v~e (bvadd a_~a_v~e (_ bv1 ~a))))" 
				 prev i MEM_ENTRIES SIZE step i prev i SIZE)
			 (format "(= a_~e_v~e (bvadd a_~a_v~e (_ bv1 ~a)))" step i prev i SIZE)))
	       (set! check_t (format "(= t_~e_v~e (get-mem mem_~e_v~e a_~e_v~e))" step i prev i prev i))
	       (grow)]
    ; @
    [(equal? choice `@)
               (set! check_a (mem-range `a))
	       (set! check_t (format "(or (bvugt a_~a_v~e (_ bv~e ~e)) (= t_~e_v~e (get-mem mem_~e_v~e a_~e_v~e)))" 
				     prev i MEM_ENTRIES SIZE     step i prev i prev i))
	       (grow)
	       (set! check_recvp_u (read-port `a U-ID UP))
	       (set! check_recvp_d (read-port `a D-ID DOWN))
	       (set! check_recvp_l (read-port `a L-ID LEFT))
	       (set! check_recvp_r (read-port `a R-ID RIGHT))]
    ; @b
    [(equal? choice `@b)
               (set! check_b (mem-range `b))
	       (set! check_t (format "(or (bvugt b_~a_v~e (_ bv~e ~e)) (= t_~e_v~e (get-mem mem_~e_v~e b_~e_v~e)))" 
				     prev i MEM_ENTRIES SIZE     step i prev i prev i))
	       (set! check_recvp_u (read-port `b U-ID UP))
	       (set! check_recvp_d (read-port `b D-ID DOWN))
	       (set! check_recvp_l (read-port `b L-ID LEFT))
	       (set! check_recvp_r (read-port `b R-ID RIGHT))
	       (grow)]
    ; @p
    [(equal? choice `@p)
               (set! check_t (format "(= t_~e_v~e ~alit_~e)" step i name step))
	       (grow)]
    ; !+ (can't store to port)
    [(equal? choice `!+)
               (set! check_a 
    		     (if syn
    			 (format "(and (bvult a_~a_v~e (_ bv~e ~e)) (= a_~e_v~e (bvadd a_~a_v~e (_ bv1 ~a))))" 
    				 prev i MEM_ENTRIES SIZE step i prev i SIZE)
    			 (format "(= a_~e_v~e (bvadd a_~a_v~e (_ bv1 ~a)))" step i prev i SIZE)))
    	       (set! check_t (format "(= t_~e_v~e s_~e_v~e)" step i prev i))
    	       (set! check_mem (format "(= mem_~e_v~e (modify-mem mem_~a_v~e a_~a_v~e t_~a_v~e))" 
    				       step i prev i prev i prev i))
    	       (shrink)]
    ; !
    [(equal? choice `!)
               (set! check_a (mem-range `a))
    	       (set! check_t (format "(= t_~e_v~e s_~e_v~e)" step i prev i))
    	       (set! check_mem (format "(ite (bvult a_~a_v~e (_ bv~e ~e)) (= mem_~e_v~e (modify-mem mem_~a_v~e a_~a_v~e t_~a_v~e)) (= mem_~e_v~e mem_~a_v~e))" 
    				       step i MEM_ENTRIES SIZE step i prev i prev i prev i step i prev i))
    	       (set! check_sendp_u (write-port `a U-ID UP))
    	       (set! check_sendp_d (write-port `a D-ID DOWN))
    	       (set! check_sendp_l (write-port `a L-ID LEFT))
    	       (set! check_sendp_r (write-port `a R-ID RIGHT))
    	       (shrink)]
    ; !b
    [(equal? choice `!b)
               (set! check_b (mem-range `b))
    	       (set! check_t (format "(= t_~e_v~e s_~e_v~e)" step i prev i))
    	       (set! check_mem (format "(ite (bvult b_~a_v~e (_ bv~e ~e)) (= mem_~e_v~e (modify-mem mem_~a_v~e b_~a_v~e t_~a_v~e)) (= mem_~e_v~e mem_~a_v~e))" 
    				       step i MEM_ENTRIES SIZE step i prev i prev i prev i step i prev i))
    	       (set! check_sendp_u (write-port `b U-ID UP))
    	       (set! check_sendp_d (write-port `b D-ID DOWN))
    	       (set! check_sendp_l (write-port `b L-ID LEFT))
    	       (set! check_sendp_r (write-port `b R-ID RIGHT))
    	       (shrink)]
    ; a!
    [(equal? choice `a!)
               (set! check_a (format "(= a_~e_v~e t_~a_v~e)" step i prev i))
	       (set! check_t (format "(= t_~e_v~e s_~e_v~e)" step i prev i))
	       (shrink)]
    ; b!
    [(equal? choice `b!)
               (set! check_b (format "(= b_~e_v~e t_~a_v~e)" step i prev i))
	       (set! check_t (format "(= t_~e_v~e s_~e_v~e)" step i prev i))
	       (shrink)]
    ; a
    [(equal? choice `a)
               (set! check_t (format "(= t_~e_v~e a_~e_v~e)" step i prev i))
	       (grow)]
    ; +*
    [(equal? choice `+*)
               (multiply-step)]
    ; pop
    [(equal? choice `pop)
	       (set! check_t (format "(= t_~e_v~e r_~e_v~e)" step i prev i))
               (shrink-return)
	       (grow)]
    ; push
    [(equal? choice `push)
	       (set! check_t (format "(= t_~e_v~e s_~e_v~e)" step i prev i))
               (grow-return)
	       (shrink)]
    ; over
    [(equal? choice `over)
               (set! check_t (format "(= t_~e_v~e s_~a_v~e)" step i prev i))
	       (grow)]
    ; nop
    [(equal? choice `nop) (void)]
        )
  (set! check_sp (string-append check_sp ") "))
  (set! check_rp (string-append check_rp ") "))
  (set! check_t (string-append check_t ") "))
  (set! check_s (string-append check_s ") "))
  (set! check_r (string-append check_r ") "))
  (set! check_a (string-append check_a ") "))
  (set! check_b (string-append check_b ") "))
  (set! check_dst (string-append check_dst ") "))
  (set! check_rst (string-append check_rst ") "))
  (set! check_mem (string-append check_mem ") "))
  (set! check_sendp_u (string-append check_sendp_u ") "))
  (set! check_sendp_d (string-append check_sendp_d ") "))
  (set! check_sendp_l (string-append check_sendp_l ") "))
  (set! check_sendp_r (string-append check_sendp_r ") "))
  (set! check_recvp_u (string-append check_recvp_u ") "))
  (set! check_recvp_d (string-append check_recvp_d ") "))
  (set! check_recvp_l (string-append check_recvp_l ") "))
  (set! check_recvp_r (string-append check_recvp_r ")"))
  (string-append (string-append (string-append (string-append (string-append (string-append (string-append (string-append 
    (string-append (string-append (string-append (string-append (string-append (string-append (string-append (string-append 
      (string-append (string-append
    check_hole 
    check_sp)
    check_rp)
    check_t)
    check_s) 
    check_r) 
    check_a)
    check_b)
    check_dst)
    check_rst)
    check_mem)
    check_sendp_u)
    check_sendp_d)
    check_sendp_l)
    check_sendp_r)
    check_recvp_u)
    check_recvp_d)
    check_recvp_l)
    check_recvp_r))

;;; Handle assumption differently from assertion on input-outpout pair.
;;; Memory out of bound check and communication check happen here.
;;; This function is only called by verifier.
(define (generate-choice-assumption choice step i name)
  (define prev (sub1 step))
  
  (define (mem-range reg)
    (string-append (string-append (string-append (string-append (string-append
      (format "(and (and (and (and (bvuge ~a_~a_v~e (_ bv~e ~e)) " reg prev i MEM_ENTRIES SIZE))
      (format "(not (= ~a_~a_v~e (_ bv~e ~e)))) " reg prev i UP SIZE))
      (format "(not (= ~a_~a_v~e (_ bv~e ~e)))) " reg prev i DOWN SIZE))
      (format "(not (= ~a_~a_v~e (_ bv~e ~e)))) " reg prev i LEFT SIZE))
      (format "(not (= ~a_~a_v~e (_ bv~e ~e))))" reg prev i RIGHT SIZE)))

  (define check_assump 
  (cond 
    ; @+ (can't read port)
    [(equal? choice `@+)
	 (format "(bvuge a_~a_v~e (_ bv~e ~e))" prev i MEM_ENTRIES SIZE)]
    ; @
    [(equal? choice `@) (mem-range `a)]
    ; @b
    [(equal? choice `@b) (mem-range `b)]
    ; !+ (can't store to port)
    [(equal? choice `!+)
	 (format "(bvuge a_~a_v~e (_ bv~e ~e))" prev i MEM_ENTRIES SIZE)]
    ; !
    [(equal? choice `!) (mem-range `a)]
    ; !b
    [(equal? choice `!b) (mem-range `b)]))

    (format "(and (= ~a_~e (_ bv~e ~e)) ~a)" name step (vector-member choice choice-id) HOLE_BIT check_assump))

;;; Returns the bv constant representing the given time (n).
(define (bv-time n)
  (format "(_ bv~a ~a)" n TIME_SIZE))

(define (generate-time-constraint step)
  (pretty-display (format "(assert (= time_~a (bvadd time_~a (ite (bvult h_~a (_ bv~a ~a)) ~a ~a))))"
                          step (sub1 step) step N_OF_SLOW HOLE_BIT (bv-time 10) (bv-time 3))))

;;; Generates assertions for holes which are already know, given a
;;; spec. The spec should have normal instructions as well as
;;; underscores for holes.
(define (generate-known-holes sketch begin n)
  (let* ([instrs (list->vector (program->instructions sketch))]
         [len    (vector-length instrs)]) ;; TODO: get rid of len?
    (for ([i (in-range 0 n)])
         (let* ([instr (vector-ref instrs i)]
                [num   (string->number instr)])
           (unless (equal? instr "_")
             (pretty-display (format "(assert (= h_~a (_ bv~a ~a)))"
                                     (add1 (+ i begin)) (car (to-choice (string->symbol instr))) HOLE_BIT))
             (when num
               (pretty-display (format "(assert (= hlit_~a (_ bv~a ~a)))"
                                       (add1 (+ i begin)) num SIZE))))))))

;;; Returns an expression counting the number of trailing nops given
;;; the total number of slots. This can then be subtracted from the
;;; total time.
(define (nop-offset begin end)
  (define bv-nop (format "(_ bv~a ~a)" (vector-member 'nop choice-id) HOLE_BIT))
  (define (go hole-number expr)
    (format "(ite (= h_~a ~a) (bvadd ~a ~a) ~a)"
            hole-number bv-nop (bv-time 3) expr (bv-time 0)))
  (define start (format "(ite (= h_~a ~a) ~a ~a)" begin bv-nop (bv-time 3) (bv-time 0)))
  (foldr go start (reverse (stream->list (in-range (add1 begin) (add1 end))))))

(define (generate-time-constraints begin end repeat time-limit)
  (for* ([step (in-range begin (add1 end))])
        (pretty-display `(declare-const ,(var-no-v `time step) ,(makeBV TIME_SIZE))))
  (pretty-display `(assert (= ,(var-no-v `time begin) (_ bv0 ,TIME_SIZE))))
  (for* ([step (in-range (add1 begin) (add1 end))])
	(generate-time-constraint step))
  (pretty-display `(declare-const total_time ,(makeBV TIME_SIZE)))
  (pretty-display (format "(assert (= total_time (bvmul (bvsub time_~a ~a) (_ bv~a ~a))))" 
			  end (nop-offset (add1 begin) end) repeat TIME_SIZE))
  (pretty-display (format "(assert (bvult total_time (_ bv~a ~a)))" time-limit TIME_SIZE)))

;;; Generates assertions for repeated body such that 
;;; the i-th hole in the body is the same for all copies.
(define (generate-repeat-constraints init body repeat)
  (for* ([i (in-range 0 body)]
	 [t (in-range 1 repeat)])
       (pretty-display (format "(assert (= h_~a h_~a))" (add1 (+ init i)) (add1 (+ init (+ i (* t body))))))
       (pretty-display (format "(assert (= hlit_~a hlit_~a))" (add1 (+ init i)) (add1 (+ init (+ i (* t body))))))))

(define support-all '#(@p @+ @b @ !+ !b ! +* 2* 2/ - + and or drop dup pop over a nop push b! a! lshift rshift /))
(define support-no-fake '#(@p @+ @b @ !+ !b ! +* 2* 2/ - + and or drop dup pop over a nop push b! a!))
(define support-no-fake-no-p '#(@+ @b @ !+ !b ! +* 2* 2/ - + and or drop dup pop over a nop push b! a!))
(define support-no-mem '#(@p +* 2* 2/ - + and or drop dup pop over a nop push a!))
(define support-no-mem-no-p '#(+* 2* 2/ - + and or drop dup pop over a nop push a!))
(define (support)
  (cond
   [(equal? SUPPORT `all) support-all]
   [(equal? SUPPORT `no-fake) support-no-fake]
   [(equal? SUPPORT `no-fake-no-p) support-no-fake-no-p]
   [(equal? SUPPORT `no-mem) support-no-mem]
   [(equal? SUPPORT `no-mem-no-p) support-no-mem-no-p]))

(define (support-len) (vector-length (support)))
 
(define (generate-formula step n version name syn [sup (support)])
  (define clauses (make-vector (vector-length sup)))
  (when (= (modulo step 4) 0)
	(pretty-display (format "(assert (= (_ bv0 2) ((_ extract 1 0) ~a_~a)))" name step)))
  (for* ([i (in-range 0 (vector-length sup))])
	(vector-set! clauses i (generate-choice (vector-ref sup i) step n version name syn)))
  (pretty-display `(assert ,(conjunct clauses (vector-length sup) `or))))

(define (generate-formulas n from to name syn [sup (support)])
  (for* ([version (in-range from to)]
	 [step (in-range 1 n)])
    (generate-formula step n version name syn sup)))

;;;;;;;;;;;;;;;;;;;;;;;; Synthesizer helper functions ;;;;;;;;;;;;;;;;;;;;;;;;

(define (assert-state-input state n i)
  (pretty-display (format "(assert (= dst_~e_v~e (_ bv~e ~e)))" n i (stack-body (progstate-data state)) STACK_SIZE))
  (pretty-display (format "(assert (= sp_~e_v~e (_ bv~e ~e)))" n i (stack-sp (progstate-data state)) 3))
  (pretty-display (format "(assert (= rst_~e_v~e (_ bv~e ~e)))" n i (stack-body (progstate-return state)) STACK_SIZE))
  (pretty-display (format "(assert (= rp_~e_v~e (_ bv~e ~e)))" n i (stack-sp (progstate-return state)) 3))
  (pretty-display (format "(assert (= mem_~e_v~e (_ bv~e ~e)))" n i (progstate-memory state) MEM_SIZE))
  (pretty-display (format "(assert (= t_~e_v~e (_ bv~e ~e)))" n i (progstate-t state) SIZE))
  (pretty-display (format "(assert (= s_~e_v~e (_ bv~e ~e)))" n i (progstate-s state) SIZE))
  (pretty-display (format "(assert (= r_~e_v~e (_ bv~e ~e)))" n i (progstate-r state) SIZE))
  (pretty-display (format "(assert (= a_~e_v~e (_ bv~e ~e)))" n i (progstate-a state) SIZE))
  (pretty-display (format "(assert (= b_~e_v~e (_ bv~e ~e)))" n i (progstate-b state) SIZE)))

(define (assert-state-output state n i)
  (when (progstate-data output-constraint)
	(pretty-display (format "(assert (= dst_~e_v~e (_ bv~e ~e)))" n i (stack-body (progstate-data state)) STACK_SIZE))
	(pretty-display (format "(assert (= sp_~e_v~e (_ bv~e ~e)))" n i (stack-sp (progstate-data state)) 3)))
  (when (progstate-return output-constraint)
	(pretty-display (format "(assert (= rst_~e_v~e (_ bv~e ~e)))" n i (stack-body (progstate-return state)) STACK_SIZE))
	(pretty-display (format "(assert (= rp_~e_v~e (_ bv~e ~e)))" n i (stack-sp (progstate-return state)) 3)))
  (when (progstate-memory output-constraint)
	(pretty-display (format "(assert (= mem_~e_v~e (_ bv~e ~e)))" n i (progstate-memory state) MEM_SIZE)))
  (when (progstate-t output-constraint)
	(pretty-display (format "(assert (= t_~e_v~e (_ bv~e ~e)))" n i (progstate-t state) SIZE)))
  (when (progstate-s output-constraint)
	(pretty-display (format "(assert (= s_~e_v~e (_ bv~e ~e)))" n i (progstate-s state) SIZE)))
  (when (progstate-r output-constraint)
	(pretty-display (format "(assert (= r_~e_v~e (_ bv~e ~e)))" n i (progstate-r state) SIZE)))
  (when (progstate-a output-constraint)
	(pretty-display (format "(assert (= a_~e_v~e (_ bv~e ~e)))" n i (progstate-a state) SIZE)))
  (when (progstate-b output-constraint)
	(pretty-display (format "(assert (= b_~e_v~e (_ bv~e ~e)))" n i (progstate-b state) SIZE))))

(define (assert-comm comm n i)
  (pretty-display (format "(assert (= send~e_v~e (_ bv~e ~e)))" U-ID i (commstate-send-u comm) COMM_SIZE))
  (pretty-display (format "(assert (= send~e_v~e (_ bv~e ~e)))" D-ID i (commstate-send-d comm) COMM_SIZE))
  (pretty-display (format "(assert (= send~e_v~e (_ bv~e ~e)))" L-ID i (commstate-send-l comm) COMM_SIZE))
  (pretty-display (format "(assert (= send~e_v~e (_ bv~e ~e)))" R-ID i (commstate-send-r comm) COMM_SIZE))
  (pretty-display (format "(assert (= recv~e_v~e (_ bv~e ~e)))" U-ID i (commstate-recv-u comm) COMM_SIZE))
  (pretty-display (format "(assert (= recv~e_v~e (_ bv~e ~e)))" D-ID i (commstate-recv-d comm) COMM_SIZE))
  (pretty-display (format "(assert (= recv~e_v~e (_ bv~e ~e)))" L-ID i (commstate-recv-l comm) COMM_SIZE))
  (pretty-display (format "(assert (= recv~e_v~e (_ bv~e ~e)))" R-ID i (commstate-recv-r comm) COMM_SIZE))
  (pretty-display (format "(assert (= sendp~e_~e_v~e (_ bv~e ~e)))" U-ID n i (commstate-sendp-u comm) COMM_BIT))
  (pretty-display (format "(assert (= sendp~e_~e_v~e (_ bv~e ~e)))" D-ID n i (commstate-sendp-d comm) COMM_BIT))
  (pretty-display (format "(assert (= sendp~e_~e_v~e (_ bv~e ~e)))" L-ID n i (commstate-sendp-l comm) COMM_BIT))
  (pretty-display (format "(assert (= sendp~e_~e_v~e (_ bv~e ~e)))" R-ID n i (commstate-sendp-r comm) COMM_BIT))
  (pretty-display (format "(assert (= recvp~e_~e_v~e (_ bv~e ~e)))" U-ID n i (commstate-recvp-u comm) COMM_BIT))
  (pretty-display (format "(assert (= recvp~e_~e_v~e (_ bv~e ~e)))" D-ID n i (commstate-recvp-d comm) COMM_BIT))
  (pretty-display (format "(assert (= recvp~e_~e_v~e (_ bv~e ~e)))" L-ID n i (commstate-recvp-l comm) COMM_BIT))
  (pretty-display (format "(assert (= recvp~e_~e_v~e (_ bv~e ~e)))" R-ID n i (commstate-recvp-r comm) COMM_BIT)))

(define (assert-pair input output comm n i has-out)
  (assert-state-input input 0 i)
  (when has-out
      (assert-state-output output n i)
      (assert-comm comm n i)))

(define (assert-input-output n has-out)
  (foldl (lambda (p i)
           (assert-pair (inout-input p) (inout-output p) (inout-comm p) n i has-out)
           (add1 i))
         0
         inout-list))

;;;;;;;;;;;;;;;;;;;;;;;; Verifier helper functions ;;;;;;;;;;;;;;;;;;;;;;;;

;;; Turn vector of cluases into a string of conjunction or disjunction of the cluases 
(define (conjunct clauses size conj)
  (define s "")
  (for ([i (in-range 1 size)])
       (set! s (string-append s (format "(~a " conj))))
  (set! s (string-append s (vector-ref clauses 0)))
  (for ([i (in-range 1 size)])
       (set! s (string-append s (format " ~a)" (vector-ref clauses i)))))
  s)

(define (generate-assumption step version name)
  (define clauses (make-vector 6))
  (define index 0)
  (for* ([choice `(@+ @ @b !+ ! !b)])
	(vector-set! clauses index 
		     (generate-choice-assumption choice step version name))
	(set! index (add1 index)))
  (conjunct clauses 6 `or))

(define (generate-assumptions n from to name)
  (define clauses (make-vector (* (- to from) (add1 n))))
  (define index 0)
  (for* ([version (in-range from to)]
	 [step (in-range 1 n)])
	(vector-set! clauses index (generate-assumption step version name))
	(set! index (add1 index)))
  (conjunct clauses  index `or))

(define (assert-input-eq)
  (for ([var `(dst rst mem t s r a b sp rp)])
       (pretty-display (format "(assert (= ~a_0_v0 ~a_0_v1))" var var)))
  (for ([i (in-range 0 4)])
       (pretty-display (format "(assert (= recv~a_v0 recv~a_v1))" i i))))

(define (assert-output-neq)
  ;;; Add this assertion to set the irrelevant communcation entries to 0
  ;;; so that it's easy for comparision
  (define (assert-ir-comm v n)
    (for* ([port `(send recv)]
	   [p (in-range 0 4)]
	   [i (in-range 0 COMM_ENTRIES)])
	  (define index (format "(_ bv~a ~a)" i COMM_BIT))
	  (pretty-display (format "(assert (or (bvult ~a ~ap~a_~a_v~a) (= (get-comm ~a~a_v~a ~a) (_ bv0 ~a))))" 
				  index port p n v   port p v index SIZE))))
  (assert-ir-comm 0 spec-count)
  (assert-ir-comm 1 cand-count)

  ;;; Assert outputs are not equal
  (define clauses (make-vector 26))
  (define index 0)

  (define (vector-add var)
    (vector-set! clauses index (format "(not (= ~a_~e_v0 ~a_~e_v1))" var spec-count var cand-count))
    (set! index (add1 index)))

  ;;; TODO: relax constraint here too
  (for ([var `(sendp0 sendp1 sendp2 sendp3 recvp0 recvp1 recvp2 recvp3)])
       (vector-add var))
  (for* ([var `(send recv)]
	 [channel (in-range 0 4)])
       (vector-set! clauses index (format "(not (= ~a~a_v0 ~a~a_v1))" var channel var channel))
       (set! index (add1 index)))
  (when (progstate-data output-constraint)
	(vector-add `dst)
	(vector-add `sp))
  (when (progstate-return output-constraint)
	(vector-add `rst)
	(vector-add `rp))
  (when (progstate-memory output-constraint)
	(vector-add `mem))
  (when (progstate-t output-constraint)
	(vector-add `t))
  (when (progstate-s output-constraint)
	(vector-add `s))
  (when (progstate-r output-constraint)
	(vector-add `r))
  (when (progstate-a output-constraint)
	(vector-add `a))
  (when (progstate-b output-constraint)
	(vector-add `b))

  ;;; Include assumption throughtout the program
  (pretty-display (format "(assert (or ~a ~a))" (conjunct clauses index `or) (generate-assumptions (add1 cand-count) 1 2 `cand))))

;;;;;;;;;;;;;;;;;;;;;;;; Synthesizer (and general formula generator) ;;;;;;;;;;;;;;;;;;;;;;;;

(define (synthesize-prog sketch init repeat has-prog has-out [time-limit #f])
  (define n (if (number? sketch) sketch (program-length sketch)))
  (define init-n (if (number? init) init (program-length init)))
  (define slots (+ init-n (* n repeat)))
  (define slots+1 (add1 slots))

  (declare-bitvector)
  (declare-functions)
  (newline)
  (if has-prog
      (encode-program spec spec-lit slots+1 `h)
      (declare-holes slots+1))

  (declare-vars slots+1 0 (length inout-list))

  (unless (number? init) (generate-known-holes init 0 init-n))
  (unless (number? sketch)
	  (for ([i (in-range 0 repeat)])
	       (generate-known-holes sketch (+ init-n (* i n)) n)))
  (generate-repeat-constraints init-n n repeat)

  (newline)
  (generate-formulas slots+1 0 (length inout-list) `h #t)
  (newline)
  (assert-input-output slots has-out)
  (newline)
  (when time-limit (generate-time-constraints init-n (+ init-n n) repeat time-limit))
  (newline)
  (pretty-display `(check-sat))
  (pretty-display `(get-model))
)

;;;;;;;;;;;;;;;;;;;;;;;; Verifier  ;;;;;;;;;;;;;;;;;;;;;;;;

(define (verify-prog)
  (declare-bitvector)
  (declare-functions)
  (newline)

  ; formular for spec
  (encode-program spec spec-lit (add1 spec-count) `spec)
  (newline)
  (declare-vars (add1 spec-count) 0 1)
  (newline)
  (generate-formulas (add1 spec-count) 0 1 `spec #t support-all)
  (newline)

  ; formular for candidate
  (encode-program cand cand-lit (add1 cand-count) `cand)
  (newline)
  (declare-vars (add1 cand-count) 1 2)
  (newline)
  (generate-formulas (add1 cand-count) 1 2 `cand #f)
  (newline)
  
  (assert-input-eq)
  (newline)
  (assert-output-neq)
  (newline)
  (pretty-display `(check-sat))
  (pretty-display `(get-model))
)

;;;;;;;;;;;;;;;;;;;;;;;; Input-Output-Rend-Recv storage, converter, and generator ;;;;;;;;;;;;;;;;;;;;;;;;

(define (vec-to-bits-inner vec vec-size)
  (define bits 0)
  (for* ([i (in-range 0 vec-size)])
    (define ele (if (< (- (- vec-size i) 1) (vector-length vec))
                    (vector-ref vec (- (- vec-size i) 1))
                    0))
    (set! bits (+ (arithmetic-shift bits SIZE) (modulo ele (arithmetic-shift 1 SIZE)))))
  bits)
(define (vec-to-bits vec vec-size)
  (if (vector? vec)
      (vec-to-bits-inner vec vec-size)
      vec))

(define (convert-progstate state)
  (define data (if (progstate-data state)
		   (stack (stack-sp (progstate-data state)) (vec-to-bits (stack-body (progstate-data state)) 8))
		   #f))
  (define return (if (progstate-return state)
		     (stack (stack-sp (progstate-return state)) (vec-to-bits (stack-body (progstate-return state)) 8))
		     #f))
  (define mem (if (progstate-memory state)
		  (vec-to-bits (progstate-memory state) MEM_ENTRIES)
		  #f))
  (progstate (progstate-a state) (progstate-b state) 
	     (progstate-p state) (progstate-i state) 
	     (progstate-r state) (progstate-s state) (progstate-t state)
	     data return mem))
             
(define (convert-commstate state)
  (commstate (vec-to-bits (commstate-send-u state) COMM_ENTRIES)
             (vec-to-bits (commstate-send-d state) COMM_ENTRIES)
             (vec-to-bits (commstate-send-l state) COMM_ENTRIES)
             (vec-to-bits (commstate-send-r state) COMM_ENTRIES)
             (vec-to-bits (commstate-recv-u state) COMM_ENTRIES)
             (vec-to-bits (commstate-recv-d state) COMM_ENTRIES)
             (vec-to-bits (commstate-recv-l state) COMM_ENTRIES)
             (vec-to-bits (commstate-recv-r state) COMM_ENTRIES)
             (commstate-sendp-u state) (commstate-sendp-d state) (commstate-sendp-l state) (commstate-sendp-r state)
             (commstate-recvp-u state) (commstate-recvp-d state) (commstate-recvp-l state) (commstate-recvp-r state)))


;;;;;;;;;;;;;;;;;;;;;;;; GreenSyn API ;;;;;;;;;;;;;;;;;;;;;;;;

(define current-input 0)
(define current-output 0)
(define current-comm 0)

(provide (all-defined-out))

;;; Set
;;; 1) number of entries of memory
;;; 2) number of entries of send/recv storage of each 4 neighbors
(define (greensyn-reset mem-entries comm-entries [constraint constraint-all] #:num-bits [num-bits 18] #:inst-pool [support `no-fake] )
  (set! output-constraint constraint)
  (set! SUPPORT support)

  (set! SIZE num-bits) ; number of bits per word
  (set! TYPE (string->symbol (format "BV~e" SIZE)))
  (set! MAX (sub1 (arithmetic-shift 1 SIZE)))
  (set! EXP_MASK (string->symbol (format "bv~e" MAX)))

  (set! STACK_SIZE (* 8 SIZE))
  (set! STACK_TYPE (string->symbol (format "BV~e" STACK_SIZE)))

  (set! MEM_ENTRIES mem-entries)
  (set! MEM_SIZE (* MEM_ENTRIES SIZE))
  (set! MEM_TYPE (string->symbol (format "BV~e" MEM_SIZE)))

  (set! COMM_ENTRIES comm-entries)
  (set! COMM_SIZE (* COMM_ENTRIES SIZE))
  (set! COMM_TYPE (string->symbol (format "BV~e" COMM_SIZE)))
  (set! COMM_BIT (inexact->exact (floor (+ (/ (log COMM_ENTRIES) (log 2)) 1))))

  (set! inout-list '()))

;;; Set input for counterexmaple.
(define (greensyn-input state)
  (set! current-input (convert-progstate state)))

;;; Set output for counterexmaple.
(define (greensyn-output state)
  (set! current-output (convert-progstate state)))

;;; Set send/recv storage for counterexmaple.
(define (greensyn-send-recv state)
  (set! current-comm (convert-commstate state)))

;;; Add previously set counterexample (input, output, and send/recv)
;;; to the list that will be generated as formula.
;;; If input, output, send/recv are set but not commit, 
;;; the counterexample won't be included in the generated formula
(define (greensyn-commit)
  (set! inout-list (cons (inout (convert-progstate current-input)
                                (convert-progstate current-output)
                                (convert-commstate current-comm))
                         inout-list)))

;;; Set spec for verification
(define (greensyn-spec string)
  (set! spec-count (compile string spec spec-lit)))

;;; Generate Z3 file for synthesis from the list of counterexamples
;;; Usage:
;;; (greensyn-reset)
;;; { (greensyn-input input) (greensyn-output output) (greensyn-send-recv send-recv) (greensyn-commit) }+
;;; (greensyn-check-sat file number_of_slots)
(define (greensyn-check-sat #:file [file "prog.smt2"] sketch [init 0] [repeat 1] #:time-limit [time-limit #f])
  (define out (open-output-file file #:exists 'replace))
  (parameterize ([current-output-port out])
    (synthesize-prog sketch init repeat #f #t time-limit))
  (close-output-port out))

;;; Generate Z3 file for verification from spec and a given candidate
;;; Usage:
;;; (greensyn-reset)
;;; (greensyn-spec string_of_spec)
;;; (greensyn-verify file string_of_candidate)
;;; CAUTION: note that if intruction in the last slot is invalid
;;; it will return unsat!!!!!
(define (greensyn-verify file string)
  (set! cand-count (compile string cand cand-lit))
  (define out (open-output-file file #:exists 'replace))
  (parameterize ([current-output-port out])
    (verify-prog))
  (close-output-port out))

;;; Generate Z3 file according to the earlier set spec (greensyn-spec)
;;; if has-out is true, then the formula will assert on earlier set output (greensyn-output)
;;; otherwise, the formula won't include output
;;; Usage:
;;; (greensyn-reset)
;;; (greensyn-spec)
;;; (greensyn-input input) 
;;; (greensyn-output output) 
;;; (greensyn-send-recv send-recv)? 
;;; (greensyn-commit) }
;;; (greensyn-gen-formula string_of_candidate assert_output)
(define (greensyn-gen-formula file has-out)
  (define out (open-output-file file #:exists 'replace))
  (parameterize ([current-output-port out])
    (synthesize-prog spec-count 0 1 #t has-out))
  (close-output-port out))