-
Notifications
You must be signed in to change notification settings - Fork 11
/
goose.go
2218 lines (2080 loc) · 61.8 KB
/
goose.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 goose implements conversion from Go source to Perennial definitions.
//
// The exposed interface allows converting individual files as well as whole
// packages to a single Coq Ast with all the converted definitions, which
// include user-defined structs in Go as Coq records and a Perennial procedure
// for each Go function.
//
// See the Goose README at https://github.com/goose-lang/goose for a high-level
// overview. The source also has some design documentation at
// https://github.com/goose-lang/goose/tree/master/docs.
package goose
import (
"bytes"
"fmt"
"go/ast"
"go/constant"
"go/importer"
"go/printer"
"go/token"
"go/types"
"strconv"
"strings"
"unicode"
"github.com/goose-lang/goose/internal/coq"
"golang.org/x/tools/go/packages"
)
// Ctx is a context for resolving Go code's types and source code
type Ctx struct {
idents identCtx
info *types.Info
Fset *token.FileSet
pkgPath string
errorReporter
PkgConfig
dep *depTracker
}
// ExprValUsage says how the result of the currently generated expression will be used
type ExprValUsage int
const (
// ExprValLocal means result of this expression will only be used locally,
// or entirely discarded
ExprValLocal ExprValUsage = iota
// ExprValReturned means the result of this expression will be returned from
// the current function (i.e., the "early return" control effect is
// available here)
ExprValReturned
// ExprValLoop the result of this expression will control the current loop
// (i.e., the "break/continue" control effect is available here)
ExprValLoop
)
// PkgConfig holds package configuration for Coq conversion
type PkgConfig struct {
TranslationConfig
Ffi string
}
func getFfi(pkg *packages.Package) string {
seenFfis := make(map[string]struct{})
packages.Visit([]*packages.Package{pkg},
func(pkg *packages.Package) bool {
// the dependencies of an FFI are not considered as being used; this
// allows one FFI to be built on top of another
if _, ok := ffiMapping[pkg.PkgPath]; ok {
return false
}
return true
},
func(pkg *packages.Package) {
if ffi, ok := ffiMapping[pkg.PkgPath]; ok {
seenFfis[ffi] = struct{}{}
}
},
)
if len(seenFfis) > 1 {
panic(fmt.Sprintf("multiple ffis used %v", seenFfis))
}
for ffi := range seenFfis {
return ffi
}
return "none"
}
// NewPkgCtx initializes a context based on a properly loaded package
func NewPkgCtx(pkg *packages.Package, tr TranslationConfig) Ctx {
// Figure out which FFI we're using
config := PkgConfig{
TranslationConfig: tr,
Ffi: getFfi(pkg),
}
return Ctx{
idents: newIdentCtx(),
info: pkg.TypesInfo,
Fset: pkg.Fset,
pkgPath: pkg.PkgPath,
errorReporter: newErrorReporter(pkg.Fset),
PkgConfig: config,
}
}
// NewCtx loads a context for files passed directly,
// rather than loaded from a packages.
//
// NOTE: this is only used to load the negative tests by file; prefer to use
// NewPkgCtx and let [packages.Load] load and type check the Go code.
func NewCtx(pkgPath string, conf PkgConfig) Ctx {
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
// TODO: these instances give the generic arguments of function
// calls, use those
Instances: make(map[*ast.Ident]types.Instance),
Types: make(map[ast.Expr]types.TypeAndValue),
Scopes: make(map[ast.Node]*types.Scope),
}
fset := token.NewFileSet()
return Ctx{
idents: newIdentCtx(),
info: info,
Fset: fset,
pkgPath: pkgPath,
errorReporter: newErrorReporter(fset),
PkgConfig: conf,
}
}
// TypeCheck type-checks a set of files and stores the result in the Ctx
//
// NOTE: this is only needed when using NewCtx in the negative tests, which load
// individual files rather than a package.
func (ctx Ctx) TypeCheck(files []*ast.File) error {
imp := importer.ForCompiler(ctx.Fset, "source", nil)
conf := types.Config{Importer: imp}
_, err := conf.Check(ctx.pkgPath, ctx.Fset, files, ctx.info)
return err
}
func (ctx Ctx) where(node ast.Node) string {
return ctx.Fset.Position(node.Pos()).String()
}
func (ctx Ctx) printGo(node ast.Node) string {
var what bytes.Buffer
err := printer.Fprint(&what, ctx.Fset, node)
if err != nil {
panic(err.Error())
}
return what.String()
}
func (ctx Ctx) field(f *ast.Field) coq.FieldDecl {
if len(f.Names) > 1 {
ctx.futureWork(f, "multiple fields for same type (split them up)")
return coq.FieldDecl{}
}
if len(f.Names) == 0 {
ctx.unsupported(f, "unnamed field/parameter")
return coq.FieldDecl{}
}
return coq.FieldDecl{
Name: f.Names[0].Name,
Type: ctx.coqType(f.Type),
}
}
func (ctx Ctx) paramList(fs *ast.FieldList) []coq.FieldDecl {
var decls []coq.FieldDecl
for _, f := range fs.List {
ty := ctx.coqType(f.Type)
for _, name := range f.Names {
decls = append(decls, coq.FieldDecl{
Name: name.Name,
Type: ty,
})
}
if len(f.Names) == 0 { // Unnamed parameter
decls = append(decls, coq.FieldDecl{
Name: "",
Type: ty,
})
}
}
return decls
}
func (ctx Ctx) typeParamList(fs *ast.FieldList) []coq.TypeIdent {
var typeParams []coq.TypeIdent
if fs == nil {
return nil
}
for _, f := range fs.List {
for _, name := range f.Names {
typeParams = append(typeParams, coq.TypeIdent(name.Name))
}
if len(f.Names) == 0 { // Unnamed parameter
ctx.unsupported(fs, "unnamed type parameters")
}
}
return typeParams
}
func (ctx Ctx) structFields(fs *ast.FieldList) []coq.FieldDecl {
var decls []coq.FieldDecl
for _, f := range fs.List {
if len(f.Names) > 1 {
ctx.futureWork(f, "multiple fields for same type (split them up)")
return nil
}
if len(f.Names) == 0 {
ctx.unsupported(f, "unnamed (embedded) field")
return nil
}
ty := ctx.coqType(f.Type)
decls = append(decls, coq.FieldDecl{
Name: f.Names[0].Name,
Type: ty,
})
}
return decls
}
func addSourceDoc(doc *ast.CommentGroup, comment *string) {
if doc == nil {
return
}
if *comment != "" {
*comment += "\n\n"
}
*comment += strings.TrimSuffix(doc.Text(), "\n")
}
func (ctx Ctx) addSourceFile(node ast.Node, comment *string) {
if !ctx.AddSourceFileComments {
return
}
if *comment != "" {
*comment += "\n\n "
}
*comment += fmt.Sprintf("go: %s", ctx.where(node))
}
func (ctx Ctx) typeDecl(doc *ast.CommentGroup, spec *ast.TypeSpec) coq.Decl {
if spec.TypeParams != nil {
ctx.futureWork(spec, "generic named type (e.g. no generic structs)")
}
switch goTy := spec.Type.(type) {
case *ast.StructType:
ty := coq.StructDecl{
Name: spec.Name.Name,
}
addSourceDoc(doc, &ty.Comment)
ctx.addSourceFile(spec, &ty.Comment)
ty.Fields = ctx.structFields(goTy.Fields)
return ty
case *ast.InterfaceType:
ty := coq.InterfaceDecl{
Name: spec.Name.Name,
}
addSourceDoc(doc, &ty.Comment)
ctx.addSourceFile(spec, &ty.Comment)
ty.Methods = ctx.structFields(goTy.Methods)
return ty
default:
if spec.Assign == 0 {
return coq.TypeDef{
Name: spec.Name.Name,
Type: ctx.coqType(spec.Type),
}
} else {
return coq.AliasDecl{
Name: spec.Name.Name,
Type: ctx.coqType(spec.Type),
}
}
}
}
func toInitialLower(s string) string {
pastFirstLetter := false
return strings.Map(func(r rune) rune {
if !pastFirstLetter {
newR := unicode.ToLower(r)
pastFirstLetter = true
return newR
}
return r
}, s)
}
func (ctx Ctx) lenExpr(e *ast.CallExpr) coq.CallExpr {
x := e.Args[0]
xTy := ctx.typeOf(x)
switch ty := xTy.Underlying().(type) {
case *types.Slice:
return coq.NewCallExpr(coq.GallinaIdent("slice.len"), ctx.expr(x))
case *types.Map:
return coq.NewCallExpr(coq.GallinaIdent("MapLen"), ctx.expr(x))
case *types.Basic:
if ty.Kind() == types.String {
return coq.NewCallExpr(coq.GallinaIdent("StringLength"), ctx.expr(x))
}
}
ctx.unsupported(e, "length of object of type %v", xTy)
return coq.CallExpr{}
}
func (ctx Ctx) capExpr(e *ast.CallExpr) coq.CallExpr {
x := e.Args[0]
xTy := ctx.typeOf(x)
switch xTy.Underlying().(type) {
case *types.Slice:
return coq.NewCallExpr(coq.GallinaIdent("slice.cap"), ctx.expr(x))
}
ctx.unsupported(e, "capacity of object of type %v", xTy)
return coq.CallExpr{}
}
func (ctx Ctx) lockMethod(f *ast.SelectorExpr) coq.CallExpr {
l := ctx.expr(f.X)
switch f.Sel.Name {
case "Lock":
return coq.NewCallExpr(coq.GallinaIdent("Mutex__Lock"), l)
case "Unlock":
return coq.NewCallExpr(coq.GallinaIdent("Mutex__Unlock"), l)
case "TryLock":
return coq.NewCallExpr(coq.GallinaIdent("Mutex__TryLock"), l)
default:
ctx.nope(f, "method %s of sync.Mutex", ctx.printGo(f))
return coq.CallExpr{}
}
}
func (ctx Ctx) condVarMethod(f *ast.SelectorExpr) coq.CallExpr {
l := ctx.expr(f.X)
switch f.Sel.Name {
case "Signal":
return coq.NewCallExpr(coq.GallinaIdent("Cond__Signal"), l)
case "Broadcast":
return coq.NewCallExpr(coq.GallinaIdent("Cond__Broadcast"), l)
case "Wait":
return coq.NewCallExpr(coq.GallinaIdent("Cond__Wait"), l)
default:
ctx.unsupported(f, "method %s of sync.Cond", f.Sel.Name)
return coq.CallExpr{}
}
}
func (ctx Ctx) waitGroupMethod(f *ast.SelectorExpr, args []ast.Expr) coq.CallExpr {
callArgs := append([]ast.Expr{f.X}, args...)
switch f.Sel.Name {
case "Add":
return ctx.newCoqCall("waitgroup.Add", callArgs)
case "Done":
return ctx.newCoqCall("waitgroup.Done", callArgs)
case "Wait":
return ctx.newCoqCall("waitgroup.Wait", callArgs)
default:
ctx.unsupported(f, "method %s of sync.WaitGroup", f.Sel.Name)
return coq.CallExpr{}
}
}
func (ctx Ctx) prophIdMethod(f *ast.SelectorExpr, args []ast.Expr) coq.CallExpr {
callArgs := append([]ast.Expr{f.X}, args...)
switch f.Sel.Name {
case "ResolveBool", "ResolveU64":
return ctx.newCoqCall("ResolveProph", callArgs)
default:
ctx.unsupported(f, "method %s of primitive.ProphId", f.Sel.Name)
return coq.CallExpr{}
}
}
func (ctx Ctx) packageMethod(f *ast.SelectorExpr,
call *ast.CallExpr) coq.Expr {
args := call.Args
// TODO: replace this with an import that has all the right definitions with
// names that match Go
if isIdent(f.X, "filesys") {
return ctx.newCoqCall("FS."+toInitialLower(f.Sel.Name), args)
}
if isIdent(f.X, "disk") {
return ctx.newCoqCall("disk."+f.Sel.Name, args)
}
if isIdent(f.X, "atomic") {
return ctx.newCoqCall("atomic."+f.Sel.Name, args)
}
if isIdent(f.X, "machine") || isIdent(f.X, "primitive") {
switch f.Sel.Name {
case "UInt64Get", "UInt64Put", "UInt32Get", "UInt32Put":
return ctx.newCoqCall(f.Sel.Name, args)
case "RandomUint64":
return ctx.newCoqCall("rand.RandomUint64", args)
case "UInt64ToString":
return ctx.newCoqCall("uint64_to_string", args)
case "Linearize":
return coq.GallinaIdent("Linearize")
case "Assume":
return ctx.newCoqCall("control.impl.Assume", args)
case "Assert":
return ctx.newCoqCall("control.impl.Assert", args)
case "Exit":
return ctx.newCoqCall("control.impl.Exit", args)
case "WaitTimeout":
return ctx.newCoqCall("lock.condWaitTimeout", args)
case "Sleep":
return ctx.newCoqCall("time.Sleep", args)
case "TimeNow":
return ctx.newCoqCall("time.TimeNow", args)
case "MapClear":
return ctx.newCoqCall("MapClear", args)
case "NewProph":
return ctx.newCoqCall("NewProph", args)
default:
ctx.futureWork(f, "unhandled call to primitive.%s", f.Sel.Name)
return coq.CallExpr{}
}
}
if isIdent(f.X, "log") {
switch f.Sel.Name {
case "Print", "Printf", "Println":
return coq.LoggingStmt{GoCall: ctx.printGo(call)}
}
}
// FIXME: this hack ensures util.DPrintf runs correctly in goose-nfsd.
//
// We always pass #() instead of a slice with the variadic arguments. The
// function is important to handle but has no observable behavior in
// GooseLang, so it's ok to skip the arguments.
//
// See https://github.com/mit-pdos/goose-nfsd/blob/master/util/util.go
if isIdent(f.X, "util") && f.Sel.Name == "DPrintf" {
return coq.NewCallExpr(coq.GallinaIdent("util.DPrintf"),
ctx.expr(args[0]),
ctx.expr(args[1]),
coq.UnitLiteral{})
}
if isIdent(f.X, "fmt") {
switch f.Sel.Name {
case "Println", "Printf":
return coq.LoggingStmt{GoCall: ctx.printGo(call)}
}
}
if isIdent(f.X, "sync") {
switch f.Sel.Name {
case "NewCond":
return ctx.newCoqCall("NewCond", args)
}
}
pkg := f.X.(*ast.Ident)
return ctx.newCoqCallTypeArgs(
coq.GallinaIdent(coq.PackageIdent{Package: pkg.Name, Ident: f.Sel.Name}.Coq(true)),
ctx.typeList(call, ctx.info.Instances[f.Sel].TypeArgs),
args)
}
func (ctx Ctx) selectorMethod(f *ast.SelectorExpr, call *ast.CallExpr) coq.Expr {
args := call.Args
selectorType, ok := ctx.getType(f.X)
if !ok {
return ctx.packageMethod(f, call)
}
if isLockRef(selectorType) {
return ctx.lockMethod(f)
}
if isCFMutexRef(selectorType) {
return ctx.lockMethod(f)
}
if isCondVar(selectorType) {
return ctx.condVarMethod(f)
}
if isWaitGroup(selectorType) {
return ctx.waitGroupMethod(f, args)
}
if isProphId(selectorType) {
return ctx.prophIdMethod(f, args)
}
if isDisk(selectorType) {
method := fmt.Sprintf("disk.%s", f.Sel)
// skip disk argument (f.X) and just pass the method arguments
return ctx.newCoqCall(method, call.Args)
}
// Tricky: need the deref'd type for exact Underlying() case handling
// and name extraction, but also need original type for knowing
// whether to deref struct func field.
deref := selectorType
if pt, ok := selectorType.(*types.Pointer); ok {
deref = pt.Elem()
}
switch deref.Underlying().(type) {
case *types.Interface:
interfaceInfo, ok := ctx.getInterfaceInfo(selectorType)
if ok {
callArgs := append([]ast.Expr{f.X}, args...)
return ctx.newCoqCall(
coq.InterfaceMethodName(interfaceInfo.name, f.Sel.Name),
callArgs)
}
case *types.Struct:
structInfo, ok := ctx.getStructInfo(selectorType)
if !ok {
panic("expected struct")
}
// see if f.Sel.Name is a struct field, and translate accordingly if so
for _, name := range structInfo.fields() {
if f.Sel.Name == name {
return ctx.newCoqCallWithExpr(
ctx.structSelector(structInfo, f),
args)
}
}
}
namedTy := deref.(*types.Named)
tyName := ctx.qualifiedName(namedTy.Obj())
callArgs := append([]ast.Expr{f.X}, args...)
fullName := coq.MethodName(tyName, f.Sel.Name)
ctx.dep.addDep(fullName)
coqCall := ctx.coqRecurFunc(fullName, f.Sel)
return ctx.newCoqCallWithExpr(coqCall, callArgs)
}
func (ctx Ctx) newCoqCallTypeArgs(method coq.Expr, typeArgs []coq.Expr,
es []ast.Expr) coq.CallExpr {
var args []coq.Expr
for _, e := range es {
args = append(args, ctx.expr(e))
}
call := coq.NewCallExpr(method, args...)
call.TypeArgs = typeArgs
return call
}
func (ctx Ctx) newCoqCall(method string, es []ast.Expr) coq.CallExpr {
return ctx.newCoqCallTypeArgs(coq.GallinaIdent(method), nil, es)
}
func (ctx Ctx) newCoqCallWithExpr(method coq.Expr, es []ast.Expr) coq.CallExpr {
return ctx.newCoqCallTypeArgs(method, nil, es)
}
func (ctx Ctx) methodExpr(call *ast.CallExpr) coq.Expr {
args := call.Args
// discovered this API via
// https://go.googlesource.com/example/+/HEAD/gotypes#named-types
if ctx.info.Types[call.Fun].IsType() {
// string -> []byte conversions are handled specially
if f, ok := call.Fun.(*ast.ArrayType); ok {
if f.Len == nil && isIdent(f.Elt, "byte") {
arg := args[0]
if isString(ctx.typeOf(arg)) {
return ctx.newCoqCall("StringToBytes", args)
}
}
}
// []byte -> string are handled specially
if f, ok := call.Fun.(*ast.Ident); ok && f.Name == "string" {
arg := args[0]
if isString(ctx.typeOf(arg).Underlying()) {
return ctx.expr(args[0])
}
if !isByteSlice(ctx.typeOf(arg)) {
ctx.unsupported(call,
"conversion from type %v to string", ctx.typeOf(arg))
return coq.CallExpr{}
}
return ctx.newCoqCall("StringFromBytes", args)
}
// a different type conversion, which is a noop in GooseLang (which is
// untyped)
// TODO: handle integer conversions here, checking if call.Fun is an integer
// type; see https://github.com/goose-lang/goose/issues/14
return ctx.expr(args[0])
}
var retExpr coq.Expr
f := call.Fun
// IndexExpr and IndexListExpr represent calls like `f[T](x)`;
// we get rid of the `[T]` since we can figure that out from the
// ctx.info.Instances thing like we would need to for implicit type
// arguments
switch indexF := f.(type) {
case *ast.IndexExpr:
f = indexF.X
case *ast.IndexListExpr:
f = indexF.X
}
switch f := f.(type) {
case *ast.Ident:
typeArgs := ctx.typeList(call, ctx.info.Instances[f].TypeArgs)
// XXX: this could be a struct field of type `func()`; right now we
// don't support generic structs, so code with a generic function field
// will be rejected. But, in the future, that might change.
retExpr = ctx.newCoqCallTypeArgs(ctx.identExpr(f), typeArgs, args)
case *ast.SelectorExpr:
retExpr = ctx.selectorMethod(f, call)
case *ast.IndexExpr:
// generic type instantiation f[T]
ctx.nope(call, "double explicit generic type instantiation")
case *ast.IndexListExpr:
// generic type instantiation f[T, V]
ctx.nope(call, "double explicit generic type instantiation with multiple arguments")
default:
ctx.unsupported(call, "call to unexpected function (of type %T)", call.Fun)
}
return retExpr
}
func (ctx Ctx) makeSliceExpr(elt coq.Type, args []ast.Expr) coq.CallExpr {
if len(args) == 2 {
return coq.NewCallExpr(coq.GallinaIdent("NewSlice"), elt, ctx.expr(args[1]))
} else if len(args) == 3 {
return coq.NewCallExpr(coq.GallinaIdent("NewSliceWithCap"), elt, ctx.expr(args[1]), ctx.expr(args[2]))
} else {
ctx.unsupported(args[0], "Too many or too few arguments in slice construction")
return coq.CallExpr{}
}
}
// makeExpr parses a call to make() into the appropriate data-structure Call
func (ctx Ctx) makeExpr(args []ast.Expr) coq.CallExpr {
switch typeArg := args[0].(type) {
case *ast.MapType:
mapTy := ctx.mapType(typeArg)
return coq.NewCallExpr(coq.GallinaIdent("NewMap"), mapTy.Key, mapTy.Value, coq.UnitLiteral{})
case *ast.ArrayType:
if typeArg.Len != nil {
ctx.nope(typeArg, "can't make() arrays (only slices)")
}
elt := ctx.coqType(typeArg.Elt)
return ctx.makeSliceExpr(elt, args)
}
switch ty := ctx.typeOf(args[0]).Underlying().(type) {
case *types.Slice:
elt := ctx.coqTypeOfType(args[0], ty.Elem())
return ctx.makeSliceExpr(elt, args)
case *types.Map:
return coq.NewCallExpr(coq.GallinaIdent("NewMap"),
ctx.coqTypeOfType(args[0], ty.Key()),
ctx.coqTypeOfType(args[0], ty.Elem()),
coq.UnitLiteral{})
default:
ctx.unsupported(args[0],
"make type should be slice or map, got %v", ty)
}
return coq.CallExpr{}
}
// newExpr parses a call to new() into an appropriate allocation
func (ctx Ctx) newExpr(ty ast.Expr) coq.CallExpr {
if sel, ok := ty.(*ast.SelectorExpr); ok {
if isIdent(sel.X, "sync") && isIdent(sel.Sel, "Mutex") {
return coq.NewCallExpr(coq.GallinaIdent("newMutex"))
}
if isIdent(sel.X, "sync") && isIdent(sel.Sel, "WaitGroup") {
return coq.NewCallExpr(coq.GallinaIdent("waitgroup.New"))
}
if isIdent(sel.X, "cfmutex") && isIdent(sel.Sel, "CFMutex") {
return coq.NewCallExpr(coq.GallinaIdent("newMutex"))
}
}
if t, ok := ctx.typeOf(ty).(*types.Array); ok {
return coq.NewCallExpr(coq.GallinaIdent("zero_array"),
ctx.coqTypeOfType(ty, t.Elem()),
coq.IntLiteral{Value: uint64(t.Len())})
}
e := coq.NewCallExpr(coq.GallinaIdent("zero_val"), ctx.coqType(ty))
// check for new(T) where T is a struct, but not a pointer to a struct
// (new(*T) should be translated to ref (zero_val ptrT) as usual,
// a pointer to a nil pointer)
if info, ok := ctx.getStructInfo(ctx.typeOf(ty)); ok && !info.throughPointer {
return coq.NewCallExpr(coq.GallinaIdent("struct.alloc"), coq.StructDesc(info.name), e)
}
return coq.NewCallExpr(coq.GallinaIdent("ref"), e)
}
// integerConversion generates an expression for converting x to an integer
// of a specific width
//
// s is only used for error reporting
func (ctx Ctx) integerConversion(s ast.Node, x ast.Expr, width int) coq.Expr {
if info, ok := getIntegerType(ctx.typeOf(x)); ok {
if info.isUntyped {
ctx.todo(s, "conversion from untyped int to uint64")
}
if info.width == width {
return ctx.expr(x)
}
return coq.NewCallExpr(coq.GallinaIdent(fmt.Sprintf("to_u%d", width)),
ctx.expr(x))
}
ctx.unsupported(s, "casts from unsupported type %v to uint%d",
ctx.typeOf(x), width)
return nil
}
func (ctx Ctx) copyExpr(n ast.Node, dst ast.Expr, src ast.Expr) coq.Expr {
e := sliceElem(ctx.typeOf(dst))
return coq.NewCallExpr(coq.GallinaIdent("SliceCopy"),
ctx.coqTypeOfType(n, e),
ctx.expr(dst), ctx.expr(src))
}
func (ctx Ctx) callExpr(s *ast.CallExpr) coq.Expr {
if isIdent(s.Fun, "make") {
return ctx.makeExpr(s.Args)
}
if isIdent(s.Fun, "new") {
return ctx.newExpr(s.Args[0])
}
if isIdent(s.Fun, "len") {
return ctx.lenExpr(s)
}
if isIdent(s.Fun, "cap") {
return ctx.capExpr(s)
}
if isIdent(s.Fun, "append") {
elemTy := sliceElem(ctx.typeOf(s.Args[0]).Underlying())
if s.Ellipsis == token.NoPos {
return coq.NewCallExpr(coq.GallinaIdent("SliceAppend"),
ctx.coqTypeOfType(s, elemTy),
ctx.expr(s.Args[0]),
ctx.expr(s.Args[1]))
}
// append(s1, s2...)
return coq.NewCallExpr(coq.GallinaIdent("SliceAppendSlice"),
ctx.coqTypeOfType(s, elemTy),
ctx.expr(s.Args[0]),
ctx.expr(s.Args[1]))
}
if isIdent(s.Fun, "copy") {
return ctx.copyExpr(s, s.Args[0], s.Args[1])
}
if isIdent(s.Fun, "delete") {
if _, ok := ctx.typeOf(s.Args[0]).(*types.Map); !ok {
ctx.unsupported(s, "delete on non-map")
}
return coq.NewCallExpr(coq.GallinaIdent("MapDelete"), ctx.expr(s.Args[0]), ctx.expr(s.Args[1]))
}
if isIdent(s.Fun, "uint64") {
return ctx.integerConversion(s, s.Args[0], 64)
}
if isIdent(s.Fun, "uint32") {
return ctx.integerConversion(s, s.Args[0], 32)
}
if isIdent(s.Fun, "uint8") {
return ctx.integerConversion(s, s.Args[0], 8)
}
if isIdent(s.Fun, "panic") {
msg := "oops"
if e, ok := s.Args[0].(*ast.BasicLit); ok {
if e.Kind == token.STRING {
v := ctx.info.Types[e].Value
msg = constant.StringVal(v)
}
}
return coq.NewCallExpr(coq.GallinaIdent("Panic"), coq.GallinaString(msg))
}
// Special case for *sync.NewCond
if _, ok := s.Fun.(*ast.SelectorExpr); ok {
} else {
if signature, ok := ctx.typeOf(s.Fun).(*types.Signature); ok {
for j := 0; j < signature.Params().Len(); j++ {
if _, ok := signature.Params().At(j).Type().Underlying().(*types.Interface); ok {
interfaceName := signature.Params().At(j).Type().String()
structName := ctx.typeOf(s.Args[0]).String()
interfaceName = unqualifyName(interfaceName)
structName = unqualifyName(structName)
if interfaceName != structName && interfaceName != "" && structName != "" {
conversion := coq.StructToInterfaceDecl{
Fun: ctx.expr(s.Fun).Coq(true),
Struct: structName,
Interface: interfaceName,
Arg: ctx.expr(s.Args[0]).Coq(true),
}.Coq(true)
for i, arg := range s.Args {
if i > 0 {
conversion += " " + ctx.expr(arg).Coq(true)
}
}
return coq.CallExpr{MethodName: coq.GallinaIdent(conversion)}
}
}
}
}
}
return ctx.methodExpr(s)
}
func (ctx Ctx) qualifiedName(obj types.Object) string {
name := obj.Name()
if ctx.pkgPath == obj.Pkg().Path() {
// no module name needed
return name
}
return fmt.Sprintf("%s.%s", obj.Pkg().Name(), name)
}
func (ctx Ctx) selectExpr(e *ast.SelectorExpr) coq.Expr {
selectorType, ok := ctx.getType(e.X)
if !ok {
if isIdent(e.X, "filesys") {
return coq.GallinaIdent("FS." + e.Sel.Name)
}
if isIdent(e.X, "disk") {
return coq.GallinaIdent("disk." + e.Sel.Name)
}
if pkg, ok := getIdent(e.X); ok {
return coq.PackageIdent{
Package: pkg,
Ident: e.Sel.Name,
}
}
}
structInfo, ok := ctx.getStructInfo(selectorType)
// Check if the select expression is actually referring to a function object
// If it is, we need to translate to 'StructName__FuncName varName' instead
// of a struct access
_, isFuncType := (ctx.typeOf(e)).(*types.Signature)
if isFuncType {
m := coq.MethodName(structInfo.name, e.Sel.Name)
ctx.dep.addDep(m)
return coq.NewCallExpr(coq.GallinaIdent(m), ctx.expr(e.X))
}
if ok {
return ctx.structSelector(structInfo, e)
}
ctx.unsupported(e, "unexpected select expression")
return nil
}
func (ctx Ctx) structSelector(info structTypeInfo, e *ast.SelectorExpr) coq.StructFieldAccessExpr {
ctx.dep.addDep(info.name)
return coq.StructFieldAccessExpr{
Struct: info.name,
Field: e.Sel.Name,
X: ctx.expr(e.X),
ThroughPointer: info.throughPointer,
}
}
func (ctx Ctx) compositeLiteral(e *ast.CompositeLit) coq.Expr {
if _, ok := ctx.typeOf(e).Underlying().(*types.Slice); ok {
if len(e.Elts) == 0 {
elemTy := ctx.coqType(e.Type).(coq.SliceType).Value
zeroLit := coq.IntLiteral{Value: 0}
return coq.NewCallExpr(coq.GallinaIdent("NewSlice"), elemTy, zeroLit)
}
if len(e.Elts) == 1 {
return ctx.newCoqCall("SliceSingleton", []ast.Expr{e.Elts[0]})
}
ctx.unsupported(e, "slice literal with multiple elements")
return nil
}
info, ok := ctx.getStructInfo(ctx.typeOf(e))
if ok {
return ctx.structLiteral(info, e)
}
ctx.unsupported(e, "composite literal of type %v", ctx.typeOf(e))
return nil
}
func (ctx Ctx) structLiteral(info structTypeInfo,
e *ast.CompositeLit) coq.StructLiteral {
ctx.dep.addDep(info.name)
lit := coq.NewStructLiteral(info.name)
for _, el := range e.Elts {
switch el := el.(type) {
case *ast.KeyValueExpr:
ident, ok := getIdent(el.Key)
if !ok {
ctx.noExample(el.Key, "struct field keyed by non-identifier %+v", el.Key)
return coq.StructLiteral{}
}
lit.AddField(ident, ctx.expr(el.Value))
default:
ctx.unsupported(e,
"un-keyed struct literal field %v", ctx.printGo(el))
}
}
return lit
}
// basicLiteral parses a basic literal
//
// (unsigned) ints, strings, and booleans are supported
func (ctx Ctx) basicLiteral(e *ast.BasicLit) coq.Expr {
if e.Kind == token.STRING {
v := ctx.info.Types[e].Value
s := constant.StringVal(v)
if strings.ContainsRune(s, '"') {
ctx.unsupported(e, "string literals with quotes")
}
return coq.StringLiteral{Value: s}
}
if e.Kind == token.INT {
info, _ := getIntegerType(ctx.typeOf(e))
v := ctx.info.Types[e].Value
n, ok := constant.Uint64Val(v)
if !ok {
ctx.unsupported(e,
"int literals must be positive numbers")
return nil
}
if info.isUint64() {
return coq.IntLiteral{Value: n}
} else if info.isUint32() {
return coq.Int32Literal{Value: uint32(n)}
} else if info.isUint8() {
return coq.ByteLiteral{Value: uint8(n)}
}
}
ctx.unsupported(e, "literal with kind %s", e.Kind)
return nil
}
func (ctx Ctx) isNilCompareExpr(e *ast.BinaryExpr) bool {
if !(e.Op == token.EQL || e.Op == token.NEQ) {
return false
}
return ctx.info.Types[e.Y].IsNil()
}
func (ctx Ctx) binExpr(e *ast.BinaryExpr) coq.Expr {
op, ok := map[token.Token]coq.BinOp{
token.LSS: coq.OpLessThan,
token.GTR: coq.OpGreaterThan,
token.SUB: coq.OpMinus,
token.EQL: coq.OpEquals,
token.NEQ: coq.OpNotEquals,
token.MUL: coq.OpMul,
token.QUO: coq.OpQuot,
token.REM: coq.OpRem,
token.LEQ: coq.OpLessEq,
token.GEQ: coq.OpGreaterEq,
token.AND: coq.OpAnd,
token.LAND: coq.OpLAnd,
token.OR: coq.OpOr,
token.LOR: coq.OpLOr,
token.XOR: coq.OpXor,
token.SHL: coq.OpShl,
token.SHR: coq.OpShr,
}[e.Op]
if e.Op == token.ADD {
if isString(ctx.typeOf(e.X)) {
op = coq.OpAppend
} else {
op = coq.OpPlus
}
ok = true
}
if ok {
expr := coq.BinaryExpr{
X: ctx.expr(e.X),
Op: op,
Y: ctx.expr(e.Y),
}
if ctx.isNilCompareExpr(e) {
if _, ok := ctx.typeOf(e.X).(*types.Pointer); ok {
expr.Y = coq.Null
}
}
return expr
}
ctx.unsupported(e, "binary operator %v", e.Op)
return nil
}
func (ctx Ctx) sliceExpr(e *ast.SliceExpr) coq.Expr {
if e.Slice3 {
ctx.unsupported(e, "3-index slice")
return nil
}
if e.Max != nil {
ctx.unsupported(e, "setting the max capacity in a slice expression is not supported")
return nil
}
x := ctx.expr(e.X)
if e.Low != nil && e.High == nil {
return coq.NewCallExpr(coq.GallinaIdent("SliceSkip"),
ctx.coqTypeOfType(e, sliceElem(ctx.typeOf(e.X))),
x, ctx.expr(e.Low))
}
if e.Low == nil && e.High != nil {