-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcoq.go
1080 lines (906 loc) · 22.5 KB
/
coq.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package glang
import (
"fmt"
"io"
"math/big"
"path"
"path/filepath"
"sort"
"strings"
)
func addParens(needs_paren bool, expr string) string {
if needs_paren {
return "(" + expr + ")"
} else {
return expr
}
}
// buffer is a simple indenting pretty printer
type buffer struct {
lines []string
indentLevel int
}
func (pp buffer) indentation() string {
b := make([]byte, pp.indentLevel)
for i := range b {
b[i] = ' '
}
return string(b)
}
func (pp *buffer) appendLine(line string) {
pp.lines = append(pp.lines, line)
}
func (pp *buffer) AddLine(line string) {
if line == "" {
pp.appendLine("")
} else {
pp.appendLine(pp.indentation() + indent(pp.indentLevel, line))
}
}
// Add adds formatted to the buffer
func (pp *buffer) Add(format string, args ...interface{}) {
pp.AddLine(fmt.Sprintf(format, args...))
}
func (pp *buffer) Indent(spaces int) {
pp.indentLevel += spaces
}
func (pp *buffer) Block(prefix string, format string, args ...interface{}) int {
pp.AddLine(prefix + indent(len(prefix), fmt.Sprintf(format, args...)))
pp.Indent(len(prefix))
return len(prefix)
}
func (pp buffer) Build() string {
return strings.Join(pp.lines, "\n")
}
func indent(spaces int, s string) string {
lines := strings.Split(s, "\n")
indentation := strings.Repeat(" ", spaces)
for i, line := range lines {
if i == 0 || line == "" {
continue
}
lines[i] = indentation + line
}
return strings.Join(lines, "\n")
}
func (pp *buffer) AddComment(c string) {
if c == "" {
return
}
// these hacks ensure that Go comments don't insert stray Coq comments
c = strings.ReplaceAll(c, "(*", "( *")
c = strings.ReplaceAll(c, "*)", "* )")
indent := pp.Block("(* ", "%s *)", c)
pp.Indent(-indent)
}
func quote(s string) string {
return `"` + s + `"`
}
// FIXME: why is this needed?
func binder(s string) string {
if s == "_" {
return "<>"
}
return quote(s)
}
// FieldDecl is a name:type declaration (for a struct or function binders)
type FieldDecl struct {
Name string
Type Type
}
func (d FieldDecl) CoqBinder() string {
return binder(d.Name)
}
func (d FieldDecl) Coq(needs_paren bool) string {
return binder(d.Name)
}
// StructDecl is a Coq record for a Go struct
type StructType struct {
Fields []FieldDecl
}
// CoqDecl implements the Decl interface
//
// A struct declaration simply consists of the struct descriptor
func (d StructType) Coq(needs_paren bool) string {
var pp buffer
pp.Add("structT [")
pp.Indent(2)
for i, fd := range d.Fields {
sep := ";"
if i == len(d.Fields)-1 {
sep = ""
}
pp.Add("%s :: %s%s", quote(fd.Name), fd.Type.Coq(false), sep)
}
pp.Indent(-2)
pp.AddLine("]")
return addParens(needs_paren, pp.Build())
}
type TypeDecl struct {
Name string
Body Type
TypeParams []TypeIdent
}
func (d TypeDecl) CoqDecl() string {
var pp buffer
typeParams := ""
for _, t := range d.TypeParams {
typeParams += fmt.Sprintf("(%s: go_type) ", t.Coq(false))
}
pp.Add("Definition %s %s: go_type := %s.", d.Name, typeParams, d.Body.Coq(false))
return pp.Build()
}
func (d TypeDecl) DefName() (bool, string) {
return true, d.Name
}
// Type represents some Coq type.
//
// Structurally identical to Expr but serves as a nice annotation in the type
// system for where types are expected.
type Type interface {
// If needs_paren is true, this should be generated with parentheses.
Coq(needs_paren bool) string
}
// TypeIdent is an identifier referencing a type.
//
// Much like the Type interface this is the same as Ident but signals that a Go
// type rather than a value is being referenced.
type TypeIdent string
func (t TypeIdent) Coq(needs_paren bool) string {
return string(t)
}
type MapType struct {
Key Type
Value Type
}
func (t MapType) Coq(needs_paren bool) string {
return NewCallExpr(GallinaIdent("mapT"), t.Key, t.Value).Coq(needs_paren)
}
type ChanType struct {
Elem Type
}
func (t ChanType) Coq(needs_paren bool) string {
return NewCallExpr(GallinaIdent("chanT"), t.Elem).Coq(needs_paren)
}
type FuncType struct {
}
func (t FuncType) Coq(needs_paren bool) string {
return "funcT"
}
type SliceType struct {
Value Type
}
func (t SliceType) Coq(needs_paren bool) string {
return "sliceT"
}
type ArrayType struct {
Len uint64
Elem Type
}
func (t ArrayType) Coq(needs_paren bool) string {
return NewCallExpr(GallinaIdent(fmt.Sprintf("arrayT %d", t.Len)), t.Elem).Coq(needs_paren)
}
type Expr interface {
// If needs_paren is true, this should be generated with parentheses.
Coq(needs_paren bool) string
}
// GallinaIdent is a identifier in Gallina (and not a variable)
//
// A GallinaIdent is translated literally to Coq.
type GallinaIdent string
func (e GallinaIdent) Coq(needs_paren bool) string {
return string(e)
}
// A Go qualified identifier, which is translated to a Gallina qualified
// identifier.
type PackageIdent struct {
Package string
Ident string
}
func (e PackageIdent) Coq(needs_paren bool) string {
return fmt.Sprintf("%s.%s", ThisIsBadAndShouldBeDeprecatedGoPathToCoqPath(e.Package), e.Ident)
}
var Skip Expr = GallinaIdent("Skip")
type ParenExpr struct {
Inner Expr
}
func (e ParenExpr) Coq(needs_paren bool) string {
return fmt.Sprintf("(%s)", e.Inner.Coq(needs_paren))
}
// IdentExpr is a go_lang-level variable
//
// An IdentExpr is quoted in Coq.
type IdentExpr string
func (e IdentExpr) Coq(needs_paren bool) string {
return quote(string(e))
}
// GallinaString is a Gallina string, wrapped in quotes
//
// This is functionally identical to IdentExpr, but semantically quite
// different.
type GallinaString string
func (s GallinaString) Coq(needs_paren bool) string {
return quote(string(s))
}
// CallExpr includes primitives and references to other functions.
type CallExpr struct {
MethodName Expr
Args []Expr
}
// NewCallExpr is a convenience to construct a CallExpr statically, especially
// for a fixed number of arguments.
func NewCallExpr(name Expr, args ...Expr) CallExpr {
if len(args) == 0 {
args = []Expr{Tt}
}
return CallExpr{MethodName: name, Args: args}
}
func (s CallExpr) Coq(needs_paren bool) string {
comps := []string{s.MethodName.Coq(true)}
for _, a := range s.Args {
comps = append(comps, a.Coq(true))
}
return addParens(needs_paren, strings.Join(comps, " "))
}
type ContinueExpr struct {
}
func (e ContinueExpr) Coq(needs_paren bool) string {
return fmt.Sprintf("continue: #()")
}
type BreakExpr struct {
}
func (e BreakExpr) Coq(needs_paren bool) string {
return fmt.Sprintf("break: #()")
}
type ReturnExpr struct {
Value Expr
}
func (e ReturnExpr) Coq(needs_paren bool) string {
return fmt.Sprintf("return: %s", e.Value.Coq(needs_paren))
}
type DoExpr struct {
Expr Expr
}
func (b DoExpr) Coq(needs_paren bool) string {
var pp buffer
pp.Add("do: %s", b.Expr.Coq(true))
return addParens(needs_paren, pp.Build())
}
func NewDoSeq(e, cont Expr) SeqExpr {
return SeqExpr{Expr: DoExpr{Expr: e}, Cont: cont}
}
type SeqExpr struct {
Expr, Cont Expr
}
func (b SeqExpr) Coq(needs_paren bool) string {
var pp buffer
if b.Cont == nil {
pp.Add("%s", b.Expr.Coq(false))
return addParens(needs_paren, pp.Build())
}
pp.Add("%s;;;", b.Expr.Coq(false))
pp.Add("%s", b.Cont.Coq(false))
return addParens(needs_paren, pp.Build())
}
type LetExpr struct {
// Names is a list to support anonymous and tuple-destructuring bindings.
//
// If Names is an empty list the binding is anonymous.
Names []string
ValExpr Expr
Cont Expr
}
func (e LetExpr) isAnonymous() bool {
return len(e.Names) == 0
}
func (b LetExpr) Coq(needs_paren bool) string {
var pp buffer
if b.Cont == nil {
if !b.isAnonymous() {
panic("let expr with nil cont but non-anonymous binding")
}
pp.Add("%s", b.ValExpr.Coq(false))
return addParens(needs_paren, pp.Build())
}
if b.isAnonymous() {
pp.Add("%s;;", b.ValExpr.Coq(false))
} else if len(b.Names) == 1 {
pp.Add("let: %s := %s in", binder(b.Names[0]), b.ValExpr.Coq(true))
} else if len(b.Names) == 2 {
pp.Add("let: (%s, %s) := %s in",
binder(b.Names[0]),
binder(b.Names[1]),
b.ValExpr.Coq(true))
} else if len(b.Names) == 3 {
pp.Add("let: ((%s, %s), %s) := %s in",
binder(b.Names[0]),
binder(b.Names[1]),
binder(b.Names[2]),
b.ValExpr.Coq(true))
} else if len(b.Names) == 4 {
pp.Add("let: (((%s, %s), %s), %s) := %s in",
binder(b.Names[0]),
binder(b.Names[1]),
binder(b.Names[2]),
binder(b.Names[3]),
b.ValExpr.Coq(true))
} else if len(b.Names) == 5 {
pp.Add("let: ((((%s, %s), %s), %s), %s) := %s in",
binder(b.Names[0]),
binder(b.Names[1]),
binder(b.Names[2]),
binder(b.Names[3]),
binder(b.Names[4]),
b.ValExpr.Coq(true))
} else {
panic(fmt.Sprintf("no support for destructuring more than %d return values (up to 5 supported)", len(b.Names)))
}
pp.Add("%s", b.Cont.Coq(false))
return addParens(needs_paren, pp.Build())
}
type fieldVal struct {
Field string
Value Expr
}
// A StructLiteral represents a record literal construction using name fields.
//
// Relies on Coq record syntax to correctly order fields for the record's
// constructor.
type StructLiteral struct {
StructType Expr
Elts []fieldVal
}
// AddField appends a new (field, val) pair to a StructLiteral.
func (sl *StructLiteral) AddField(field string, value Expr) {
sl.Elts = append(sl.Elts, fieldVal{field, value})
}
func (sl StructLiteral) Coq(needs_paren bool) string {
var pp buffer
method := "struct.make"
pp.Add("%s %s [{", method, sl.StructType.Coq(true))
pp.Indent(2)
for i, f := range sl.Elts {
terminator := ";"
if i == len(sl.Elts)-1 {
terminator = ""
}
pp.Add("%s ::= %s%s", quote(f.Field), f.Value.Coq(false), terminator)
}
pp.Indent(-2)
pp.Add("}]")
return addParens(needs_paren, pp.Build())
}
type BoolLiteral bool
func (b BoolLiteral) Coq(needs_paren bool) string {
if b {
return "#true"
} else {
return "#false"
}
}
var (
False BoolLiteral = BoolLiteral(false)
True BoolLiteral = BoolLiteral(true)
)
type BoolVal struct {
Value Expr
}
func (b BoolVal) Coq(needs_paren bool) string {
return fmt.Sprintf("#%s", b.Value.Coq(true))
}
type UnitLiteral struct{}
var Tt UnitLiteral = struct{}{}
func (tt UnitLiteral) Coq(needs_paren bool) string {
return "#()"
}
type ZLiteral struct {
Value *big.Int
}
func (z ZLiteral) Coq(needs_paren bool) string {
return z.Value.String()
}
type StringLiteral struct {
Value string
}
func (s StringLiteral) Coq(needs_paren bool) string {
return fmt.Sprintf(`"%s"`, strings.Replace(s.Value, `"`, `""`, -1)) + "%go"
}
type Int64Val struct {
Value Expr
}
func (l Int64Val) Coq(needs_paren bool) string {
return fmt.Sprintf("#(W64 %s)", l.Value.Coq(true))
}
type Int32Val struct {
Value Expr
}
func (l Int32Val) Coq(needs_paren bool) string {
return fmt.Sprintf("#(W32 %s)", l.Value.Coq(true))
}
type Int16Val struct {
Value Expr
}
func (l Int16Val) Coq(needs_paren bool) string {
return fmt.Sprintf("#(W16 %s)", l.Value.Coq(true))
}
type Int8Val struct {
Value Expr
}
func (l Int8Val) Coq(needs_paren bool) string {
return fmt.Sprintf("#(W8 %s)", l.Value.Coq(true))
}
type StringVal struct {
Value Expr
}
func (l StringVal) Coq(needs_paren bool) string {
return fmt.Sprintf(`#%s`, l.Value.Coq(true))
}
// BinOp is an enum for a Coq binary operator
type BinOp int
// Constants for the supported Coq binary operators
const (
OpPlus BinOp = iota
OpMinus
OpEquals
OpNotEquals
OpLessThan
OpGreaterThan
OpLessEq
OpGreaterEq
OpEqualsZ
OpLessThanZ
OpGreaterThanZ
OpLessEqZ
OpGreaterEqZ
OpGallinaAppend
OpAppend
OpMul
OpQuot
OpRem
OpAnd
OpOr
OpXor
OpLAnd
OpLOr
OpShl
OpShr
)
type BinaryExpr struct {
X Expr
Op BinOp
Y Expr
}
func (be BinaryExpr) Coq(needs_paren bool) string {
coqBinOp := map[BinOp]string{
OpPlus: "+",
OpMinus: "-",
OpEquals: "=",
OpNotEquals: "≠",
OpGallinaAppend: "++",
OpAppend: "+",
OpMul: "*",
OpQuot: "`quot`",
OpRem: "`rem`",
OpLessThan: "<",
OpGreaterThan: ">",
OpLessEq: "≤",
OpGreaterEq: "≥",
OpEqualsZ: "=?",
OpLessThanZ: "<?",
OpGreaterThanZ: ">?",
OpLessEqZ: "<=?",
OpGreaterEqZ: ">=?",
OpAnd: "`and`",
OpOr: "`or`",
OpXor: "`xor`",
OpLAnd: "&&",
OpLOr: "||",
OpShl: "≪",
OpShr: "≫",
}
if binop, ok := coqBinOp[be.Op]; ok {
expr := fmt.Sprintf("%s %s %s",
be.X.Coq(true), binop, be.Y.Coq(true))
return addParens(needs_paren, expr)
}
panic(fmt.Sprintf("unknown binop %d", be.Op))
}
type GallinaNotExpr struct {
X Expr
}
func (e GallinaNotExpr) Coq(needs_paren bool) string {
return fmt.Sprintf("(negb %s)", e.X.Coq(true))
}
type NotExpr struct {
X Expr
}
func (e NotExpr) Coq(needs_paren bool) string {
return fmt.Sprintf("(~ %s)", e.X.Coq(true))
}
type TupleExpr []Expr
func (te TupleExpr) Coq(needs_paren bool) string {
var comps []string
for _, t := range te {
comps = append(comps, t.Coq(false))
}
return fmt.Sprintf("(%s)",
indent(1, strings.Join(comps, ", ")))
}
type ListExpr []Expr
func (le ListExpr) Coq(needs_paren bool) string {
var comps []string
for _, t := range le {
comps = append(comps, t.Coq(false))
}
elements := indent(1, strings.Join(comps, "; "))
if strings.HasPrefix(elements, "#") {
// [# ...] is a vector notation while we want the list notation [ ... ]
// (and `[#` is a single token even if the vector notation isn't in
// scope)
return fmt.Sprintf("[ %s ]", elements)
}
return fmt.Sprintf("[%s]", elements)
}
type DerefExpr struct {
X Expr
Ty Expr
}
func (e DerefExpr) Coq(needs_paren bool) string {
expr := fmt.Sprintf("![%s] %s", e.Ty.Coq(false), e.X.Coq(true))
return addParens(needs_paren, expr)
}
type RefExpr struct {
X Expr
Ty Expr
}
func (e RefExpr) Coq(needs_paren bool) string {
return NewCallExpr(GallinaIdent("ref_ty"), e.Ty, e.X).Coq(needs_paren)
}
type StoreStmt struct {
Dst Expr
Ty Expr
X Expr
}
func (e StoreStmt) Coq(needs_paren bool) string {
expr := fmt.Sprintf("%s <-[%s] %s", e.Dst.Coq(true), e.Ty.Coq(false), e.X.Coq(true))
return addParens(needs_paren, expr)
}
type IfExpr struct {
Cond Expr
Then Expr
Else Expr
}
func flowBranch(pp *buffer, prefix string, e Expr, suffix string) {
code := e.Coq(false) + suffix
if !strings.ContainsRune(code, '\n') {
// compact, single-line form
indent := pp.Block(prefix+" ", "%s", code)
pp.Indent(-indent)
return
}
// full multiline, nicely indented form
pp.AddLine(prefix)
pp.Indent(2)
pp.AddLine(code)
pp.Indent(-2)
}
func (ife IfExpr) Coq(needs_paren bool) string {
var pp buffer
// Since we are parenthesesizing all if, we don't need to parenthesize the things inside the if
pp.Add("(if: %s", ife.Cond.Coq(false))
flowBranch(&pp, "then", ife.Then, "")
flowBranch(&pp, "else", ife.Else, ")")
return pp.Build()
}
// The init statement must wrap the ForLoopExpr, so it can make use of bindings
// introduced there.
type ForLoopExpr struct {
Cond Expr
Post Expr
// the body of the loop
Body Expr
}
func (e ForLoopExpr) Coq(needs_paren bool) string {
var pp buffer
pp.Add("(for: (λ: <>, %s); (λ: <>, %s) := λ: <>,", e.Cond.Coq(false), e.Post.Coq(false))
pp.Indent(2)
pp.Add("%s)", e.Body.Coq(false))
return pp.Build()
}
type ForRangeSliceExpr struct {
Ty Expr
Slice Expr
Body Expr
}
func (e ForRangeSliceExpr) Coq(needs_paren bool) string {
var pp buffer
pp.Add("slice.for_range %s %s (λ: \"$key\" \"$value\",",
e.Ty.Coq(true),
e.Slice.Coq(true),
)
pp.Indent(2)
pp.Add("%s)", e.Body.Coq(false))
pp.Indent(-2)
return addParens(needs_paren, pp.Build())
}
type ForRangeChanExpr struct {
Chan Expr
Body Expr
}
func (e ForRangeChanExpr) Coq(needs_paren bool) string {
var pp buffer
pp.Add("chan.for_range %s (λ: \"$key\" \"$value\",",
e.Chan.Coq(true),
)
pp.Indent(2)
pp.Add("%s)", e.Body.Coq(false))
pp.Indent(-2)
return addParens(needs_paren, pp.Build())
}
// ForRangeMapExpr is a call to the map iteration helper.
type ForRangeMapExpr struct {
// map to iterate over
Map Expr
// body of loop, with KeyIdent and ValueIdent as free variables
Body Expr
}
func (e ForRangeMapExpr) Coq(needs_paren bool) string {
var pp buffer
pp.Add("map.for_range %s (λ: \"$key\" \"value\",", e.Map.Coq(true))
pp.Indent(2)
pp.Add("%s)", e.Body.Coq(false))
return addParens(needs_paren, pp.Build())
}
// SpawnExpr is a call to Spawn a thread running a procedure.
//
// The body can capture variables in the environment.
type SpawnExpr struct {
Body Expr
}
func (e SpawnExpr) Coq(needs_paren bool) string {
var pp buffer
pp.Block("Fork (", "%s)", e.Body.Coq(false))
return addParens(needs_paren, pp.Build())
}
// FuncLit is an unnamed function literal, consisting of its parameters and body.
type FuncLit struct {
Args []FieldDecl
Body Expr
}
func (e FuncLit) Coq(needs_paren bool) string {
var pp buffer
var args []string
for _, a := range e.Args {
args = append(args, a.CoqBinder())
}
if len(args) == 0 {
args = []string{"<>"}
}
sig := strings.Join(args, " ")
pp.Add("(λ: %s,", sig)
pp.Indent(2)
defer pp.Indent(-2)
pp.AddLine(e.Body.Coq(false))
pp.Add(")")
return pp.Build()
}
type ValueScoped struct {
Value Expr
}
func (e ValueScoped) Coq(needs_paren bool) string {
return e.Value.Coq(true) + "%V"
}
// FuncDecl declares a function, including its parameters and body.
type FuncDecl struct {
Name string
RecvArg *FieldDecl
Args []FieldDecl
Body Expr
Comment string
}
// Signature renders the function declaration's bindings
func (d FuncDecl) Signature() string {
var args []string
if d.RecvArg != nil {
args = append(args, d.RecvArg.CoqBinder())
}
for _, a := range d.Args {
args = append(args, a.CoqBinder())
}
if len(d.Args) == 0 {
args = append(args, "<>")
}
return strings.Join(args, " ")
}
// CoqDecl implements the Decl interface
//
// For FuncDecl this emits the Coq vernacular Definition that defines the whole
// function.
func (d FuncDecl) CoqDecl() string {
var pp buffer
pp.AddComment(d.Comment)
pp.Add("Definition %s : val :=", d.Name)
func() {
pp.Indent(2)
defer pp.Indent(-2)
pp.Add("rec: \"%s\" %s :=", d.Name, d.Signature())
pp.Indent(2)
defer pp.Indent(-2)
pp.AddLine(d.Body.Coq(false) + ".")
}()
return pp.Build()
}
func (d FuncDecl) DefName() (bool, string) {
return true, d.Name
}
type ConstDecl struct {
Name string
Val Expr
Type Expr
Comment string
}
func (d ConstDecl) CoqDecl() string {
var pp buffer
pp.AddComment(d.Comment)
indent := pp.Block("Definition ", "%s : %s := %s.",
d.Name, d.Type.Coq(false), d.Val.Coq(false))
pp.Indent(-indent)
return pp.Build()
}
func (d ConstDecl) DefName() (bool, string) {
return true, d.Name
}
type InstanceDecl struct {
Type Expr
// If not global, instance will be export
Global bool
Body Expr
// Can be empty (instance gets an automatic name in Coq)
Name string
}
func (d InstanceDecl) CoqDecl() string {
var pp buffer
qualifier := "#[export]"
if d.Global {
qualifier = "#[global]"
}
pp.Add("%s Instance %s : %s :=",
qualifier, d.Name, d.Type.Coq(false))
pp.Indent(2)
pp.Add("%s.", d.Body.Coq(false))
return pp.Build()
}
func (d InstanceDecl) DefName() (bool, string) {
return true, d.Name
}
type AxiomDecl struct {
DeclName string
Type Expr
}
func (d AxiomDecl) CoqDecl() string {
return fmt.Sprintf("Axiom %s : %s.", d.DeclName, d.Type.Coq(false))
}
func (d AxiomDecl) DefName() (bool, string) {
return true, d.DeclName
}
// Decl is a FuncDecl, StructDecl, CommentDecl, or ConstDecl
type Decl interface {
CoqDecl() string
DefName() (bool, string) // If true, then the Gallina identifier that is defined by this decl.
}
type PtrType struct {
}
func (t PtrType) Coq(needs_paren bool) string {
return "ptrT"
}
func TypeMethod(typeName string, methodName string) string {
return fmt.Sprintf("%s__%s", typeName, methodName)
}
const importHeader string = `
From New.golang Require Import defn.
`
// These will not end up in `File.Decls`, they are put into `File.Imports` by `translatePackage`.
type ImportDecl struct {
Path string
}
// This is an injective mapping
// FIXME: should really use this
func goPathToCoqPath(p string) string {
p = strings.ReplaceAll(p, "_", "__")
p = strings.ReplaceAll(p, ".", "_dot_")
p = strings.ReplaceAll(p, "-", "_dash_")
return p
}
func ThisIsBadAndShouldBeDeprecatedGoPathToCoqPath(p string) string {
p = strings.ReplaceAll(p, "_", "_")
p = strings.ReplaceAll(p, ".", "_")
p = strings.ReplaceAll(p, "-", "_")
return p
}
// ImportToPath converts a Go import path to a Coq path
func ImportToPath(pkgPath string) string {
coqPath := ThisIsBadAndShouldBeDeprecatedGoPathToCoqPath(pkgPath)
p := path.Dir(coqPath)
filename := path.Base(coqPath) + ".v"
return filepath.Join(p, filename)
}
func (decl ImportDecl) CoqDecl() string {
coqImportQualid := strings.ReplaceAll(ThisIsBadAndShouldBeDeprecatedGoPathToCoqPath(decl.Path), "/", ".")
return fmt.Sprintf("Require Export New.code.%s.", coqImportQualid)
}
func (decl ImportDecl) DefName() (bool, string) {
return false, ""
}
// ImportDecls groups imports into one declaration so they can be printed