~mna/snow unlisted

snow/pkg/codegen/translate.go -rw-r--r-- 26.1 KiB
424066c5Martin Angers doc: v0.0.5 1 year, 7 months ago
                                                                                
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
package codegen

import (
	"container/list"
	"fmt"
	goast "go/ast"
	gotoken "go/token"
	"path/filepath"
	"strconv"

	"git.sr.ht/~mna/snow/pkg/semantic"
	"git.sr.ht/~mna/snow/pkg/token"
)

// The translator translates a Snow abstract semantic graph to a Go abstract
// syntax tree that can then be written to file.
type translator struct {
	// resolver of mangled names for declarations and other nodes (provided as input)
	resolver *nameResolver
	// list of external imports per file (provided as input)
	fileImports map[*semantic.File][]_import
	// list of external import per function (provided as input)
	fnImports map[*semantic.Fn]_import

	// current file being processed in the Unit
	curFile *semantic.File
	// map of already generated conversion functions (value is the associated mangled name)
	convertFns map[convertFnKey]string
	// map of active replacement types for generic placeholder types
	curGenInst map[*semantic.GenericType]semantic.Type
	// set of already rendered generic instantiations, based on the mangled name
	renderedGenInsts map[string]bool

	// expressions are generated and returned to the parent node
	generatedExpr goast.Expr

	filesList *list.List
	// the following two lists represent the current topLevel list of nodes (the file),
	// and the current container list.
	topLevel        *list.List
	parentContainer *list.List
	// map associating placeholder marks in their container where generic
	// instantiations should be inserted. The associated Element is a container
	// with no associated Go nodes.
	genDeclMarks map[semantic.Decl]*mark
}

type convertFnKey struct {
	from, to semantic.Type
}

type mark struct {
	list *list.List
	elem *list.Element
}

// file, block, if, guard, struct and fn are containers
type container struct {
	snode    semantic.Node
	nodes    []goast.Node
	children *list.List
}

func newContainer(snode semantic.Node, ns ...goast.Node) *container {
	return &container{
		snode:    snode,
		nodes:    ns,
		children: list.New(),
	}
}

func (t *translator) withContainer(c *container, fn func()) {
	old := t.parentContainer
	t.parentContainer = c.children
	defer func() { t.parentContainer = old }()
	fn()
}

// TODO: do a with genInst like withContainer for this?
// merges the new generic instantiation replacement types into a cloned lookup map,
// sets it as the current replacement lookup map and returns the previous map, that
// should be set back in place once done with this generic instantiation.
func (t *translator) cloneGenInst(clause *semantic.GenericClause, types []semantic.Type) map[*semantic.GenericType]semantic.Type {
	old := t.curGenInst
	new := make(map[*semantic.GenericType]semantic.Type, len(types))
	for k, v := range old {
		new[k] = v
	}
	for i, gt := range clause.Elems {
		newt := types[i]
		new[semantic.AsGenericType(gt.Type())] = newt
	}
	t.curGenInst = new
	return old
}

