forked from goose-lang/goose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoose.go
1572 lines (1460 loc) · 41.5 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/glang"
"golang.org/x/tools/go/packages"
)
// Ctx is a context for resolving Go code's types and source code
type Ctx struct {
info *types.Info
Fset *token.FileSet
pkgPath string
errorReporter
Config
dep *depTracker
}
// Config holds global configuration for Coq conversion
type Config struct {
AddSourceFileComments bool
TypeCheck bool
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 Translator) Ctx {
// Figure out which FFI we're using
var config Config
// TODO: this duplication is bad, Config should probably embed Translator or
// some other cleanup is needed
config.TypeCheck = tr.TypeCheck
config.AddSourceFileComments = tr.AddSourceFileComments
config.Ffi = getFfi(pkg)
return Ctx{
info: pkg.TypesInfo,
Fset: pkg.Fset,
pkgPath: pkg.PkgPath,
errorReporter: newErrorReporter(pkg.Fset),
Config: config,
}
}
// NewCtx loads a context for files passed directly,
// rather than loaded from a packages.
func NewCtx(pkgPath string, conf Config) 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{
info: info,
Fset: fset,
pkgPath: pkgPath,
errorReporter: newErrorReporter(fset),
Config: conf,
}
}
// FIXME: this is currently never called
// TypeCheck type-checks a set of files and stores the result in the Ctx
//
// This is needed before conversion to Coq to disambiguate some methods.
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) glang.FieldDecl {
if len(f.Names) > 1 {
ctx.futureWork(f, "multiple fields for same type (split them up)")
return glang.FieldDecl{}
}
if len(f.Names) == 0 {
ctx.unsupported(f, "unnamed field/parameter")
return glang.FieldDecl{}
}
return glang.FieldDecl{
Name: f.Names[0].Name,
Type: ctx.glangTypeFromExpr(f.Type),
}
}
func (ctx Ctx) paramList(fs *ast.FieldList) []glang.FieldDecl {
var decls []glang.FieldDecl
for _, f := range fs.List {
ty := ctx.glangTypeFromExpr(f.Type)
for _, name := range f.Names {
decls = append(decls, glang.FieldDecl{
Name: name.Name,
Type: ty,
})
}
if len(f.Names) == 0 { // Unnamed parameter
decls = append(decls, glang.FieldDecl{
Name: "",
Type: ty,
})
}
}
return decls
}
func (ctx Ctx) typeParamList(fs *ast.FieldList) []glang.TypeIdent {
var typeParams []glang.TypeIdent
if fs == nil {
return nil
}
for _, f := range fs.List {
for _, name := range f.Names {
typeParams = append(typeParams, glang.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) []glang.FieldDecl {
var decls []glang.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.glangTypeFromExpr(f.Type)
decls = append(decls, glang.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(spec *ast.TypeSpec) glang.Decl {
if spec.TypeParams != nil {
ctx.futureWork(spec, "generic named type (e.g. no generic structs)")
}
return glang.TypeDecl{
Name: spec.Name.Name,
Body: ctx.glangTypeFromExpr(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) glang.CallExpr {
x := e.Args[0]
xTy := ctx.typeOf(x)
switch ty := xTy.Underlying().(type) {
case *types.Slice:
return glang.NewCallExpr(glang.GallinaIdent("slice.len"), ctx.expr(x))
case *types.Map:
return glang.NewCallExpr(glang.GallinaIdent("MapLen"), ctx.expr(x))
case *types.Basic:
if ty.Kind() == types.String {
return glang.NewCallExpr(glang.GallinaIdent("StringLength"), ctx.expr(x))
}
}
ctx.unsupported(e, "length of object of type %v", xTy)
return glang.CallExpr{}
}
func (ctx Ctx) capExpr(e *ast.CallExpr) glang.CallExpr {
x := e.Args[0]
xTy := ctx.typeOf(x)
switch xTy.Underlying().(type) {
case *types.Slice:
return glang.NewCallExpr(glang.GallinaIdent("slice.cap"), ctx.expr(x))
}
ctx.unsupported(e, "capacity of object of type %v", xTy)
return glang.CallExpr{}
}
func (ctx Ctx) prophIdMethod(f *ast.SelectorExpr, args []ast.Expr) glang.CallExpr {
callArgs := append([]ast.Expr{f.X}, args...)
switch f.Sel.Name {
case "ResolveBool", "ResolveU64":
return ctx.newCoqCall(glang.GallinaIdent("ResolveProph"), callArgs)
default:
ctx.unsupported(f, "method %s of machine.ProphId", f.Sel.Name)
return glang.CallExpr{}
}
}
func (ctx Ctx) packageMethod(f *ast.SelectorExpr,
call *ast.CallExpr) glang.Expr {
args := call.Args
pkg := f.X.(*ast.Ident)
return ctx.newCoqCall(glang.PackageIdent{Package: pkg.Name, Ident: f.Sel.Name}, args)
}
func (ctx Ctx) newCoqCall(method glang.Expr, es []ast.Expr) glang.CallExpr {
var args []glang.Expr
for _, e := range es {
args = append(args, ctx.expr(e))
}
call := glang.NewCallExpr(method, args...)
return call
}
func (ctx Ctx) methodExpr(call *ast.CallExpr) glang.Expr {
if f, ok := call.Fun.(*ast.Ident); ok {
if ctx.info.Instances[f].TypeArgs.Len() > 0 {
ctx.unsupported(f, "generic function")
}
}
return ctx.newCoqCall(ctx.expr(call.Fun), call.Args)
}
func (ctx Ctx) makeSliceExpr(elt glang.Type, args []ast.Expr) glang.CallExpr {
if len(args) == 2 {
return glang.NewCallExpr(glang.GallinaIdent("slice.make2"), elt, ctx.expr(args[1]))
} else if len(args) == 3 {
return glang.NewCallExpr(glang.GallinaIdent("slice.make3"), elt, ctx.expr(args[1]), ctx.expr(args[2]))
} else {
ctx.unsupported(args[0], "Too many or too few arguments in slice construction")
return glang.CallExpr{}
}
}
// makeExpr parses a call to make() into the appropriate data-structure Call
func (ctx Ctx) makeExpr(args []ast.Expr) glang.Expr {
switch ty := ctx.typeOf(args[0]).Underlying().(type) {
case *types.Slice:
elt := ctx.glangType(args[0], ty.Elem())
if len(args) == 2 {
return glang.NewCallExpr(glang.GallinaIdent("slice.make2"), elt, ctx.expr(args[1]))
} else if len(args) == 3 {
return glang.NewCallExpr(glang.GallinaIdent("slice.make3"), elt, ctx.expr(args[1]), ctx.expr(args[2]))
} else {
ctx.nope(args[0], "Too many or too few arguments in slice construction")
return glang.CallExpr{}
}
case *types.Map:
return glang.NewCallExpr(glang.GallinaIdent("map.make"),
ctx.glangType(args[0], ty.Key()),
ctx.glangType(args[0], ty.Elem()),
glang.UnitLiteral{})
default:
ctx.unsupported(args[0],
"make of should be slice or map, got %v", ty)
}
return glang.CallExpr{}
}
// newExpr parses a call to new() into an appropriate allocation
func (ctx Ctx) newExpr(ty ast.Expr) glang.Expr {
return glang.RefExpr{
X: glang.NewCallExpr(glang.GallinaIdent("zero_val"), ctx.glangTypeFromExpr(ty)),
Ty: ctx.glangTypeFromExpr(ty),
}
}
// 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) glang.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 glang.NewCallExpr(glang.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) glang.Expr {
e := sliceElem(ctx.typeOf(dst))
return glang.NewCallExpr(glang.GallinaIdent("slice.copy"),
ctx.glangType(n, e),
ctx.expr(dst), ctx.expr(src))
}
func (ctx Ctx) conversionExpr(s *ast.CallExpr) glang.Expr {
if len(s.Args) != 1 {
ctx.nope(s, "expect exactly one argument in a conversion")
}
toType := ctx.info.TypeOf(s.Fun).Underlying()
fromType := ctx.info.TypeOf(s.Args[0]).Underlying()
if toType == fromType {
return ctx.expr(s.Args[0])
}
switch toType := toType.(type) {
case *types.Basic:
// handle conversions between integer types
if fromType, ok := fromType.(*types.Basic); ok {
if (fromType.Info()&types.IsInteger) != 0 &&
toType.Info()&types.IsInteger == 0 {
ctx.unsupported(s, "converting from integer type to non-integer type")
}
switch toType.Kind() {
case types.Uint64:
return ctx.integerConversion(s, s.Args[0], 64)
case types.Uint32:
return ctx.integerConversion(s, s.Args[0], 32)
case types.Uint8:
return ctx.integerConversion(s, s.Args[0], 8)
}
}
// handle `string(b)`, where b : []byte
if toType.Kind() == types.String && isByteSlice(fromType) {
return ctx.newCoqCall(glang.GallinaIdent("StringFromBytes"), s.Args)
}
case *types.Slice:
// handle `[]byte(s)`, where s : string
if eltType, ok := toType.Elem().Underlying().(*types.Basic); ok &&
eltType.Kind() == types.Byte && isString(fromType) {
return ctx.newCoqCall(glang.GallinaIdent("StringToBytes"), s.Args)
}
}
ctx.unsupported(s, "conversion from %s to %s", fromType, toType)
return nil
}
func (ctx Ctx) builtinCallExpr(s *ast.CallExpr) glang.Expr {
funName := s.Fun.(*ast.Ident).Name
switch funName {
case "make":
return ctx.makeExpr(s.Args)
case "new":
return ctx.newExpr(s.Args[0])
case "len":
return ctx.lenExpr(s)
case "cap":
return ctx.capExpr(s)
case "append":
elemTy := sliceElem(ctx.typeOf(s.Args[0]))
var xExpr glang.Expr = glang.GallinaIdent("slice.nil")
// append(s, x1, x2, xn)
if s.Ellipsis == token.NoPos {
if len(s.Args) > 0 {
var exprs []glang.Expr
for _, arg := range s.Args[1:] {
exprs = append(exprs, ctx.expr(arg))
}
xExpr = glang.NewCallExpr(glang.GallinaIdent("slice.literal"),
// FIXME: get the type of the vararg
ctx.glangType(s.Args[1], ctx.typeOf(s.Args[1])),
glang.ListExpr(exprs))
}
} else {
// append(s1, s2...)
xExpr = ctx.expr(s.Args[1])
}
return glang.NewCallExpr(glang.GallinaIdent("slice.append"),
ctx.glangType(s, elemTy),
ctx.expr(s.Args[0]),
xExpr,
)
case "copy":
return ctx.copyExpr(s, s.Args[0], s.Args[1])
case "delete":
if _, ok := ctx.typeOf(s.Args[0]).(*types.Map); !ok {
ctx.nope(s, "delete on non-map")
}
return glang.NewCallExpr(glang.GallinaIdent("MapDelete"), ctx.expr(s.Args[0]), ctx.expr(s.Args[1]))
case "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 glang.NewCallExpr(glang.GallinaIdent("Panic"), glang.GallinaString(msg))
default:
ctx.unsupported(s, "builtin %s not supported", funName)
return nil
}
}
func (ctx Ctx) callExpr(s *ast.CallExpr) glang.Expr {
if ctx.info.Types[s.Fun].IsType() {
return ctx.conversionExpr(s)
} else if ctx.info.Types[s.Fun].IsBuiltin() {
return ctx.builtinCallExpr(s)
} else {
return ctx.methodExpr(s)
}
}
func (ctx Ctx) qualifiedName(obj types.Object) string {
name := obj.Name()
if obj.Pkg() == nil {
return name
} else if ctx.pkgPath == obj.Pkg().Path() {
// no module name needed
return name
}
return fmt.Sprintf("%s.%s", obj.Pkg().Name(), name)
}
func (ctx Ctx) selectorExpr(e *ast.SelectorExpr) glang.Expr {
selectorType, ok := ctx.getType(e.X)
if !ok {
if isIdent(e.X, "filesys") {
return glang.GallinaIdent("FS." + e.Sel.Name)
}
if isIdent(e.X, "disk") {
return glang.GallinaIdent("disk." + e.Sel.Name)
}
if pkg, ok := getIdent(e.X); ok {
return glang.PackageIdent{
Package: pkg,
Ident: e.Sel.Name,
}
}
}
structInfo, ok := ctx.getStructInfo(selectorType)
if ok {
// Check if select expression refers to a field of the struct
isField := false
for i := 0; i < structInfo.structType.NumFields(); i++ {
if structInfo.structType.Field(i).Name() == e.Sel.Name {
isField = true
break
}
}
if isField {
return glang.DerefExpr{
X: ctx.exprAddr(e),
Ty: ctx.glangType(e, ctx.typeOf(e)),
}
}
}
// must be method
m := glang.TypeMethod(structInfo.name, e.Sel.Name)
ctx.dep.addDep(m)
return glang.NewCallExpr(glang.GallinaIdent(m), ctx.expr(e.X))
}
func (ctx Ctx) compositeLiteral(e *ast.CompositeLit) glang.Expr {
if t, ok := ctx.typeOf(e).Underlying().(*types.Slice); ok {
var args glang.ListExpr
for _, e := range e.Elts {
args = append(args, ctx.expr(e))
}
return glang.NewCallExpr(glang.GallinaIdent("slice.literal"),
ctx.glangType(e, t.Elem()),
args)
}
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) glang.StructLiteral {
ctx.dep.addDep(info.name)
lit := glang.NewStructLiteral(info.name)
isUnkeyedStruct := false
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 glang.StructLiteral{}
}
lit.AddField(ident, ctx.expr(el.Value))
default:
isUnkeyedStruct = true
}
}
if isUnkeyedStruct {
if len(e.Elts) != info.structType.NumFields() {
ctx.nope(e, "expected as many elements are there are struct fields in unkeyed literal")
}
for i := range info.structType.NumFields() {
lit.AddField(info.structType.Field(i).Name(), ctx.expr(e.Elts[i]))
}
}
return lit
}
// basicLiteral translates a basic literal
//
// (unsigned) ints, strings, and booleans are supported
func (ctx Ctx) basicLiteral(e *ast.BasicLit) glang.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 glang.StringLiteral{Value: s}
}
if e.Kind == token.INT {
tv := ctx.info.Types[e]
switch t := tv.Type.Underlying().(type) {
case *types.Basic:
switch t.Name() {
case "uint64":
n, ok := constant.Uint64Val(tv.Value)
if !ok {
ctx.nope(e, "uint64 literal with failed constant.Uint64Val")
}
return glang.IntLiteral{Value: n}
case "uint32":
n, ok := constant.Uint64Val(tv.Value)
if !ok {
ctx.nope(e, "uint32 literal with failed constant.Uint64Val")
}
return glang.Int32Literal{Value: uint32(n)}
case "uint8":
fallthrough
case "byte":
n, ok := constant.Uint64Val(tv.Value)
if !ok {
ctx.nope(e, "uint8 literal with failed constant.Uint64Val")
}
return glang.ByteLiteral{Value: uint8(n)}
case "int": // FIXME: this case is a temporary hack to support e.g. the int in `make([]byte, 20)`
n, ok := constant.Uint64Val(tv.Value)
if !ok {
ctx.todo(e, "int literal with negative value")
}
return glang.IntLiteral{Value: n}
case "untyped int": // FIXME: this case is a temporary hack to support e.g. the int in `make([]byte, 20)`
n, ok := constant.Uint64Val(tv.Value)
if !ok {
ctx.todo(e, "int literal with negative value")
}
return glang.IntLiteral{Value: n}
default:
ctx.todo(e, "%s integer literal", t.Name())
return glang.Tt
}
}
ctx.nope(e, "integer literal with unexpected underlying type that's %T", tv.Type.Underlying())
}
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) glang.Expr {
op, ok := map[token.Token]glang.BinOp{
token.LSS: glang.OpLessThan,
token.GTR: glang.OpGreaterThan,
token.SUB: glang.OpMinus,
token.EQL: glang.OpEquals,
token.NEQ: glang.OpNotEquals,
token.MUL: glang.OpMul,
token.QUO: glang.OpQuot,
token.REM: glang.OpRem,
token.LEQ: glang.OpLessEq,
token.GEQ: glang.OpGreaterEq,
token.AND: glang.OpAnd,
token.LAND: glang.OpLAnd,
token.OR: glang.OpOr,
token.LOR: glang.OpLOr,
token.XOR: glang.OpXor,
token.SHL: glang.OpShl,
token.SHR: glang.OpShr,
}[e.Op]
if e.Op == token.ADD {
if isString(ctx.typeOf(e.X)) {
op = glang.OpAppend
} else {
op = glang.OpPlus
}
ok = true
}
if ok {
expr := glang.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 = glang.Null
}
}
return expr
}
ctx.unsupported(e, "binary operator %v", e.Op)
return nil
}
func (ctx Ctx) sliceExpr(e *ast.SliceExpr) glang.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
}
if e.Low == nil && e.High == nil {
ctx.unsupported(e, "complete slice doesn't do anything")
}
x := ctx.expr(e.X)
var lowExpr glang.Expr = glang.IntLiteral{Value: 0}
var highExpr glang.Expr = glang.NewCallExpr(glang.GallinaIdent("slice.len"), glang.IdentExpr("$s"))
if e.Low != nil {
lowExpr = ctx.expr(e.Low)
}
if e.High != nil {
highExpr = ctx.expr(e.High)
}
return glang.LetExpr{
Names: []string{"$s"},
ValExpr: x,
Cont: glang.NewCallExpr(glang.GallinaIdent("slice.slice"),
ctx.glangType(e, sliceElem(ctx.typeOf(e.X))),
glang.IdentExpr("$s"), lowExpr, highExpr),
}
}
func (ctx Ctx) nilExpr(e *ast.Ident) glang.Expr {
t := ctx.typeOf(e)
switch t.(type) {
case *types.Pointer:
return glang.GallinaIdent("null")
case *types.Slice:
return glang.GallinaIdent("slice.nil")
case *types.Basic:
// TODO: this gets triggered for all of our unit tests because the
// nil identifier is mapped to an untyped nil object.
// This seems wrong; the runtime representation of each of these
// uses depends on the type, so Go must know how they're being used.
return glang.GallinaIdent("slice.nil")
default:
ctx.unsupported(e, "nil of type %v (not pointer or slice)", t)
return nil
}
}
func (ctx Ctx) unaryExpr(e *ast.UnaryExpr) glang.Expr {
if e.Op == token.NOT {
return glang.NotExpr{X: ctx.expr(e.X)}
}
if e.Op == token.XOR {
return glang.NotExpr{X: ctx.expr(e.X)}
}
if e.Op == token.AND {
if x, ok := e.X.(*ast.IndexExpr); ok {
// e is &a[b] where x is a.b
if xTy, ok := ctx.typeOf(x.X).(*types.Slice); ok {
return glang.NewCallExpr(glang.GallinaIdent("SliceRef"),
ctx.glangType(e, xTy.Elem()),
ctx.expr(x.X), ctx.expr(x.Index))
}
}
if info, ok := ctx.getStructInfo(ctx.typeOf(e.X)); ok {
structLit, ok := e.X.(*ast.CompositeLit)
if ok {
// e is &s{...} (a struct literal)
sl := ctx.structLiteral(info, structLit)
return glang.RefExpr{
X: sl,
Ty: ctx.glangType(e.X, ctx.typeOf(e.X)),
}
}
}
// e is something else
return ctx.exprAddr(e.X)
}
ctx.unsupported(e, "unary expression %s", e.Op)
return nil
}
func (ctx Ctx) variable(s *ast.Ident) glang.Expr {
if _, ok := ctx.info.Uses[s].(*types.Const); ok {
ctx.dep.addDep(s.Name)
return glang.GallinaIdent(s.Name)
}
return glang.DerefExpr{X: glang.IdentExpr(s.Name), Ty: ctx.glangType(s, ctx.typeOf(s))}
}
func (ctx Ctx) function(s *ast.Ident) glang.Expr {
ctx.dep.addDep(s.Name)
return glang.GallinaIdent(s.Name)
}
func (ctx Ctx) goBuiltin(e *ast.Ident) bool {
s, ok := ctx.info.Uses[e]
if !ok {
return false
}
return s.Parent() == types.Universe
}
func (ctx Ctx) identExpr(e *ast.Ident) glang.Expr {
if ctx.goBuiltin(e) {
switch e.Name {
case "nil":
return ctx.nilExpr(e)
case "true":
return glang.True
case "false":
return glang.False
}
ctx.unsupported(e, "special identifier")
}
// check if e refers to a variable,
obj := ctx.info.ObjectOf(e)
if _, ok := obj.(*types.Const); ok {
// is a variable
return ctx.variable(e)
}
if _, ok := obj.(*types.Var); ok {
// is a variable
return ctx.variable(e)
}
if _, ok := obj.(*types.Func); ok {
// is a function
return ctx.function(e)
}
ctx.unsupported(e, "unrecognized kind of identifier; not local variable or global function")
panic("")
}
func (ctx Ctx) indexExpr(e *ast.IndexExpr, isSpecial bool) glang.Expr {
xTy := ctx.typeOf(e.X).Underlying()
switch xTy.(type) {
case *types.Map:
e := glang.NewCallExpr(glang.GallinaIdent("map.get"),
ctx.expr(e.X),
ctx.expr(e.Index))
// FIXME: this is non-local. Should decide whether to do "Fst" based on
// assign statement or parent expression.
if !isSpecial {
e = glang.NewCallExpr(glang.GallinaIdent("Fst"), e)
}
return e
case *types.Slice:
return glang.DerefExpr{
X: ctx.exprAddr(e),
Ty: ctx.glangType(e, ctx.typeOf(e)),
}
case *types.Signature:
ctx.unsupported(e, "generic function %v", xTy)
}
ctx.unsupported(e, "index into unknown type %v", xTy)
return glang.CallExpr{}
}
func (ctx Ctx) derefExpr(e ast.Expr) glang.Expr {
return glang.DerefExpr{
X: ctx.expr(e),
Ty: ctx.glangType(e, ptrElem(ctx.typeOf(e))),
}
}
func (ctx Ctx) expr(e ast.Expr) glang.Expr {
return ctx.exprSpecial(e, false)
}
func (ctx Ctx) funcLit(e *ast.FuncLit) glang.FuncLit {
fl := glang.FuncLit{}
fl.Args = ctx.paramList(e.Type.Params)
// fl.ReturnType = ctx.returnType(d.Type.Results)
fl.Body = ctx.blockStmt(e.Body)
return fl
}
func (ctx Ctx) exprSpecial(e ast.Expr, isSpecial bool) glang.Expr {
switch e := e.(type) {
case *ast.CallExpr:
return ctx.callExpr(e)
case *ast.Ident:
return ctx.identExpr(e)
case *ast.SelectorExpr:
return ctx.selectorExpr(e)
case *ast.CompositeLit:
return ctx.compositeLiteral(e)
case *ast.BasicLit:
return ctx.basicLiteral(e)
case *ast.BinaryExpr:
return ctx.binExpr(e)
case *ast.SliceExpr:
return ctx.sliceExpr(e)
case *ast.IndexExpr:
return ctx.indexExpr(e, isSpecial)
case *ast.UnaryExpr:
return ctx.unaryExpr(e)
case *ast.ParenExpr:
return ctx.expr(e.X)
case *ast.StarExpr:
return ctx.derefExpr(e.X)
case *ast.TypeAssertExpr:
// TODO: do something with the type
return ctx.expr(e.X)
case *ast.FuncLit:
return ctx.funcLit(e)
default:
ctx.unsupported(e, "unexpected expr")
}
return nil
}
func (ctx Ctx) blockStmt(s *ast.BlockStmt) glang.Expr {
ss := s.List
var e glang.Expr = glang.DoExpr{Expr: glang.Tt}
for len(ss) > 0 {
stmt := ss[len(ss)-1]
ss = ss[:len(ss)-1]
e = ctx.stmt(stmt, e)
}
return e
}
func (ctx Ctx) ifStmt(s *ast.IfStmt, cont glang.Expr) glang.Expr {
var elseExpr glang.Expr = glang.DoExpr{Expr: glang.Tt}
if s.Else != nil {
elseExpr = ctx.stmt(s.Else, glang.Tt)
}
ife := glang.IfExpr{
Cond: ctx.expr(s.Cond),
Then: ctx.blockStmt(s.Body),
Else: elseExpr,
}
if s.Init != nil {
ctx.unsupported(s.Init, "if statement initializations")
}
return glang.LetExpr{ValExpr: ife, Cont: cont}
}
func (ctx Ctx) loopVar(s ast.Stmt) (ident *ast.Ident, init glang.Expr) {
initAssign, ok := s.(*ast.AssignStmt)
if !ok ||
len(initAssign.Lhs) > 1 ||
len(initAssign.Rhs) > 1 ||
initAssign.Tok != token.DEFINE {
ctx.unsupported(s, "loop initialization must be a single assignment")
return nil, nil
}
lhs, ok := initAssign.Lhs[0].(*ast.Ident)
if !ok {
ctx.nope(s, "initialization must define an identifier")
}
rhs := initAssign.Rhs[0]
return lhs, ctx.expr(rhs)
}
func (ctx Ctx) forStmt(s *ast.ForStmt, cont glang.Expr) glang.Expr {
var cond glang.Expr = glang.True
if s.Cond != nil {
cond = ctx.expr(s.Cond)
}
var post glang.Expr = glang.Skip
if s.Post != nil {
post = ctx.stmt(s.Post, glang.Tt)
}
body := ctx.blockStmt(s.Body)
var e glang.Expr = glang.ForLoopExpr{
Cond: cond,
Post: post,
Body: body,
}
if s.Init != nil {
e = glang.ParenExpr{Inner: ctx.stmt(s.Init, e)}
}
return glang.LetExpr{ValExpr: e, Cont: cont}
}
func getIdentOrAnonymous(e ast.Expr) (ident string, ok bool) {
if e == nil {
return "_", true
}
return getIdent(e)
}
func (ctx Ctx) mapRangeStmt(s *ast.RangeStmt) glang.Expr {