1package main
2
3import (
4	"bytes"
5	"fmt"
6	"go/ast"
7	"go/token"
8	"io"
9	"reflect"
10	"strings"
11	"sync"
12)
13
14// decl.class
15type decl_class int16
16
17const (
18	decl_invalid = decl_class(-1 + iota)
19
20	// these are in a sorted order
21	decl_const
22	decl_func
23	decl_import
24	decl_package
25	decl_type
26	decl_var
27
28	// this one serves as a temporary type for those methods that were
29	// declared before their actual owner
30	decl_methods_stub
31)
32
33func (this decl_class) String() string {
34	switch this {
35	case decl_invalid:
36		return "PANIC"
37	case decl_const:
38		return "const"
39	case decl_func:
40		return "func"
41	case decl_import:
42		return "import"
43	case decl_package:
44		return "package"
45	case decl_type:
46		return "type"
47	case decl_var:
48		return "var"
49	case decl_methods_stub:
50		return "IF YOU SEE THIS, REPORT A BUG" // :D
51	}
52	panic("unreachable")
53}
54
55// decl.flags
56type decl_flags int16
57
58const (
59	decl_foreign decl_flags = 1 << iota // imported from another package
60
61	// means that the decl is a part of the range statement
62	// its type is inferred in a special way
63	decl_rangevar
64
65	// decl of decl_type class is a type alias
66	decl_alias
67
68	// for preventing infinite recursions and loops in type inference code
69	decl_visited
70)
71
72//-------------------------------------------------------------------------
73// decl
74//
75// The most important data structure of the whole gocode project. It
76// describes a single declaration and its children.
77//-------------------------------------------------------------------------
78
79type decl struct {
80	// Name starts with '$' if the declaration describes an anonymous type.
81	// '$s_%d' for anonymous struct types
82	// '$i_%d' for anonymous interface types
83	name  string
84	typ   ast.Expr
85	class decl_class
86	flags decl_flags
87
88	// functions for interface type, fields+methods for struct type
89	children map[string]*decl
90
91	// embedded types
92	embedded []ast.Expr
93
94	// if the type is unknown at AST building time, I'm using these
95	value ast.Expr
96
97	// if it's a multiassignment and the Value is a CallExpr, it is being set
98	// to an index into the return value tuple, otherwise it's a -1
99	value_index int
100
101	// scope where this Decl was declared in (not its visibilty scope!)
102	// Decl uses it for type inference
103	scope *scope
104}
105
106func ast_decl_type(d ast.Decl) ast.Expr {
107	switch t := d.(type) {
108	case *ast.GenDecl:
109		switch t.Tok {
110		case token.CONST, token.VAR:
111			c := t.Specs[0].(*ast.ValueSpec)
112			return c.Type
113		case token.TYPE:
114			t := t.Specs[0].(*ast.TypeSpec)
115			return t.Type
116		}
117	case *ast.FuncDecl:
118		return t.Type
119	}
120	panic("unreachable")
121}
122
123func ast_decl_flags(d ast.Decl) decl_flags {
124	switch t := d.(type) {
125	case *ast.GenDecl:
126		switch t.Tok {
127		case token.TYPE:
128			if isAliasTypeSpec(t.Specs[0].(*ast.TypeSpec)) {
129				return decl_alias
130			}
131		}
132	}
133	return 0
134}
135
136func ast_decl_class(d ast.Decl) decl_class {
137	switch t := d.(type) {
138	case *ast.GenDecl:
139		switch t.Tok {
140		case token.VAR:
141			return decl_var
142		case token.CONST:
143			return decl_const
144		case token.TYPE:
145			return decl_type
146		}
147	case *ast.FuncDecl:
148		return decl_func
149	}
150	panic("unreachable")
151}
152
153func ast_decl_convertable(d ast.Decl) bool {
154	switch t := d.(type) {
155	case *ast.GenDecl:
156		switch t.Tok {
157		case token.VAR, token.CONST, token.TYPE:
158			return true
159		}
160	case *ast.FuncDecl:
161		return true
162	}
163	return false
164}
165
166func ast_field_list_to_decls(f *ast.FieldList, class decl_class, flags decl_flags, scope *scope, add_anonymous bool) map[string]*decl {
167	count := 0
168	for _, field := range f.List {
169		count += len(field.Names)
170	}
171
172	decls := make(map[string]*decl, count)
173	for _, field := range f.List {
174		for _, name := range field.Names {
175			if flags&decl_foreign != 0 && !ast.IsExported(name.Name) {
176				continue
177			}
178			d := &decl{
179				name:        name.Name,
180				typ:         field.Type,
181				class:       class,
182				flags:       flags,
183				scope:       scope,
184				value_index: -1,
185			}
186			decls[d.name] = d
187		}
188
189		// add anonymous field as a child (type embedding)
190		if class == decl_var && field.Names == nil && add_anonymous {
191			tp := get_type_path(field.Type)
192			if flags&decl_foreign != 0 && !ast.IsExported(tp.name) {
193				continue
194			}
195			d := &decl{
196				name:        tp.name,
197				typ:         field.Type,
198				class:       class,
199				flags:       flags,
200				scope:       scope,
201				value_index: -1,
202			}
203			decls[d.name] = d
204		}
205	}
206	return decls
207}
208
209func ast_field_list_to_embedded(f *ast.FieldList) []ast.Expr {
210	count := 0
211	for _, field := range f.List {
212		if field.Names == nil || field.Names[0].Name == "?" {
213			count++
214		}
215	}
216
217	if count == 0 {
218		return nil
219	}
220
221	embedded := make([]ast.Expr, count)
222	i := 0
223	for _, field := range f.List {
224		if field.Names == nil || field.Names[0].Name == "?" {
225			embedded[i] = field.Type
226			i++
227		}
228	}
229
230	return embedded
231}
232
233func ast_type_to_embedded(ty ast.Expr) []ast.Expr {
234	switch t := ty.(type) {
235	case *ast.StructType:
236		return ast_field_list_to_embedded(t.Fields)
237	case *ast.InterfaceType:
238		return ast_field_list_to_embedded(t.Methods)
239	}
240	return nil
241}
242
243func ast_type_to_children(ty ast.Expr, flags decl_flags, scope *scope) map[string]*decl {
244	switch t := ty.(type) {
245	case *ast.StructType:
246		return ast_field_list_to_decls(t.Fields, decl_var, flags, scope, true)
247	case *ast.InterfaceType:
248		return ast_field_list_to_decls(t.Methods, decl_func, flags, scope, false)
249	}
250	return nil
251}
252
253//-------------------------------------------------------------------------
254// anonymous_id_gen
255//
256// ID generator for anonymous types (thread-safe)
257//-------------------------------------------------------------------------
258
259type anonymous_id_gen struct {
260	sync.Mutex
261	i int
262}
263
264func (a *anonymous_id_gen) gen() (id int) {
265	a.Lock()
266	defer a.Unlock()
267	id = a.i
268	a.i++
269	return
270}
271
272var g_anon_gen anonymous_id_gen
273
274//-------------------------------------------------------------------------
275
276func check_for_anon_type(t ast.Expr, flags decl_flags, s *scope) ast.Expr {
277	if t == nil {
278		return nil
279	}
280	var name string
281
282	switch t.(type) {
283	case *ast.StructType:
284		name = fmt.Sprintf("$s_%d", g_anon_gen.gen())
285	case *ast.InterfaceType:
286		name = fmt.Sprintf("$i_%d", g_anon_gen.gen())
287	}
288
289	if name != "" {
290		anonymify_ast(t, flags, s)
291		d := new_decl_full(name, decl_type, flags, t, nil, -1, s)
292		s.add_named_decl(d)
293		return ast.NewIdent(name)
294	}
295	return t
296}
297
298//-------------------------------------------------------------------------
299
300func new_decl_full(name string, class decl_class, flags decl_flags, typ, v ast.Expr, vi int, s *scope) *decl {
301	if name == "_" {
302		return nil
303	}
304	d := new(decl)
305	d.name = name
306	d.class = class
307	d.flags = flags
308	d.typ = typ
309	d.value = v
310	d.value_index = vi
311	d.scope = s
312	d.children = ast_type_to_children(d.typ, flags, s)
313	d.embedded = ast_type_to_embedded(d.typ)
314	return d
315}
316
317func new_decl(name string, class decl_class, scope *scope) *decl {
318	decl := new(decl)
319	decl.name = name
320	decl.class = class
321	decl.value_index = -1
322	decl.scope = scope
323	return decl
324}
325
326func new_decl_var(name string, typ ast.Expr, value ast.Expr, vindex int, scope *scope) *decl {
327	if name == "_" {
328		return nil
329	}
330	decl := new(decl)
331	decl.name = name
332	decl.class = decl_var
333	decl.typ = typ
334	decl.value = value
335	decl.value_index = vindex
336	decl.scope = scope
337	return decl
338}
339
340func method_of(d ast.Decl) string {
341	if t, ok := d.(*ast.FuncDecl); ok {
342		if t.Recv != nil && len(t.Recv.List) != 0 {
343			switch t := t.Recv.List[0].Type.(type) {
344			case *ast.StarExpr:
345				if se, ok := t.X.(*ast.SelectorExpr); ok {
346					return se.Sel.Name
347				}
348				if ident, ok := t.X.(*ast.Ident); ok {
349					return ident.Name
350				}
351				return ""
352			case *ast.Ident:
353				return t.Name
354			default:
355				return ""
356			}
357		}
358	}
359	return ""
360}
361
362func (other *decl) deep_copy() *decl {
363	d := new(decl)
364	d.name = other.name
365	d.class = other.class
366	d.flags = other.flags
367	d.typ = other.typ
368	d.value = other.value
369	d.value_index = other.value_index
370	d.children = make(map[string]*decl, len(other.children))
371	for key, value := range other.children {
372		d.children[key] = value
373	}
374	if other.embedded != nil {
375		d.embedded = make([]ast.Expr, len(other.embedded))
376		copy(d.embedded, other.embedded)
377	}
378	d.scope = other.scope
379	return d
380}
381
382func (d *decl) is_rangevar() bool {
383	return d.flags&decl_rangevar != 0
384}
385
386func (d *decl) is_alias() bool {
387	return d.flags&decl_alias != 0
388}
389
390func (d *decl) is_visited() bool {
391	return d.flags&decl_visited != 0
392}
393
394func (d *decl) set_visited() {
395	d.flags |= decl_visited
396}
397
398func (d *decl) clear_visited() {
399	d.flags &^= decl_visited
400}
401
402func (d *decl) expand_or_replace(other *decl) {
403	// expand only if it's a methods stub, otherwise simply keep it as is
404	if d.class != decl_methods_stub && other.class != decl_methods_stub {
405		return
406	}
407
408	if d.class == decl_methods_stub {
409		d.typ = other.typ
410		d.class = other.class
411		d.flags = other.flags
412	}
413
414	if other.children != nil {
415		for _, c := range other.children {
416			d.add_child(c)
417		}
418	}
419
420	if other.embedded != nil {
421		d.embedded = other.embedded
422		d.scope = other.scope
423	}
424}
425
426func (d *decl) matches() bool {
427	if strings.HasPrefix(d.name, "$") || d.class == decl_methods_stub {
428		return false
429	}
430	return true
431}
432
433func (d *decl) pretty_print_type(out io.Writer, canonical_aliases map[string]string) {
434	switch d.class {
435	case decl_type:
436		switch d.typ.(type) {
437		case *ast.StructType:
438			// TODO: not used due to anonymify?
439			fmt.Fprintf(out, "struct")
440		case *ast.InterfaceType:
441			// TODO: not used due to anonymify?
442			fmt.Fprintf(out, "interface")
443		default:
444			if d.typ != nil {
445				pretty_print_type_expr(out, d.typ, canonical_aliases)
446			}
447		}
448	case decl_var:
449		if d.typ != nil {
450			pretty_print_type_expr(out, d.typ, canonical_aliases)
451		}
452	case decl_func:
453		pretty_print_type_expr(out, d.typ, canonical_aliases)
454	}
455}
456
457func (d *decl) add_child(cd *decl) {
458	if d.children == nil {
459		d.children = make(map[string]*decl)
460	}
461	d.children[cd.name] = cd
462}
463
464func check_for_builtin_funcs(typ *ast.Ident, c *ast.CallExpr, scope *scope) (ast.Expr, *scope) {
465	if strings.HasPrefix(typ.Name, "func(") {
466		if t, ok := c.Fun.(*ast.Ident); ok {
467			switch t.Name {
468			case "new":
469				if len(c.Args) > 0 {
470					e := new(ast.StarExpr)
471					e.X = c.Args[0]
472					return e, scope
473				}
474			case "make":
475				if len(c.Args) > 0 {
476					return c.Args[0], scope
477				}
478			case "append":
479				if len(c.Args) > 0 {
480					t, scope, _ := infer_type(c.Args[0], scope, -1)
481					return t, scope
482				}
483			case "complex":
484				// TODO: fix it
485				return ast.NewIdent("complex"), g_universe_scope
486			case "closed":
487				return ast.NewIdent("bool"), g_universe_scope
488			case "cap":
489				return ast.NewIdent("int"), g_universe_scope
490			case "copy":
491				return ast.NewIdent("int"), g_universe_scope
492			case "len":
493				return ast.NewIdent("int"), g_universe_scope
494			}
495			// TODO:
496			// func recover() interface{}
497			// func imag(c ComplexType) FloatType
498			// func real(c ComplexType) FloatType
499		}
500	}
501	return nil, nil
502}
503
504func func_return_type(f *ast.FuncType, index int) ast.Expr {
505	if f.Results == nil {
506		return nil
507	}
508
509	if index == -1 {
510		return f.Results.List[0].Type
511	}
512
513	i := 0
514	var field *ast.Field
515	for _, field = range f.Results.List {
516		n := 1
517		if field.Names != nil {
518			n = len(field.Names)
519		}
520		if i <= index && index < i+n {
521			return field.Type
522		}
523		i += n
524	}
525	return nil
526}
527
528type type_path struct {
529	pkg  string
530	name string
531}
532
533func (tp *type_path) is_nil() bool {
534	return tp.pkg == "" && tp.name == ""
535}
536
537// converts type expressions like:
538// ast.Expr
539// *ast.Expr
540// $ast$go/ast.Expr
541// to a path that can be used to lookup a type related Decl
542func get_type_path(e ast.Expr) (r type_path) {
543	if e == nil {
544		return type_path{"", ""}
545	}
546
547	switch t := e.(type) {
548	case *ast.Ident:
549		r.name = t.Name
550	case *ast.StarExpr:
551		r = get_type_path(t.X)
552	case *ast.SelectorExpr:
553		if ident, ok := t.X.(*ast.Ident); ok {
554			r.pkg = ident.Name
555		}
556		r.name = t.Sel.Name
557	}
558	return
559}
560
561func lookup_path(tp type_path, scope *scope) *decl {
562	if tp.is_nil() {
563		return nil
564	}
565	var decl *decl
566	if tp.pkg != "" {
567		decl = scope.lookup(tp.pkg)
568		// return nil early if the package wasn't found but it's part
569		// of the type specification
570		if decl == nil {
571			return nil
572		}
573	}
574
575	if decl != nil {
576		if tp.name != "" {
577			return decl.find_child(tp.name)
578		} else {
579			return decl
580		}
581	}
582
583	return scope.lookup(tp.name)
584}
585
586func lookup_pkg(tp type_path, scope *scope) string {
587	if tp.is_nil() {
588		return ""
589	}
590	if tp.pkg == "" {
591		return ""
592	}
593	decl := scope.lookup(tp.pkg)
594	if decl == nil {
595		return ""
596	}
597	return decl.name
598}
599
600func type_to_decl(t ast.Expr, scope *scope) *decl {
601	if t == nil {
602		//TODO
603		return nil
604	}
605	tp := get_type_path(t)
606	d := lookup_path(tp, scope)
607	if d != nil && d.class == decl_var {
608		// weird variable declaration pointing to itself
609		return nil
610	}
611	return d
612}
613
614func expr_to_decl(e ast.Expr, scope *scope) *decl {
615	t, scope, _ := infer_type(e, scope, -1)
616	return type_to_decl(t, scope)
617}
618
619//-------------------------------------------------------------------------
620// Type inference
621//-------------------------------------------------------------------------
622
623type type_predicate func(ast.Expr) bool
624
625func advance_to_type(pred type_predicate, v ast.Expr, scope *scope) (ast.Expr, *scope) {
626	if pred(v) {
627		return v, scope
628	}
629
630	decl := type_to_decl(v, scope)
631	if decl == nil {
632		return nil, nil
633	}
634
635	if decl.is_visited() {
636		return nil, nil
637	}
638	decl.set_visited()
639	defer decl.clear_visited()
640
641	return advance_to_type(pred, decl.typ, decl.scope)
642}
643
644func advance_to_struct_or_interface(decl *decl) *decl {
645	if decl.is_visited() {
646		return nil
647	}
648	decl.set_visited()
649	defer decl.clear_visited()
650
651	if struct_interface_predicate(decl.typ) {
652		return decl
653	}
654
655	decl = type_to_decl(decl.typ, decl.scope)
656	if decl == nil {
657		return nil
658	}
659	return advance_to_struct_or_interface(decl)
660}
661
662func struct_interface_predicate(v ast.Expr) bool {
663	switch v.(type) {
664	case *ast.StructType, *ast.InterfaceType:
665		return true
666	}
667	return false
668}
669
670func chan_predicate(v ast.Expr) bool {
671	_, ok := v.(*ast.ChanType)
672	return ok
673}
674
675func index_predicate(v ast.Expr) bool {
676	switch v.(type) {
677	case *ast.ArrayType, *ast.MapType, *ast.Ellipsis:
678		return true
679	}
680	return false
681}
682
683func star_predicate(v ast.Expr) bool {
684	_, ok := v.(*ast.StarExpr)
685	return ok
686}
687
688func func_predicate(v ast.Expr) bool {
689	_, ok := v.(*ast.FuncType)
690	return ok
691}
692
693func range_predicate(v ast.Expr) bool {
694	switch t := v.(type) {
695	case *ast.Ident:
696		if t.Name == "string" {
697			return true
698		}
699	case *ast.ArrayType, *ast.MapType, *ast.ChanType, *ast.Ellipsis:
700		return true
701	}
702	return false
703}
704
705type anonymous_typer struct {
706	flags decl_flags
707	scope *scope
708}
709
710func (a *anonymous_typer) Visit(node ast.Node) ast.Visitor {
711	switch t := node.(type) {
712	case *ast.CompositeLit:
713		t.Type = check_for_anon_type(t.Type, a.flags, a.scope)
714	case *ast.MapType:
715		t.Key = check_for_anon_type(t.Key, a.flags, a.scope)
716		t.Value = check_for_anon_type(t.Value, a.flags, a.scope)
717	case *ast.ArrayType:
718		t.Elt = check_for_anon_type(t.Elt, a.flags, a.scope)
719	case *ast.Ellipsis:
720		t.Elt = check_for_anon_type(t.Elt, a.flags, a.scope)
721	case *ast.ChanType:
722		t.Value = check_for_anon_type(t.Value, a.flags, a.scope)
723	case *ast.Field:
724		t.Type = check_for_anon_type(t.Type, a.flags, a.scope)
725	case *ast.CallExpr:
726		t.Fun = check_for_anon_type(t.Fun, a.flags, a.scope)
727	case *ast.ParenExpr:
728		t.X = check_for_anon_type(t.X, a.flags, a.scope)
729	case *ast.StarExpr:
730		t.X = check_for_anon_type(t.X, a.flags, a.scope)
731	case *ast.GenDecl:
732		switch t.Tok {
733		case token.VAR:
734			for _, s := range t.Specs {
735				vs := s.(*ast.ValueSpec)
736				vs.Type = check_for_anon_type(vs.Type, a.flags, a.scope)
737			}
738		case token.TYPE:
739			for _, s := range t.Specs {
740				ts := s.(*ast.TypeSpec)
741				if isAliasTypeSpec(ts) {
742					ts.Type = check_for_anon_type(ts.Type, a.flags, a.scope)
743				}
744			}
745		}
746	}
747	return a
748}
749
750func anonymify_ast(node ast.Node, flags decl_flags, scope *scope) {
751	v := anonymous_typer{flags, scope}
752	ast.Walk(&v, node)
753}
754
755// RETURNS:
756// 	- type expression which represents a full name of a type
757//	- bool whether a type expression is actually a type (used internally)
758//	- scope in which type makes sense
759func infer_type(v ast.Expr, scope *scope, index int) (ast.Expr, *scope, bool) {
760	switch t := v.(type) {
761	case *ast.CompositeLit:
762		return t.Type, scope, true
763	case *ast.Ident:
764		if d := scope.lookup(t.Name); d != nil {
765			if d.class == decl_package {
766				return ast.NewIdent(t.Name), scope, false
767			}
768			//check type, fix bug test.0055
769			if i, ok := d.typ.(*ast.Ident); ok {
770				if i.Obj != nil && i.Obj.Decl != nil {
771					if typ, ok := i.Obj.Decl.(*ast.TypeSpec); ok {
772						if _, ok := typ.Type.(*ast.Ident); ok {
773							return infer_type(typ.Type, scope, -1)
774						}
775					}
776				}
777			}
778			typ, scope := d.infer_type()
779			return typ, scope, d.class == decl_type
780		}
781	case *ast.UnaryExpr:
782		switch t.Op {
783		case token.AND:
784			// &a makes sense only with values, don't even check for type
785			it, s, _ := infer_type(t.X, scope, -1)
786			if it == nil {
787				break
788			}
789
790			e := new(ast.StarExpr)
791			e.X = it
792			return e, s, false
793		case token.ARROW:
794			// <-a makes sense only with values
795			it, s, _ := infer_type(t.X, scope, -1)
796			if it == nil {
797				break
798			}
799			switch index {
800			case -1, 0:
801				it, s = advance_to_type(chan_predicate, it, s)
802				return it.(*ast.ChanType).Value, s, false
803			case 1:
804				// technically it's a value, but in case of index == 1
805				// it is always the last infer operation
806				return ast.NewIdent("bool"), g_universe_scope, false
807			}
808		case token.ADD, token.NOT, token.SUB, token.XOR:
809			it, s, _ := infer_type(t.X, scope, -1)
810			if it == nil {
811				break
812			}
813			return it, s, false
814		}
815	case *ast.BinaryExpr:
816		switch t.Op {
817		case token.EQL, token.NEQ, token.LSS, token.LEQ,
818			token.GTR, token.GEQ, token.LOR, token.LAND:
819			// logic operations, the result is a bool, always
820			return ast.NewIdent("bool"), g_universe_scope, false
821		case token.ADD, token.SUB, token.MUL, token.QUO, token.OR,
822			token.XOR, token.REM, token.AND, token.AND_NOT:
823			// try X, then Y, they should be the same anyway
824			it, s, _ := infer_type(t.X, scope, -1)
825			if it == nil {
826				it, s, _ = infer_type(t.Y, scope, -1)
827				if it == nil {
828					break
829				}
830			}
831			return it, s, false
832		case token.SHL, token.SHR:
833			// try only X for shifts, Y is always uint
834			it, s, _ := infer_type(t.X, scope, -1)
835			if it == nil {
836				break
837			}
838			return it, s, false
839		}
840	case *ast.IndexExpr:
841		// something[another] always returns a value and it works on a value too
842		it, s, _ := infer_type(t.X, scope, -1)
843		if it == nil {
844			break
845		}
846		it, s = advance_to_type(index_predicate, it, s)
847		switch t := it.(type) {
848		case *ast.ArrayType:
849			return t.Elt, s, false
850		case *ast.Ellipsis:
851			return t.Elt, s, false
852		case *ast.MapType:
853			switch index {
854			case -1, 0:
855				return t.Value, s, false
856			case 1:
857				return ast.NewIdent("bool"), g_universe_scope, false
858			}
859		}
860	case *ast.SliceExpr:
861		// something[start : end] always returns a value
862		it, s, _ := infer_type(t.X, scope, -1)
863		if it == nil {
864			break
865		}
866		it, s = advance_to_type(index_predicate, it, s)
867		switch t := it.(type) {
868		case *ast.ArrayType:
869			e := new(ast.ArrayType)
870			e.Elt = t.Elt
871			return e, s, false
872		}
873	case *ast.StarExpr:
874		it, s, is_type := infer_type(t.X, scope, -1)
875		if it == nil {
876			break
877		}
878		if is_type {
879			// if it's a type, add * modifier, make it a 'pointer of' type
880			e := new(ast.StarExpr)
881			e.X = it
882			return e, s, true
883		} else {
884			it, s := advance_to_type(star_predicate, it, s)
885			if se, ok := it.(*ast.StarExpr); ok {
886				return se.X, s, false
887			}
888		}
889	case *ast.CallExpr:
890		// this is a function call or a type cast:
891		// myFunc(1,2,3) or int16(myvar)
892		it, s, is_type := infer_type(t.Fun, scope, -1)
893		if it == nil {
894			break
895		}
896
897		if is_type {
898			// a type cast
899			return it, scope, false
900		} else {
901			// it must be a function call or a built-in function
902			// first check for built-in
903			if ct, ok := it.(*ast.Ident); ok {
904				ty, s := check_for_builtin_funcs(ct, t, scope)
905				if ty != nil {
906					return ty, s, false
907				}
908			}
909
910			// then check for an ordinary function call
911			it, scope = advance_to_type(func_predicate, it, s)
912			if ct, ok := it.(*ast.FuncType); ok {
913				return func_return_type(ct, index), s, false
914			}
915		}
916	case *ast.ParenExpr:
917		it, s, is_type := infer_type(t.X, scope, -1)
918		if it == nil {
919			break
920		}
921		return it, s, is_type
922	case *ast.SelectorExpr:
923		it, s, _ := infer_type(t.X, scope, -1)
924		if it == nil {
925			break
926		}
927		if d := type_to_decl(it, s); d != nil {
928			c := d.find_child_and_in_embedded(t.Sel.Name)
929			if c != nil {
930				if c.class == decl_type {
931					return t, scope, true
932				} else {
933					typ, s := c.infer_type()
934					return typ, s, false
935				}
936			}
937		}
938	case *ast.FuncLit:
939		// it's a value, but I think most likely we don't even care, cause we can only
940		// call it, and CallExpr uses the type itself to figure out
941		return t.Type, scope, false
942	case *ast.TypeAssertExpr:
943		if t.Type == nil {
944			return infer_type(t.X, scope, -1)
945		}
946		switch index {
947		case -1, 0:
948			// converting a value to a different type, but return thing is a value
949			it, _, _ := infer_type(t.Type, scope, -1)
950			return it, scope, false
951		case 1:
952			return ast.NewIdent("bool"), g_universe_scope, false
953		}
954	case *ast.ArrayType, *ast.MapType, *ast.ChanType, *ast.Ellipsis,
955		*ast.FuncType, *ast.StructType, *ast.InterfaceType:
956		return t, scope, true
957	default:
958		_ = reflect.TypeOf(v)
959	}
960	return nil, nil, false
961}
962
963// Uses Value, ValueIndex and Scope to infer the type of this
964// declaration. Returns the type itself and the scope where this type
965// makes sense.
966func (d *decl) infer_type() (ast.Expr, *scope) {
967	// special case for range vars
968	if d.is_rangevar() {
969		var scope *scope
970		d.typ, scope = infer_range_type(d.value, d.scope, d.value_index)
971		return d.typ, scope
972	}
973
974	switch d.class {
975	case decl_package:
976		// package is handled specially in inferType
977		return nil, nil
978	case decl_type:
979		return ast.NewIdent(d.name), d.scope
980	}
981
982	// shortcut
983	if d.typ != nil && d.value == nil {
984		return d.typ, d.scope
985	}
986
987	// prevent loops
988	if d.is_visited() {
989		return nil, nil
990	}
991	d.set_visited()
992	defer d.clear_visited()
993
994	var scope *scope
995	d.typ, scope, _ = infer_type(d.value, d.scope, d.value_index)
996	return d.typ, scope
997}
998
999func (d *decl) type_dealias() *decl {
1000	if d.is_visited() {
1001		return nil
1002	}
1003	d.set_visited()
1004	defer d.clear_visited()
1005
1006	dd := type_to_decl(d.typ, d.scope)
1007	if dd != nil && dd.is_alias() {
1008		return dd.type_dealias()
1009	}
1010	return dd
1011}
1012
1013func (d *decl) find_child(name string) *decl {
1014	// type aliases don't really have any children on their own, but they
1015	// point to a different type, let's try to find one
1016	if d.is_alias() {
1017		dd := d.type_dealias()
1018		if dd != nil {
1019			return dd.find_child(name)
1020		}
1021
1022		// note that type alias can also point to a type literal, something like
1023		// type A = struct { A int }
1024		// in this case we rely on "advance_to_struct_or_interface" below
1025	}
1026
1027	if d.children != nil {
1028		if c, ok := d.children[name]; ok {
1029			return c
1030		}
1031	}
1032
1033	decl := advance_to_struct_or_interface(d)
1034	if decl != nil && decl != d {
1035		if d.is_visited() {
1036			return nil
1037		}
1038		d.set_visited()
1039		defer d.clear_visited()
1040
1041		return decl.find_child(name)
1042	}
1043	return nil
1044}
1045
1046func (d *decl) find_child_and_in_embedded(name string) *decl {
1047	if d == nil {
1048		return nil
1049	}
1050	if d.is_alias() {
1051		if dd := d.type_dealias(); dd != nil {
1052			return dd.find_child_and_in_embedded(name)
1053		}
1054	}
1055
1056	if d.is_visited() {
1057		return nil
1058	}
1059	d.set_visited()
1060	defer d.clear_visited()
1061
1062	c := d.find_child(name)
1063	if c == nil {
1064		for _, e := range d.embedded {
1065			typedecl := type_to_decl(e, d.scope)
1066			c = typedecl.find_child_and_in_embedded(name)
1067			if c != nil {
1068				break
1069			}
1070		}
1071	}
1072	return c
1073}
1074
1075// Special type inference for range statements.
1076// [int], [int] := range [string]
1077// [int], [value] := range [slice or array]
1078// [key], [value] := range [map]
1079// [value], [nil] := range [chan]
1080func infer_range_type(e ast.Expr, sc *scope, valueindex int) (ast.Expr, *scope) {
1081	t, s, _ := infer_type(e, sc, -1)
1082	t, s = advance_to_type(range_predicate, t, s)
1083	if t != nil {
1084		var t1, t2 ast.Expr
1085		var s1, s2 *scope
1086		s1 = s
1087		s2 = s
1088
1089		switch t := t.(type) {
1090		case *ast.Ident:
1091			// string
1092			if t.Name == "string" {
1093				t1 = ast.NewIdent("int")
1094				t2 = ast.NewIdent("rune")
1095				s1 = g_universe_scope
1096				s2 = g_universe_scope
1097			} else {
1098				t1, t2 = nil, nil
1099			}
1100		case *ast.ArrayType:
1101			t1 = ast.NewIdent("int")
1102			s1 = g_universe_scope
1103			t2 = t.Elt
1104		case *ast.Ellipsis:
1105			t1 = ast.NewIdent("int")
1106			s1 = g_universe_scope
1107			t2 = t.Elt
1108		case *ast.MapType:
1109			t1 = t.Key
1110			t2 = t.Value
1111		case *ast.ChanType:
1112			t1 = t.Value
1113			t2 = nil
1114		default:
1115			t1, t2 = nil, nil
1116		}
1117
1118		switch valueindex {
1119		case 0:
1120			return t1, s1
1121		case 1:
1122			return t2, s2
1123		}
1124	}
1125	return nil, nil
1126}
1127
1128//-------------------------------------------------------------------------
1129// Pretty printing
1130//-------------------------------------------------------------------------
1131
1132func get_array_len(e ast.Expr) string {
1133	switch t := e.(type) {
1134	case *ast.BasicLit:
1135		return string(t.Value)
1136	case *ast.Ellipsis:
1137		return "..."
1138	}
1139	return ""
1140}
1141
1142func pretty_print_type_expr(out io.Writer, e ast.Expr, canonical_aliases map[string]string) {
1143	switch t := e.(type) {
1144	case *ast.StarExpr:
1145		fmt.Fprintf(out, "*")
1146		pretty_print_type_expr(out, t.X, canonical_aliases)
1147	case *ast.Ident:
1148		if strings.HasPrefix(t.Name, "$") {
1149			// beautify anonymous types
1150			switch t.Name[1] {
1151			case 's':
1152				fmt.Fprintf(out, "struct")
1153			case 'i':
1154				// ok, in most cases anonymous interface is an
1155				// empty interface, I'll just pretend that
1156				// it's always true
1157				fmt.Fprintf(out, "interface{}")
1158			}
1159		} else if !*g_debug && strings.HasPrefix(t.Name, "!") {
1160			// these are full package names for disambiguating and pretty
1161			// printing packages within packages, e.g.
1162			// !go/ast!ast vs. !github.com/nsf/my/ast!ast
1163			// another ugly hack, if people are punished in hell for ugly hacks
1164			// I'm screwed...
1165			emarkIdx := strings.LastIndex(t.Name, "!")
1166			path := t.Name[1:emarkIdx]
1167			alias := canonical_aliases[path]
1168			if alias == "" {
1169				alias = t.Name[emarkIdx+1:]
1170			}
1171			fmt.Fprintf(out, alias)
1172		} else {
1173			fmt.Fprintf(out, t.Name)
1174		}
1175	case *ast.ArrayType:
1176		al := ""
1177		if t.Len != nil {
1178			al = get_array_len(t.Len)
1179		}
1180		if al != "" {
1181			fmt.Fprintf(out, "[%s]", al)
1182		} else {
1183			fmt.Fprintf(out, "[]")
1184		}
1185		pretty_print_type_expr(out, t.Elt, canonical_aliases)
1186	case *ast.SelectorExpr:
1187		pretty_print_type_expr(out, t.X, canonical_aliases)
1188		fmt.Fprintf(out, ".%s", t.Sel.Name)
1189	case *ast.FuncType:
1190		fmt.Fprintf(out, "func(")
1191		pretty_print_func_field_list(out, t.Params, canonical_aliases)
1192		fmt.Fprintf(out, ")")
1193
1194		buf := bytes.NewBuffer(make([]byte, 0, 256))
1195		nresults := pretty_print_func_field_list(buf, t.Results, canonical_aliases)
1196		if nresults > 0 {
1197			results := buf.String()
1198			if strings.IndexAny(results, ", ") != -1 {
1199				results = "(" + results + ")"
1200			}
1201			fmt.Fprintf(out, " %s", results)
1202		}
1203	case *ast.MapType:
1204		fmt.Fprintf(out, "map[")
1205		pretty_print_type_expr(out, t.Key, canonical_aliases)
1206		fmt.Fprintf(out, "]")
1207		pretty_print_type_expr(out, t.Value, canonical_aliases)
1208	case *ast.InterfaceType:
1209		fmt.Fprintf(out, "interface{}")
1210	case *ast.Ellipsis:
1211		fmt.Fprintf(out, "...")
1212		pretty_print_type_expr(out, t.Elt, canonical_aliases)
1213	case *ast.StructType:
1214		fmt.Fprintf(out, "struct")
1215	case *ast.ChanType:
1216		switch t.Dir {
1217		case ast.RECV:
1218			fmt.Fprintf(out, "<-chan ")
1219		case ast.SEND:
1220			fmt.Fprintf(out, "chan<- ")
1221		case ast.SEND | ast.RECV:
1222			fmt.Fprintf(out, "chan ")
1223		}
1224		pretty_print_type_expr(out, t.Value, canonical_aliases)
1225	case *ast.ParenExpr:
1226		fmt.Fprintf(out, "(")
1227		pretty_print_type_expr(out, t.X, canonical_aliases)
1228		fmt.Fprintf(out, ")")
1229	case *ast.BadExpr:
1230		// TODO: probably I should check that in a separate function
1231		// and simply discard declarations with BadExpr as a part of their
1232		// type
1233	default:
1234		// the element has some weird type, just ignore it
1235	}
1236}
1237
1238func pretty_print_func_field_list(out io.Writer, f *ast.FieldList, canonical_aliases map[string]string) int {
1239	count := 0
1240	if f == nil {
1241		return count
1242	}
1243	for i, field := range f.List {
1244		// names
1245		if field.Names != nil {
1246			hasNonblank := false
1247			for j, name := range field.Names {
1248				if name.Name != "?" {
1249					hasNonblank = true
1250					fmt.Fprintf(out, "%s", name.Name)
1251					if j != len(field.Names)-1 {
1252						fmt.Fprintf(out, ", ")
1253					}
1254				}
1255				count++
1256			}
1257			if hasNonblank {
1258				fmt.Fprintf(out, " ")
1259			}
1260		} else {
1261			count++
1262		}
1263
1264		// type
1265		pretty_print_type_expr(out, field.Type, canonical_aliases)
1266
1267		// ,
1268		if i != len(f.List)-1 {
1269			fmt.Fprintf(out, ", ")
1270		}
1271	}
1272	return count
1273}
1274
1275func ast_decl_names(d ast.Decl) []*ast.Ident {
1276	var names []*ast.Ident
1277
1278	switch t := d.(type) {
1279	case *ast.GenDecl:
1280		switch t.Tok {
1281		case token.CONST:
1282			c := t.Specs[0].(*ast.ValueSpec)
1283			names = make([]*ast.Ident, len(c.Names))
1284			for i, name := range c.Names {
1285				names[i] = name
1286			}
1287		case token.TYPE:
1288			t := t.Specs[0].(*ast.TypeSpec)
1289			names = make([]*ast.Ident, 1)
1290			names[0] = t.Name
1291		case token.VAR:
1292			v := t.Specs[0].(*ast.ValueSpec)
1293			names = make([]*ast.Ident, len(v.Names))
1294			for i, name := range v.Names {
1295				names[i] = name
1296			}
1297		}
1298	case *ast.FuncDecl:
1299		names = make([]*ast.Ident, 1)
1300		names[0] = t.Name
1301	}
1302
1303	return names
1304}
1305
1306func ast_decl_values(d ast.Decl) []ast.Expr {
1307	// TODO: CONST values here too
1308	switch t := d.(type) {
1309	case *ast.GenDecl:
1310		switch t.Tok {
1311		case token.VAR:
1312			v := t.Specs[0].(*ast.ValueSpec)
1313			if v.Values != nil {
1314				return v.Values
1315			}
1316		}
1317	}
1318	return nil
1319}
1320
1321func ast_decl_split(d ast.Decl) []ast.Decl {
1322	var decls []ast.Decl
1323	if t, ok := d.(*ast.GenDecl); ok {
1324		decls = make([]ast.Decl, len(t.Specs))
1325		for i, s := range t.Specs {
1326			decl := new(ast.GenDecl)
1327			*decl = *t
1328			decl.Specs = make([]ast.Spec, 1)
1329			decl.Specs[0] = s
1330			decls[i] = decl
1331		}
1332	} else {
1333		decls = make([]ast.Decl, 1)
1334		decls[0] = d
1335	}
1336	return decls
1337}
1338
1339//-------------------------------------------------------------------------
1340// decl_pack
1341//-------------------------------------------------------------------------
1342
1343type decl_pack struct {
1344	names  []*ast.Ident
1345	typ    ast.Expr
1346	values []ast.Expr
1347}
1348
1349type foreach_decl_struct struct {
1350	decl_pack
1351	decl ast.Decl
1352}
1353
1354func (f *decl_pack) value(i int) ast.Expr {
1355	if f.values == nil {
1356		return nil
1357	}
1358	if len(f.values) > 1 {
1359		return f.values[i]
1360	}
1361	return f.values[0]
1362}
1363
1364func (f *decl_pack) value_index(i int) (v ast.Expr, vi int) {
1365	// default: nil value
1366	v = nil
1367	vi = -1
1368
1369	if f.values != nil {
1370		// A = B, if there is only one name, the value is solo too
1371		if len(f.names) == 1 {
1372			return f.values[0], -1
1373		}
1374
1375		if len(f.values) > 1 {
1376			// in case if there are multiple values, it's a usual
1377			// multiassignment
1378			if i >= len(f.values) {
1379				i = len(f.values) - 1
1380			}
1381			v = f.values[i]
1382		} else {
1383			// in case if there is one value, but many names, it's
1384			// a tuple unpack.. use index here
1385			v = f.values[0]
1386			vi = i
1387		}
1388	}
1389	return
1390}
1391
1392func (f *decl_pack) type_value_index(i int) (ast.Expr, ast.Expr, int) {
1393	if f.typ != nil {
1394		// If there is a type, we don't care about value, just return the type
1395		// and zero value.
1396		return f.typ, nil, -1
1397	}
1398
1399	// And otherwise we simply return nil type and a valid value for later inferring.
1400	v, vi := f.value_index(i)
1401	return nil, v, vi
1402}
1403
1404type foreach_decl_func func(data *foreach_decl_struct)
1405
1406func foreach_decl(decl ast.Decl, do foreach_decl_func) {
1407	decls := ast_decl_split(decl)
1408	var data foreach_decl_struct
1409	for _, decl := range decls {
1410		if !ast_decl_convertable(decl) {
1411			continue
1412		}
1413		data.names = ast_decl_names(decl)
1414		data.typ = ast_decl_type(decl)
1415		data.values = ast_decl_values(decl)
1416		data.decl = decl
1417
1418		do(&data)
1419	}
1420}
1421
1422//-------------------------------------------------------------------------
1423// Built-in declarations
1424//-------------------------------------------------------------------------
1425
1426var g_universe_scope = new_scope(nil)
1427
1428func init() {
1429	builtin := ast.NewIdent("built-in")
1430
1431	add_type := func(name string) {
1432		d := new_decl(name, decl_type, g_universe_scope)
1433		d.typ = builtin
1434		g_universe_scope.add_named_decl(d)
1435	}
1436	add_type("bool")
1437	add_type("byte")
1438	add_type("complex64")
1439	add_type("complex128")
1440	add_type("float32")
1441	add_type("float64")
1442	add_type("int8")
1443	add_type("int16")
1444	add_type("int32")
1445	add_type("int64")
1446	add_type("string")
1447	add_type("uint8")
1448	add_type("uint16")
1449	add_type("uint32")
1450	add_type("uint64")
1451	add_type("int")
1452	add_type("uint")
1453	add_type("uintptr")
1454	add_type("rune")
1455
1456	add_const := func(name string) {
1457		d := new_decl(name, decl_const, g_universe_scope)
1458		d.typ = builtin
1459		g_universe_scope.add_named_decl(d)
1460	}
1461	add_const("true")
1462	add_const("false")
1463	add_const("iota")
1464	add_const("nil")
1465
1466	add_func := func(name, typ string) {
1467		d := new_decl(name, decl_func, g_universe_scope)
1468		d.typ = ast.NewIdent(typ)
1469		g_universe_scope.add_named_decl(d)
1470	}
1471	add_func("append", "func([]type, ...type) []type")
1472	add_func("cap", "func(container) int")
1473	add_func("close", "func(channel)")
1474	add_func("complex", "func(real, imag) complex")
1475	add_func("copy", "func(dst, src)")
1476	add_func("delete", "func(map[typeA]typeB, typeA)")
1477	add_func("imag", "func(complex)")
1478	add_func("len", "func(container) int")
1479	add_func("make", "func(type, len[, cap]) type")
1480	add_func("new", "func(type) *type")
1481	add_func("panic", "func(interface{})")
1482	add_func("print", "func(...interface{})")
1483	add_func("println", "func(...interface{})")
1484	add_func("real", "func(complex)")
1485	add_func("recover", "func() interface{}")
1486
1487	// built-in error interface
1488	d := new_decl("error", decl_type, g_universe_scope)
1489	d.typ = &ast.InterfaceType{}
1490	d.children = make(map[string]*decl)
1491	d.children["Error"] = new_decl("Error", decl_func, g_universe_scope)
1492	d.children["Error"].typ = &ast.FuncType{
1493		Results: &ast.FieldList{
1494			List: []*ast.Field{
1495				{
1496					Type: ast.NewIdent("string"),
1497				},
1498			},
1499		},
1500	}
1501	g_universe_scope.add_named_decl(d)
1502}
1503