func (t *translator) Visit(n semantic.Node) semantic.Visitor {
	switch n := n.(type) {
	case *semantic.Unit:
		t.convertFns = make(map[convertFnKey]string)
		t.renderedGenInsts = make(map[string]bool)
		t.genDeclMarks = make(map[semantic.Decl]*mark)
		t.filesList = list.New()
		for _, f := range n.Files {
			t.curFile = f
			semantic.Walk(t, f)
		}

	case *semantic.File:
		// create package clause, imports if any
		gof := &goast.File{Name: &goast.Ident{Name: "main"}}
		t.addFileImports(n, gof)
		cont := newContainer(n, gof)
		t.filesList.PushBack(cont)
		t.topLevel = cont.children

		t.withContainer(cont, func() {
			for _, v := range n.Vars {
				semantic.Walk(t, v)
			}
			for _, str := range n.Structs {
				semantic.Walk(t, str)
			}
			for _, fn := range n.Fns {
				semantic.Walk(t, fn)
			}
			for _, iface := range n.Interfaces {
				semantic.Walk(t, iface)
			}
		})

		// ************** DECLARATIONS *****************

	case *semantic.Fn:
		if n.IsGeneric() {
			// go nodes will be generated only on instantiation, create an empty container for now
			var m *mark
			if n.Scope().IsTopLevel() || n.MethodOf != nil {
				m = &mark{list: t.topLevel, elem: t.topLevel.PushBack(newContainer(n))}
			} else {
				m = &mark{list: t.parentContainer, elem: t.parentContainer.PushBack(newContainer(n))}
			}
			t.genDeclMarks[n] = m
			break
		}
		name := t.resolver.NameForDecl(n)
		t.createFn(name, n)

	case *semantic.Struct:
		if n.IsGeneric() {
			// go nodes will be generated only on instantiation, create an empty container for now
			m := &mark{list: t.topLevel, elem: t.topLevel.PushBack(newContainer(n))}
			t.genDeclMarks[n] = m
			break
		}
		name := t.resolver.NameForDecl(n)
		t.createStruct(name, semantic.AsStructType(n.Type()))

	case *semantic.Var:
		name := t.resolver.NameForDecl(n)
		vs := &goast.ValueSpec{
			Names: []*goast.Ident{{Name: name}},
			Type:  t.goTypeExprFor(n.Type()),
		}
		if n.Value != nil {
			semantic.Walk(t, n.Value)
			expr := t.generatedExpr
			vs.Values = []goast.Expr{expr}
		}
		t.parentContainer.PushBack(&goast.GenDecl{
			Tok:   gotoken.VAR,
			Specs: []goast.Spec{vs},
		})

	case *semantic.Interface:
		if n.IsGeneric() {
			// go nodes will be generated only on instantiation, create an empty container for now
			m := &mark{list: t.topLevel, elem: t.topLevel.PushBack(newContainer(n))}
			t.genDeclMarks[n] = m
			break
		}
		name := t.resolver.NameForDecl(n)
		t.createInterface(name, semantic.AsInterfaceType(n.Type()))

		// ************** STATEMENTS *****************

	case *semantic.Block:
		bs := &goast.BlockStmt{
			List: make([]goast.Stmt, 0, len(n.Stmts)),
		}
		cont := newContainer(n, bs)
		t.parentContainer.PushBack(cont)
		t.withContainer(cont, func() {
			for _, stmt := range n.Stmts {
				semantic.Walk(t, stmt)
			}
		})

	case *semantic.Return:
		rs := &goast.ReturnStmt{}
		if n.Value != nil {
			semantic.Walk(t, n.Value)
			rs.Results = []goast.Expr{t.generatedExpr}
		}
		t.parentContainer.PushBack(rs)

	case *semantic.Assign:
		semantic.Walk(t, n.Left)
		as := &goast.AssignStmt{
			Lhs: []goast.Expr{t.generatedExpr},
			Tok: tokenToGoToken[token.Assign],
		}
		semantic.Walk(t, n.Right)
		as.Rhs = []goast.Expr{t.generatedExpr}
		t.parentContainer.PushBack(as)

	case *semantic.ExprStmt:
		semantic.Walk(t, n.Value)
		t.parentContainer.PushBack(&goast.ExprStmt{X: t.generatedExpr})

	case *semantic.If:
		is := &goast.IfStmt{}
		for _, cond := range n.Conds {
			semantic.Walk(t, cond)
			if is.Cond == nil {
				is.Cond = t.generatedExpr
				continue
			}
			and := &goast.BinaryExpr{
				X:  is.Cond,
				Op: tokenToGoToken[token.And],
				Y:  t.generatedExpr,
			}
			is.Cond = and
		}

		cont := newContainer(n, is)
		t.parentContainer.PushBack(cont)
		t.withContainer(cont, func() {
			semantic.Walk(t, n.Body)
			if n.Else != nil {
				semantic.Walk(t, n.Else)
			}
		})

	case *semantic.Guard:
		// use an empty if and an else
		is := &goast.IfStmt{}
		for _, cond := range n.Conds {
			semantic.Walk(t, cond)
			if is.Cond == nil {
				is.Cond = t.generatedExpr
				continue
			}
			and := &goast.BinaryExpr{
				X:  is.Cond,
				Op: tokenToGoToken[token.And],
				Y:  t.generatedExpr,
			}
			is.Cond = and
		}

		// empty "if" body
		is.Body = &goast.BlockStmt{}
		cont := newContainer(n, is)
		t.parentContainer.PushBack(cont)
		t.withContainer(cont, func() {
			semantic.Walk(t, n.Else)
		})

		// ************** EXPRESSIONS *****************

	case *semantic.FnTypeExpr:
		t.generatedExpr = t.goTypeExprFor(n.Type())

	case *semantic.TupleTypeExpr:
		t.generatedExpr = t.goTypeExprFor(n.Type())

	case *semantic.TupleVal:
		cl := &goast.CompositeLit{
			Type: t.goTypeExprFor(n.Type()),
			Elts: make([]goast.Expr, len(n.Values)),
		}
		for i, val := range n.Values {
			semantic.Walk(t, val)
			cl.Elts[i] = t.generatedExpr
		}
		t.generatedExpr = cl

	case *semantic.Binary:
		semantic.Walk(t, n.Left)
		be := &goast.BinaryExpr{
			X:  t.generatedExpr,
			Op: tokenToGoToken[n.Op],
		}
		semantic.Walk(t, n.Right)
		be.Y = t.generatedExpr
		t.generatedExpr = be

	case *semantic.Unary:
		semantic.Walk(t, n.Right)
		t.generatedExpr = &goast.UnaryExpr{
			Op: tokenToGoToken[n.Op],
			X:  t.generatedExpr,
		}

	case *semantic.Paren:
		semantic.Walk(t, n.Value)
		t.generatedExpr = &goast.ParenExpr{X: t.generatedExpr}

	case *semantic.Call:
		semantic.Walk(t, n.Fun)

		if n.InitOf != nil {
			t.generatedExpr = t.callStructInit(n)
			break
			// TODO: once modules exist, the n.Fun might be a qualified struct type, and the initializer
			// might be in a different module, will need to address that...
		}

		ce := &goast.CallExpr{
			Fun:  t.generatedExpr,
			Args: make([]goast.Expr, len(n.Args)),
		}
		for i, arg := range n.Args {
			semantic.Walk(t, arg)
			ce.Args[i] = t.generatedExpr
		}
		t.generatedExpr = ce

	case *semantic.Selector:
		semantic.Walk(t, n.Left)
		left := t.generatedExpr
		semantic.Walk(t, n.Sel)
		sel := t.generatedExpr

		if n.TypeContext() == semantic.Typ {
			// if this is a nested type, use just the type of Sel, as it is hoisted to the
			// top-level in Go and mangled.
			t.generatedExpr = sel
			break
		}

		// n.Sel might have generated a "self.right" selector expression, just take
		// the right part for this case as it's already on the right side, makes no
		// sense to have "self.".
		var rident *goast.Ident
		switch gen := sel.(type) {
		case *goast.SelectorExpr:
			rident = gen.Sel
		case *goast.Ident:
			rident = gen
		}
		t.generatedExpr = &goast.SelectorExpr{
			X:   left,
			Sel: rident,
		}

	case *semantic.LitString:
		t.generatedExpr = &goast.BasicLit{
			Kind:  tokenToGoToken[token.String],
			Value: n.Repr,
		}

	case *semantic.LitInt:
		t.generatedExpr = &goast.BasicLit{
			Kind:  tokenToGoToken[token.Int],
			Value: n.Repr,
		}

	case *semantic.GenericInst:
		// render this generic instantiation if not already rendered
		name := t.resolver.NameForGenericInst(n, t.curGenInst)
		t.renderGenInst(n, name)
		t.generatedExpr = &goast.Ident{Name: name}

	case *semantic.Ident:
		if n.Index >= 0 {
			t.generatedExpr = &goast.Ident{Name: t.resolver.NameForTuple(n.Index, false)}
			break
		}

		name := t.resolver.NameForDecl(n.Ref)
		expr := goast.Expr(&goast.Ident{Name: name})
		if v := semantic.AsVarDecl(n.Ref); v != nil && v.PropOf != nil {
			// this is a property, turn the AST into a selector on "self"
			expr = &goast.SelectorExpr{
				X:   &goast.Ident{Name: semantic.SelfVarName},
				Sel: expr.(*goast.Ident),
			}
		} else if f := semantic.AsFnDecl(n.Ref); f != nil && f.MethodOf != nil {
			// this is a method, turn the AST into a selector on "self"
			expr = &goast.SelectorExpr{
				X:   &goast.Ident{Name: semantic.SelfVarName},
				Sel: expr.(*goast.Ident),
			}
		}
		t.generatedExpr = expr

	case *semantic.ImplicitConv:
		semantic.Walk(t, n.Value)
		t.generatedExpr = t.reconcileExprWith(n.Type(), n.Value.Type(), t.generatedExpr)

	default:
		panic(fmt.Sprintf("invalid node type: %T", n))
	}
	return nil
}

