~mna/snow

ref: wip-post-ast snow/pkg/semantic/typeassign_pass.go -rw-r--r-- 6.4 KiB
81715ef3Martin Angers pkg/{codegen,semantic}: OMG all codegen tests pass, all is good 2 years 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
package semantic

import (
	"fmt"

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

const maxDeferredLoops = 100

// The typeassign pass sets the types of every expression and declaration in
// the unit. Upon completion, all Expr have a Type and TypeContext, all Decl
// have a Type, and all *Ident have their Ref set if valid.
func typeassign(unit *Unit, errh func(token.Pos, string)) {
	t := &typeassignVisitor{
		errh: errh,
	}
	Walk(t, unit)

	// it is possible that after a pass of deferred nodes, there are *more* deferred
	// nodes, because it unlocked a sub-tree that still can't be resolved. So we
	// cannot stop just by checking if the number of deferred calls diminished or not.
	for i := 0; i < maxDeferredLoops && len(t.deferred) > 0; i++ {
		// run deferred processing to try and resolve unresolved types
		pass := make([]func(), len(t.deferred))
		copy(pass, t.deferred)
		t.deferred = t.deferred[:0]
		for _, fn := range pass {
			fn()
		}
	}
}

type typeassignVisitor struct {
	errh     func(token.Pos, string)
	deferred []func()
}

func (t *typeassignVisitor) addDeferred(n Node) {
	t.deferred = append(t.deferred, func() {
		Walk(t, n)
	})
}

func (t *typeassignVisitor) errUndefined(ident *Ident, in Type) {
	if in != nil {
		t.errh(ident.Pos(), fmt.Sprintf("undefined in %s: %s", in, ident.Name))
	} else {
		t.errh(ident.Pos(), fmt.Sprintf("undefined: %s", ident.Name))
	}
	ident.ctx = Invalid
	ident.typ = unresolvedType{}
}

func (t *typeassignVisitor) Visit(n Node) Visitor {
	switch n := n.(type) {
	case *Unit, *File, *Block, *Return, *Assign, *ExprStmt, *If, *Guard:
		return t

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

	case *Fn:
		sigt := &SignatureType{
			Params: make([]Type, len(n.Params)),
		}
		for _, attr := range n.Attrs {
			Walk(t, attr)
		}
		for i, param := range n.Params {
			Walk(t, param)
			sigt.Params[i] = param.Type()
		}
		if n.ReturnExpr != nil {
			Walk(t, n.ReturnExpr)
			sigt.Return = n.ReturnExpr.Type()
		} else {
			sigt.Return = &BasicType{Kind: Void}
		}
		if n.Body != nil {
			Walk(t, n.Body)
		}
		n.typ = sigt

	case *Var:
		// type of var is either its explicit type or the type of its initialization
		var typ Type = unresolvedType{}
		if n.TypeExpr != nil {
			Walk(t, n.TypeExpr)
			typ = n.TypeExpr.Type()
		}
		if n.Value != nil {
			Walk(t, n.Value)
			if n.TypeExpr == nil {
				typ = n.Value.Type()
			}
		}
		n.typ = typ

	case *Struct:
		n.typ = &StructType{Decl: n}
		for _, v := range n.Vars {
			Walk(t, v)
		}
		for _, fn := range n.Fns {
			Walk(t, fn)
		}
		for _, str := range n.Structs {
			Walk(t, str)
		}

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

	case *FnTypeExpr:
		// build the signature type of this function literal
		sigt := &SignatureType{
			Params: make([]Type, len(n.Params)),
		}
		for i, param := range n.Params {
			Walk(t, param)
			sigt.Params[i] = param.Type()
		}
		if n.Return != nil {
			Walk(t, n.Return)
			sigt.Return = n.Return.Type()
		} else {
			sigt.Return = &BasicType{Kind: Void}
		}
		n.ctx = Typ
		n.typ = sigt

	case *TupleTypeExpr:
		tupt := &TupleType{
			Fields: make([]Type, len(n.Fields)),
		}
		for i, typ := range n.Fields {
			Walk(t, typ)
			tupt.Fields[i] = typ.Type()
		}
		n.ctx = Typ
		n.typ = tupt

	case *TupleVal:
		tupt := &TupleType{
			Fields: make([]Type, len(n.Values)),
		}
		for i, val := range n.Values {
			Walk(t, val)
			tupt.Fields[i] = val.Type()
		}
		n.ctx = Value
		n.typ = tupt

	case *Binary:
		// assign a type to each operand
		Walk(t, n.Left)
		Walk(t, n.Right)

		var newType Type = unresolvedType{}
		lt, rt := AsBasicType(n.Left.Type()), AsBasicType(n.Right.Type())
		if lt != nil && rt != nil {
			kl, kr := lt.Kind, rt.Kind
			if kr < kl {
				kl, kr = kr, kl
			}

			opKind := binaryOpsTable[n.Op][kl][kr]
			if bt := (&BasicType{Kind: opKind}); bt.Valid() {
				newType = bt
			}
		}
		n.ctx = Value
		n.typ = newType

	case *Unary:
		// start with type of operand
		Walk(t, n.Right)
		rt := n.Right.Type()

		// type of unary is the same as long as operand is an allowed type for the
		// operator
		if !IsBasicOfKind(rt, unaryOpsTable[n.Op]...) {
			rt = unresolvedType{}
		}
		n.ctx = Value
		n.typ = rt

	case *Paren:
		// type is that of its value, and context remains the same
		Walk(t, n.Value)
		n.ctx = n.Value.TypeContext()
		n.typ = n.Value.Type()

	case *Call:
		Walk(t, n.Fun)
		for _, arg := range n.Args {
			Walk(t, arg)
		}

		// the type of the call expression is the return type of the signature type
		// of n.Fun, if it is a signature type, or the type of the struct or
		// attribute if it is a struct initializer or func attribute. Otherwise
		// default to unresolved.
		lt := n.Fun.Type()
		n.ctx = Value
		switch lt := lt.(type) {
		case *SignatureType:
			n.typ = lt.Return
		case *StructType:
			n.typ = lt
			n.InitOf = lt.Decl
		default:
			n.typ = unresolvedType{}
		}

	case *Selector:
		Walk(t, n.Left)
		// must not call walk on n.Sel, as it will not find the right symbol in
		// the lookup chain - must look in n.Left.
		t.typeAssignSelector(n.Left.Type(), n.Left.TypeContext(), n.Sel)

		n.ctx = selectorTypeContext[n.Left.TypeContext()][n.Sel.TypeContext()]
		n.typ = n.Sel.Type()

	case *Ident:
		decl := n.Scope().LookupChain(n.Name, n.Pos())
		if decl == nil {
			t.errUndefined(n, nil)
			break
		}
		n.Ref = decl
		n.ctx = decl.TypeContext()
		if n.typ = decl.Type(); n.typ == nil {
			n.typ = unresolvedType{}
		}

	case *LitString:
		n.ctx = Constant
		n.typ = &BasicType{Kind: String}

	case *LitInt:
		n.ctx = Constant
		n.typ = &BasicType{Kind: Int}

	default:
		if n != nil {
			panic(fmt.Sprintf("invalid node type: %T", n))
		}
	}

	if typed, ok := n.(Typed); ok {
		if !typed.Type().Valid() {
			t.addDeferred(n)
		}
	}

	return nil
}

func (t *typeassignVisitor) typeAssignSelector(left Type, leftCtx TypeContext, sel *Ident) {
	// do not add sel as deferred - this is not walked as an Ident, but as part
	// of the Selector expr. If Sel is marked unresolved, then the Selector
	// expression will be unresolved too and will be properly added to deferred.

	switch left := left.(type) {
	case *StructType:
		decl := left.Decl.BodyScope.Lookup(sel.Name)
		if decl != nil {
			sel.ctx = decl.TypeContext()
			sel.typ = decl.Type()
			sel.Ref = decl
			return
		}
		t.errUndefined(sel, left)

	case *TupleType:
		sel.ctx = leftCtx
		if sel.Index < 0 || sel.Index >= len(left.Fields) {
			t.errUndefined(sel, left)
			return
		}
		sel.typ = left.Fields[sel.Index]

	default:
		sel.ctx = Invalid
		sel.typ = unresolvedType{}
	}
}