~mna/snow unlisted

snow/pkg/semantic/typeassign_pass.go -rw-r--r-- 9.4 KiB
424066c5Martin Angers doc: v0.0.5 1 year, 6 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
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()

	// flag indicating that the Identifier is part of a generic instantiation expression.
	genericInstIdent bool
	// flag indicating that we are visiting the left-hand side of a selector.
	selectorLHS bool
}

func (t *typeassignVisitor) addDeferred(n Node) {
	genericInstIdent := t.genericInstIdent
	selectorLHS := t.selectorLHS
	t.deferred = append(t.deferred, func() {
		t.genericInstIdent = genericInstIdent
		t.selectorLHS = selectorLHS
		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)
		}

		if n.GenericParams != nil {
			for _, elem := range n.GenericParams.Elems {
				Walk(t, elem)
			}
		}
		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.
		// Its ctx (type context) is set during translation pass, based on var or let keyword.
		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:
		st := &StructType{Decl: n}

		if n.GenericParams != nil {
			for _, elem := range n.GenericParams.Elems {
				Walk(t, elem)
			}
		}
		for _, v := range n.Vars {
			Walk(t, v)
		}
		for _, fn := range n.Fns {
			Walk(t, fn)
		}
		for _, str := range n.Structs {
			Walk(t, str)
		}
		n.typ = st

	case *Interface:
		it := &InterfaceType{Decl: n}

		if n.GenericParams != nil {
			for _, elem := range n.GenericParams.Elems {
				Walk(t, elem)
			}
		}
		for _, fn := range n.Methods {
			Walk(t, fn)
		}
		n.typ = it

	case *GenericElem:
		n.typ = &GenericType{
			Name:    n.Ident(),
			ScopeID: n.Scope().ID,
		}

	// ************** 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:
		slhs := t.selectorLHS // flag can be recursive, do not set to false after Walk, set to old value
		t.selectorLHS = true
		Walk(t, n.Left)
		t.selectorLHS = slhs

		// must not call walk on n.Sel, as it will not find the right symbol in
		// the lookup chain - must look in n.Left.
		switch sel := n.Sel.(type) {
		case *Ident:
			t.typeAssignSelector(n.Left.Type(), n.Left.TypeContext(), sel)
		case *GenericInst:
			t.typeAssignSelector(n.Left.Type(), n.Left.TypeContext(), sel.GenericDecl)
			// at this point sel.Type() should be a generic type and sel.Ref a generic decl,
			// now instantiate it.
			t.typeAssignGenericInst(sel)
		}

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

	case *GenericInst:
		t.genericInstIdent = true
		Walk(t, n.GenericDecl)
		t.genericInstIdent = false
		t.typeAssignGenericInst(n)

	case *Ident:
		decl := n.Scope().LookupChain(n.Name, n.Pos())
		if decl == nil {
			t.errUndefined(n, nil)
			break
		}
		if !t.genericInstIdent && !t.selectorLHS && decl.IsGeneric() {
			// cannot access a generic identifier without an instantiation, unless it is used
			// on the left-hand side of a selector to access an inner member.
			t.errh(n.Pos(), "cannot use generic declaration without instantiation")
		}

		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
		}

		if st := AsStructType(typed.Type()); st != nil {
			cloned := &StructType{Decl: st.Decl, Inst: st.Inst, Ctx: typed.TypeContext()}
			typed.setType(cloned)
		}
	}

	return nil
}

// returns the concrete type of an instantiated generic declaration.
func (t *typeassignVisitor) instantiateGeneric(gi *GenericInst, gen GenericDecl, types []Type) Type {
	// make the map of generic type names to actual types
	gc := gen.GenClause()
	resolve := makeGenericResolveMap(gc, types)
	if count := len(types); count < len(gc.Elems) || len(types) > len(gc.Elems) {
		t.errh(gi.Pos(), fmt.Sprintf("wrong number of types provided in generic instantiation, want %d, got %d", len(gc.Elems), len(types)))
	}
	return gen.Instantiate(gi, types, resolve)
}

func (t *typeassignVisitor) typeAssignGenericInst(gi *GenericInst) {
	gi.ctx = Invalid
	gi.typ = unresolvedType{}
	if !gi.GenericDecl.Type().Valid() {
		return
	}
	genRef := gi.GenericDecl.Ref
	if genRef == nil || !genRef.Type().Valid() {
		return
	}
	if !genRef.IsGeneric() {
		t.errh(gi.Pos(), "invalid instantiation of a non-generic declaration")
		return
	}

	types := make([]Type, len(gi.TypeExprs))
	for i, te := range gi.TypeExprs {
		Walk(t, te)
		types[i] = te.Type()
	}

	ctx := genRef.TypeContext()
	switch {
	case ctx == Typ:
		gi.ctx = Typ // instantiated struct / interface generics are types
	case ctx.isAnyOf(TypeContextValues...):
		gi.ctx = Value // instantiated fn generics are values
	}
	gi.typ = t.instantiateGeneric(gi, genRef.(GenericDecl), types)
}

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.

	if tof, ok := left.(typeContainer); ok {
		sel.typ, sel.ctx = tof.typeof(sel, leftCtx)
		if sel.typ == nil {
			t.errUndefined(sel, left)
		}
		return
	}
	sel.ctx = Invalid
	sel.typ = unresolvedType{}
}