func (t *translator) createFn(nm string, fn *semantic.Fn) {
	ft := t.goTypeExprFor(fn.Type()).(*goast.FuncType)
	// function type has no name for parameters, add them in
	for i, p := range ft.Params.List {
		nm := t.resolver.NameForDecl(fn.Params[i])
		p.Names = []*goast.Ident{{Name: nm}}
	}

	// create the container but don't set its Go nodes yet, we don't know
	// if it will be a func literal or declaration.
	cont := &container{snode: fn, children: list.New()}

	var body *goast.BlockStmt
	t.withContainer(cont, func() {
		if fn.Body != nil {
			semantic.Walk(t, fn.Body)
		} else if fn.AbstractMethodOf == nil {
			// this is an external function
			body = createExternalFnBody(ft, t.fnImports[fn])
		}
	})

	// the function declaration is a top-level func statement if it is top-level
	// in snow or is a struct method.
	fd := &goast.FuncDecl{
		Name: &goast.Ident{Name: nm},
		Type: ft,
		Body: body,
	}
	if fn.Scope().IsTopLevel() || fn.MethodOf != nil {
		if str := fn.MethodOf; str != nil {
			t.convertFuncToMethod(fd, str, fn.IsRef)
		}

		cont.nodes = []goast.Node{fd}
		if mark := t.genDeclMarks[fn]; mark != nil {
			mark.list.InsertBefore(cont, mark.elem)
		} else {
			t.topLevel.PushBack(cont)
		}
		return

	}
	if fn.AbstractMethodOf != nil {
		// if it is an interface method, create the function declaration inside the
		// interface's container. It cannot be a generic itself (only the interface can).
		cont.nodes = []goast.Node{fd}
		t.parentContainer.PushBack(cont)
		return
	}

	cont.nodes = createFuncLit(nm, ft, body)
	if mark := t.genDeclMarks[fn]; mark != nil {
		mark.list.InsertBefore(cont, mark.elem)
	} else {
		t.parentContainer.PushBack(cont)
	}
}

func (t *translator) convertFuncToMethod(fn *goast.FuncDecl, str *semantic.Struct, isRef bool) {
	typ := t.goTypeExprFor(str.Type())
	if isRef {
		typ = &goast.StarExpr{X: typ}
	}
	fn.Recv = &goast.FieldList{
		List: []*goast.Field{{
			Names: []*goast.Ident{{Name: semantic.SelfVarName}},
			Type:  typ,
		}},
	}
}

func (t *translator) createStruct(nm string, strTyp *semantic.StructType) {
	// all struct declarations are attached to the top-level scope of the file.
	fields := &goast.FieldList{List: make([]*goast.Field, len(strTyp.Decl.Vars))}

	// create the container but don't set its Go node yet, it will be created
	// only after looping over the vars.
	cont := &container{snode: strTyp.Decl, children: list.New()}

	// keep a map of field values, will be used to generate the struct
	// initializer
	propInit := make(map[*semantic.Var][]goast.Expr)
	t.withContainer(cont, func() {
		for i, prop := range strTyp.Decl.Vars {
			semantic.Walk(t, prop)
			node := t.parentContainer.Back().Value
			vs := node.(*goast.GenDecl).Specs[0].(*goast.ValueSpec)
			fields.List[i] = &goast.Field{
				Names: vs.Names,
				Type:  vs.Type,
			}
			if prop.Value != nil {
				propInit[prop] = vs.Values
			}
		}
	})

	decl := &goast.GenDecl{
		Tok: gotoken.TYPE,
		Specs: []goast.Spec{
			&goast.TypeSpec{Name: &goast.Ident{Name: nm}, Type: &goast.StructType{Fields: fields}},
		},
	}
	cont.nodes = []goast.Node{decl}
	if mark := t.genDeclMarks[strTyp.Decl]; mark != nil {
		mark.list.InsertBefore(cont, mark.elem)
	} else {
		t.topLevel.PushBack(cont)
	}

	// generate struct initializer function
	strInit := t.createStructInit(nm, strTyp, propInit)

	// generate methods and nested structs and interfaces
	for _, meth := range strTyp.Decl.Fns {
		semantic.Walk(t, meth)
	}
	for _, str := range strTyp.Decl.Structs {
		semantic.Walk(t, str)
	}
	for _, iface := range strTyp.Decl.Interfaces {
		semantic.Walk(t, iface)
	}

	if mark := t.genDeclMarks[strTyp.Decl]; mark != nil {
		mark.list.InsertBefore(strInit, mark.elem)
	} else {
		t.topLevel.PushBack(strInit)
	}
}

func (t *translator) createInterface(nm string, ifaceTyp *semantic.InterfaceType) {
	// all interface declarations are attached to the top-level scope of the file.
	fields := &goast.FieldList{List: make([]*goast.Field, len(ifaceTyp.Decl.Methods))}

	// create the container but don't set its Go node yet, it will be created
	// only after looping over the methods.
	cont := &container{snode: ifaceTyp.Decl, children: list.New()}

	t.withContainer(cont, func() {
		for i, m := range ifaceTyp.Decl.Methods {
			semantic.Walk(t, m)
			node := t.parentContainer.Back().Value
			fnDecl := node.(*container).nodes[0].(*goast.FuncDecl)
			fields.List[i] = &goast.Field{
				Names: []*goast.Ident{fnDecl.Name},
				Type:  fnDecl.Type,
			}
		}
	})

	decl := &goast.GenDecl{
		Tok: gotoken.TYPE,
		Specs: []goast.Spec{
			&goast.TypeSpec{Name: &goast.Ident{Name: nm}, Type: &goast.InterfaceType{Methods: fields}},
		},
	}
	cont.nodes = []goast.Node{decl}
	if mark := t.genDeclMarks[ifaceTyp.Decl]; mark != nil {
		mark.list.InsertBefore(cont, mark.elem)
	} else {
		t.topLevel.PushBack(cont)
	}
}

func (t *translator) addFileImports(f *semantic.File, gof *goast.File) {
	imports := t.fileImports[f]
	set := make(map[string]bool, len(imports))
	for _, imp := range imports {
		if set[imp.Pkg+"\n"+imp.Path] {
			continue
		}
		impSpec := &goast.ImportSpec{
			Path: &goast.BasicLit{
				Kind:  gotoken.STRING,
				Value: strconv.Quote(imp.Path),
			},
		}
		if imp.Pkg != "" {
			impSpec.Name = &goast.Ident{Name: imp.Pkg}
		}
		gof.Imports = append(gof.Imports, impSpec)
		gof.Decls = append(gof.Decls, &goast.GenDecl{Tok: gotoken.IMPORT, Specs: []goast.Spec{impSpec}})
		set[imp.Pkg+"\n"+imp.Path] = true
	}
}

func (t *translator) goTypeExprFor(T semantic.Type) goast.Expr {
	switch T := T.(type) {
	case *semantic.GenericType:
		newt := t.curGenInst[T]
		if newt == nil {
			panic(fmt.Sprintf("no instantiated type replacement for generic type %s", T.Name))
		}
		return t.goTypeExprFor(newt)

	case *semantic.BasicType:
		return &goast.Ident{Name: basicIdentsToGo[T.Kind.String()]}

	case *semantic.SignatureType:
		ft := &goast.FuncType{
			Params: &goast.FieldList{List: make([]*goast.Field, len(T.Params))},
		}
		for i, param := range T.Params {
			ft.Params.List[i] = &goast.Field{Type: t.goTypeExprFor(param)}
		}
		if !semantic.IsBasicOfKind(T.Return, semantic.Void) {
			ft.Results = &goast.FieldList{
				List: []*goast.Field{{Type: t.goTypeExprFor(T.Return)}},
			}
		}
		return ft

	case *semantic.TupleType:
		// tuples are generated as struct literals
		st := &goast.StructType{
			Fields: &goast.FieldList{List: make([]*goast.Field, len(T.Fields))},
		}
		for i, field := range T.Fields {
			st.Fields.List[i] = &goast.Field{
				Names: []*goast.Ident{{Name: t.resolver.NameForTuple(i, false)}},
				Type:  t.goTypeExprFor(field),
			}
		}
		return st

	case *semantic.StructType:
		name := t.resolver.NameForStructType(T, t.curGenInst)
		return &goast.Ident{Name: name}

	case *semantic.InterfaceType:
		name := t.resolver.NameForInterfaceType(T, t.curGenInst)
		return &goast.Ident{Name: name}

	default:
		panic(fmt.Sprintf("invalid type: %T", T))
	}
}

func (t *translator) reconcileExprWith(LT, RT semantic.Type, expr goast.Expr) goast.Expr {
	if !LT.IdenticalTo(RT) {
		return t.convertExprFromTo(expr, RT, LT)
	}
	return expr
}

func (t *translator) convertExprFromTo(expr goast.Expr, fromT, toT semantic.Type) goast.Expr {
	var convertCallExpr goast.Expr

	// if toT is an interface, no explicit conversion needed, Go will be able to assign fromT
	// to it (as the rules for assignability are the same). Only thing is if one of the methods
	// is satisfied by a ref function, the address of expr must be returned instead.
	if semantic.AsInterfaceType(toT) != nil {
		if st := semantic.AsStructType(fromT); st != nil && st.Ctx == semantic.Mutable {
			return &goast.UnaryExpr{Op: gotoken.AND, X: expr}
		}
		return expr
	}

	fromTupT, ok1 := fromT.(*semantic.TupleType)
	toTupT, ok2 := toT.(*semantic.TupleType)
	if ok1 && ok2 {
		// create a conversion function from fromTupT to toTupT and call it
		fnName := t.getOrCreateConvertFn(fromTupT, toTupT)
		convertCallExpr = &goast.Ident{Name: fnName}
	} else {
		convertCallExpr = t.goTypeExprFor(toT)
	}

	return &goast.CallExpr{
		Fun:  convertCallExpr,
		Args: []goast.Expr{expr},
	}
}

func (t *translator) getOrCreateConvertFn(from, to *semantic.TupleType) string {
	key := convertFnKey{from, to}
	if nm := t.convertFns[key]; nm != "" {
		return nm
	}

	fnName := t.resolver.NameForConv(len(t.convertFns))
	t.convertFns[key] = fnName

	fd := &goast.FuncDecl{
		Name: &goast.Ident{Name: fnName},
		Type: &goast.FuncType{
			Params: &goast.FieldList{
				List: []*goast.Field{
					{
						Names: []*goast.Ident{{Name: "from"}},
						Type:  t.goTypeExprFor(from),
					},
				},
			},
			Results: &goast.FieldList{
				List: []*goast.Field{
					{Type: t.goTypeExprFor(to)},
				},
			},
		},
		Body: &goast.BlockStmt{
			List: make([]goast.Stmt, 1),
		},
	}

	cl := &goast.CompositeLit{
		Type: t.goTypeExprFor(to),
		Elts: make([]goast.Expr, len(to.Fields)),
	}
	for i, toTyp := range to.Fields {
		fromTyp := from.Fields[i]
		expr := &goast.SelectorExpr{
			X:   &goast.Ident{Name: "from"},
			Sel: &goast.Ident{Name: t.resolver.NameForTuple(i, false)},
		}
		cl.Elts[i] = t.reconcileExprWith(toTyp, fromTyp, expr)
	}
	ret := &goast.ReturnStmt{
		Results: []goast.Expr{cl},
	}
	fd.Body.List[0] = ret
	t.topLevel.PushBack(fd)

	return fnName
}

func (t *translator) callStructInit(c *semantic.Call) *goast.CallExpr {
	// map of struct labels to field decls
	// TODO: memoize this to optimize codegen a bit
	lblToDecl := make(map[string]*semantic.Var, len(c.InitOf.Vars))
	for _, v := range c.InitOf.Vars {
		lblToDecl[v.Ident()] = v
	}

	// The struct initializer has the signature (where S is the struct type):
	// func init(s S, m map[string]bool) S
	// The map m contains the labels (unmangled field names) set by the caller.
	strName := t.resolver.NameForStructType(semantic.AsStructType(c.Fun.Type()), t.curGenInst)
	ce := &goast.CallExpr{
		Fun:  &goast.Ident{Name: t.resolver.NameForStructInit(strName)},
		Args: make([]goast.Expr, 2),
	}

	// build the struct argument
	strLit := &goast.CompositeLit{
		Type: &goast.Ident{Name: strName},
		Elts: make([]goast.Expr, len(c.Args)),
	}
	for i, arg := range c.Args {
		semantic.Walk(t, arg)
		kve := &goast.KeyValueExpr{
			Key:   &goast.Ident{Name: t.resolver.NameForDecl(lblToDecl[c.Labels[i]])},
			Value: t.generatedExpr,
		}
		strLit.Elts[i] = kve
	}

	// build the map of labels provided
	mapLit := &goast.CompositeLit{
		Type: &goast.MapType{Key: &goast.Ident{Name: "string"}, Value: &goast.Ident{Name: "bool"}},
		Elts: make([]goast.Expr, len(c.Labels)),
	}
	for i, lbl := range c.Labels {
		kve := &goast.KeyValueExpr{
			Key:   &goast.BasicLit{Kind: gotoken.STRING, Value: strconv.Quote(lbl)},
			Value: &goast.Ident{Name: "true"},
		}
		mapLit.Elts[i] = kve
	}

	ce.Args[0] = strLit
	ce.Args[1] = mapLit
	return ce
}

func (t *translator) createStructInit(baseName string, strTyp *semantic.StructType, propInit map[*semantic.Var][]goast.Expr) *goast.FuncDecl {
	// The struct initializer has the signature (where S is the struct type):
	// func init(s S, m map[string]bool) S
	// The map m contains the labels (unmangled field names) set by the caller.

	strTypExpr := t.goTypeExprFor(strTyp)
	// declare the return variable
	ret := &goast.GenDecl{
		Tok: gotoken.VAR,
		Specs: []goast.Spec{
			&goast.ValueSpec{
				Names: []*goast.Ident{{Name: "r"}},
				Type:  strTypExpr,
			},
		},
	}

	// build the statements that make up the body of the function
	stmts := make([]goast.Stmt, 0, len(strTyp.Decl.Vars)*2+1)
	stmts = append(stmts, &goast.DeclStmt{Decl: ret})

	// assign variables with initial values, and overwrite if value was provided
	for _, v := range strTyp.Decl.Vars {
		name := t.resolver.NameForDecl(v)

		if v.Value != nil {
			// assign the initial value for that field
			stmts = append(stmts, &goast.AssignStmt{
				Lhs: []goast.Expr{
					&goast.SelectorExpr{
						X:   &goast.Ident{Name: "r"},
						Sel: &goast.Ident{Name: name},
					},
				},
				Tok: gotoken.ASSIGN,
				Rhs: propInit[v],
			})
		}
		ifs := &goast.IfStmt{
			Cond: &goast.IndexExpr{
				X: &goast.Ident{Name: "m"}, Index: &goast.BasicLit{Kind: gotoken.STRING, Value: strconv.Quote(v.Ident())},
			},
			Body: &goast.BlockStmt{
				List: []goast.Stmt{
					&goast.AssignStmt{
						Lhs: []goast.Expr{&goast.SelectorExpr{X: &goast.Ident{Name: "r"}, Sel: &goast.Ident{Name: name}}},
						Tok: gotoken.ASSIGN,
						Rhs: []goast.Expr{&goast.SelectorExpr{X: &goast.Ident{Name: "s"}, Sel: &goast.Ident{Name: name}}},
					},
				},
			},
		}
		stmts = append(stmts, ifs)
	}

	// return the constructed struct
	stmts = append(stmts, &goast.ReturnStmt{
		Results: []goast.Expr{&goast.Ident{Name: "r"}},
	})

	// create the partial signature type, minus the map as this is not a concept
	// that exists in Snow yet.
	name := t.resolver.NameForStructInit(baseName)
	sig := &semantic.SignatureType{
		Params: []semantic.Type{strTyp},
		Return: strTyp,
	}
	ft := t.goTypeExprFor(sig).(*goast.FuncType)

	// add the second parameter, the map[string]bool of set labels
	ft.Params.List = append(ft.Params.List, &goast.Field{
		Type: &goast.MapType{
			Key: &goast.Ident{Name: "string"}, Value: &goast.Ident{Name: "bool"},
		},
	})

	// set the parameter names
	ft.Params.List[0].Names = []*goast.Ident{{Name: "s"}}
	ft.Params.List[1].Names = []*goast.Ident{{Name: "m"}}

	return &goast.FuncDecl{
		Name: &goast.Ident{Name: name},
		Type: ft,
		Body: &goast.BlockStmt{List: stmts},
	}
}

func (t *translator) renderGenInst(gi *semantic.GenericInst, name string) {
	if t.renderedGenInsts[name] {
		return
	}

	t.renderedGenInsts[name] = true

	decl := gi.GenericDecl.Ref
	gd := decl.(semantic.GenericDecl)
	_, insts := gd.GenInsts()
	types := insts[gi]

	old := t.cloneGenInst(gd.GenClause(), types)
	defer func() { t.curGenInst = old }()

	switch decl := decl.(type) {
	case *semantic.Fn:
		t.createFn(name, decl)
	case *semantic.Struct:
		t.createStruct(name, semantic.AsStructType(gi.Type()))
	case *semantic.Interface:
		t.createInterface(name, semantic.AsInterfaceType(gi.Type()))
	default:
		panic(fmt.Sprintf("invalid generic type to render: %T", decl))
	}
}

func createFuncLit(name string, ft *goast.FuncType, body *goast.BlockStmt) []goast.Node {
	// need to declare first and assign second, so the func can be recursive
	return []goast.Node{
		&goast.DeclStmt{
			Decl: &goast.GenDecl{
				Tok: gotoken.VAR,
				Specs: []goast.Spec{
					&goast.ValueSpec{
						Names: []*goast.Ident{{Name: name}},
						Type:  ft,
					},
				},
			},
		},
		&goast.AssignStmt{
			Lhs: []goast.Expr{&goast.Ident{Name: name}},
			Tok: gotoken.ASSIGN,
			Rhs: []goast.Expr{&goast.FuncLit{Type: ft, Body: body}},
		},
	}
}

func createExternalFnBody(ft *goast.FuncType, imp _import) *goast.BlockStmt {
	pkg := imp.Pkg
	if pkg == "" {
		pkg = filepath.Base(imp.Path)
	}
	ce := &goast.CallExpr{
		Fun: &goast.SelectorExpr{
			X:   &goast.Ident{Name: pkg},
			Sel: &goast.Ident{Name: imp.Symbol},
		},
		Args: make([]goast.Expr, len(ft.Params.List)),
	}
	for i, param := range ft.Params.List {
		ce.Args[i] = &goast.Ident{Name: param.Names[0].Name}
	}

	var stmt goast.Stmt
	if ft.Results != nil {
		stmt = &goast.ReturnStmt{Results: []goast.Expr{ce}}
	} else {
		stmt = &goast.ExprStmt{X: ce}
	}
	return &goast.BlockStmt{List: []goast.Stmt{stmt}}
}

var tokenToGoToken = map[token.Token]gotoken.Token{
	token.Int:    gotoken.INT,
	token.Float:  gotoken.FLOAT,
	token.String: gotoken.STRING,
	token.Add:    gotoken.ADD,
	token.Sub:    gotoken.SUB,
	token.Mul:    gotoken.MUL,
	token.Div:    gotoken.QUO,
	token.Mod:    gotoken.REM,
	token.And:    gotoken.LAND,
	token.Or:     gotoken.LOR,
	token.Eq:     gotoken.EQL,
	token.Lt:     gotoken.LSS,
	token.Gt:     gotoken.GTR,
	token.Assign: gotoken.ASSIGN,
	token.Not:    gotoken.NOT,
	token.NotEq:  gotoken.NEQ,
	token.Lte:    gotoken.LEQ,
	token.Gte:    gotoken.GEQ,
}